64-bit host/cross fixes.
[qemu] / vl.c
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 #include "vl.h"
25
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>
32
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
58
59 #if defined(CONFIG_SLIRP)
60 #include "libslirp.h"
61 #endif
62
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
72
73 #ifdef CONFIG_SDL
74 #ifdef __APPLE__
75 #include <SDL/SDL.h>
76 #endif
77 #endif /* CONFIG_SDL */
78
79 #ifdef CONFIG_COCOA
80 #undef main
81 #define main qemu_main
82 #endif /* CONFIG_COCOA */
83
84 #include "disas.h"
85
86 #include "exec-all.h"
87
88 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
89
90 //#define DEBUG_UNUSED_IOPORT
91 //#define DEBUG_IOPORT
92
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
98
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
106
107 /* XXX: use a two level table to limit memory usage */
108 #define MAX_IOPORTS 65536
109
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 TextConsole *vga_console;
141 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
142 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
143 #ifdef TARGET_I386
144 int win2k_install_hack = 0;
145 #endif
146 int usb_enabled = 0;
147 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
148 USBDevice *vm_usb_hub;
149 static VLANState *first_vlan;
150 int smp_cpus = 1;
151 #if defined(TARGET_SPARC)
152 #define MAX_CPUS 16
153 #elif defined(TARGET_I386)
154 #define MAX_CPUS 255
155 #else
156 #define MAX_CPUS 1
157 #endif
158
159 /***********************************************************/
160 /* x86 ISA bus support */
161
162 target_phys_addr_t isa_mem_base = 0;
163 PicState2 *isa_pic;
164
165 uint32_t default_ioport_readb(void *opaque, uint32_t address)
166 {
167 #ifdef DEBUG_UNUSED_IOPORT
168     fprintf(stderr, "inb: port=0x%04x\n", address);
169 #endif
170     return 0xff;
171 }
172
173 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
174 {
175 #ifdef DEBUG_UNUSED_IOPORT
176     fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
177 #endif
178 }
179
180 /* default is to make two byte accesses */
181 uint32_t default_ioport_readw(void *opaque, uint32_t address)
182 {
183     uint32_t data;
184     data = ioport_read_table[0][address](ioport_opaque[address], address);
185     address = (address + 1) & (MAX_IOPORTS - 1);
186     data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
187     return data;
188 }
189
190 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
191 {
192     ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
193     address = (address + 1) & (MAX_IOPORTS - 1);
194     ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
195 }
196
197 uint32_t default_ioport_readl(void *opaque, uint32_t address)
198 {
199 #ifdef DEBUG_UNUSED_IOPORT
200     fprintf(stderr, "inl: port=0x%04x\n", address);
201 #endif
202     return 0xffffffff;
203 }
204
205 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
206 {
207 #ifdef DEBUG_UNUSED_IOPORT
208     fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
209 #endif
210 }
211
212 void init_ioports(void)
213 {
214     int i;
215
216     for(i = 0; i < MAX_IOPORTS; i++) {
217         ioport_read_table[0][i] = default_ioport_readb;
218         ioport_write_table[0][i] = default_ioport_writeb;
219         ioport_read_table[1][i] = default_ioport_readw;
220         ioport_write_table[1][i] = default_ioport_writew;
221         ioport_read_table[2][i] = default_ioport_readl;
222         ioport_write_table[2][i] = default_ioport_writel;
223     }
224 }
225
226 /* size is the word size in byte */
227 int register_ioport_read(int start, int length, int size, 
228                          IOPortReadFunc *func, void *opaque)
229 {
230     int i, bsize;
231
232     if (size == 1) {
233         bsize = 0;
234     } else if (size == 2) {
235         bsize = 1;
236     } else if (size == 4) {
237         bsize = 2;
238     } else {
239         hw_error("register_ioport_read: invalid size");
240         return -1;
241     }
242     for(i = start; i < start + length; i += size) {
243         ioport_read_table[bsize][i] = func;
244         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
245             hw_error("register_ioport_read: invalid opaque");
246         ioport_opaque[i] = opaque;
247     }
248     return 0;
249 }
250
251 /* size is the word size in byte */
252 int register_ioport_write(int start, int length, int size, 
253                           IOPortWriteFunc *func, void *opaque)
254 {
255     int i, bsize;
256
257     if (size == 1) {
258         bsize = 0;
259     } else if (size == 2) {
260         bsize = 1;
261     } else if (size == 4) {
262         bsize = 2;
263     } else {
264         hw_error("register_ioport_write: invalid size");
265         return -1;
266     }
267     for(i = start; i < start + length; i += size) {
268         ioport_write_table[bsize][i] = func;
269         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
270             hw_error("register_ioport_read: invalid opaque");
271         ioport_opaque[i] = opaque;
272     }
273     return 0;
274 }
275
276 void isa_unassign_ioport(int start, int length)
277 {
278     int i;
279
280     for(i = start; i < start + length; i++) {
281         ioport_read_table[0][i] = default_ioport_readb;
282         ioport_read_table[1][i] = default_ioport_readw;
283         ioport_read_table[2][i] = default_ioport_readl;
284
285         ioport_write_table[0][i] = default_ioport_writeb;
286         ioport_write_table[1][i] = default_ioport_writew;
287         ioport_write_table[2][i] = default_ioport_writel;
288     }
289 }
290
291 /***********************************************************/
292
293 void pstrcpy(char *buf, int buf_size, const char *str)
294 {
295     int c;
296     char *q = buf;
297
298     if (buf_size <= 0)
299         return;
300
301     for(;;) {
302         c = *str++;
303         if (c == 0 || q >= buf + buf_size - 1)
304             break;
305         *q++ = c;
306     }
307     *q = '\0';
308 }
309
310 /* strcat and truncate. */
311 char *pstrcat(char *buf, int buf_size, const char *s)
312 {
313     int len;
314     len = strlen(buf);
315     if (len < buf_size) 
316         pstrcpy(buf + len, buf_size - len, s);
317     return buf;
318 }
319
320 int strstart(const char *str, const char *val, const char **ptr)
321 {
322     const char *p, *q;
323     p = str;
324     q = val;
325     while (*q != '\0') {
326         if (*p != *q)
327             return 0;
328         p++;
329         q++;
330     }
331     if (ptr)
332         *ptr = p;
333     return 1;
334 }
335
336 /* return the size or -1 if error */
337 int get_image_size(const char *filename)
338 {
339     int fd, size;
340     fd = open(filename, O_RDONLY | O_BINARY);
341     if (fd < 0)
342         return -1;
343     size = lseek(fd, 0, SEEK_END);
344     close(fd);
345     return size;
346 }
347
348 /* return the size or -1 if error */
349 int load_image(const char *filename, uint8_t *addr)
350 {
351     int fd, size;
352     fd = open(filename, O_RDONLY | O_BINARY);
353     if (fd < 0)
354         return -1;
355     size = lseek(fd, 0, SEEK_END);
356     lseek(fd, 0, SEEK_SET);
357     if (read(fd, addr, size) != size) {
358         close(fd);
359         return -1;
360     }
361     close(fd);
362     return size;
363 }
364
365 void cpu_outb(CPUState *env, int addr, int val)
366 {
367 #ifdef DEBUG_IOPORT
368     if (loglevel & CPU_LOG_IOPORT)
369         fprintf(logfile, "outb: %04x %02x\n", addr, val);
370 #endif    
371     ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
372 }
373
374 void cpu_outw(CPUState *env, int addr, int val)
375 {
376 #ifdef DEBUG_IOPORT
377     if (loglevel & CPU_LOG_IOPORT)
378         fprintf(logfile, "outw: %04x %04x\n", addr, val);
379 #endif    
380     ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
381 }
382
383 void cpu_outl(CPUState *env, int addr, int val)
384 {
385 #ifdef DEBUG_IOPORT
386     if (loglevel & CPU_LOG_IOPORT)
387         fprintf(logfile, "outl: %04x %08x\n", addr, val);
388 #endif
389     ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
390 }
391
392 int cpu_inb(CPUState *env, int addr)
393 {
394     int val;
395     val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
396 #ifdef DEBUG_IOPORT
397     if (loglevel & CPU_LOG_IOPORT)
398         fprintf(logfile, "inb : %04x %02x\n", addr, val);
399 #endif
400     return val;
401 }
402
403 int cpu_inw(CPUState *env, int addr)
404 {
405     int val;
406     val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
407 #ifdef DEBUG_IOPORT
408     if (loglevel & CPU_LOG_IOPORT)
409         fprintf(logfile, "inw : %04x %04x\n", addr, val);
410 #endif
411     return val;
412 }
413
414 int cpu_inl(CPUState *env, int addr)
415 {
416     int val;
417     val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
418 #ifdef DEBUG_IOPORT
419     if (loglevel & CPU_LOG_IOPORT)
420         fprintf(logfile, "inl : %04x %08x\n", addr, val);
421 #endif
422     return val;
423 }
424
425 /***********************************************************/
426 void hw_error(const char *fmt, ...)
427 {
428     va_list ap;
429     CPUState *env;
430
431     va_start(ap, fmt);
432     fprintf(stderr, "qemu: hardware error: ");
433     vfprintf(stderr, fmt, ap);
434     fprintf(stderr, "\n");
435     for(env = first_cpu; env != NULL; env = env->next_cpu) {
436         fprintf(stderr, "CPU #%d:\n", env->cpu_index);
437 #ifdef TARGET_I386
438         cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
439 #else
440         cpu_dump_state(env, stderr, fprintf, 0);
441 #endif
442     }
443     va_end(ap);
444     abort();
445 }
446
447 /***********************************************************/
448 /* keyboard/mouse */
449
450 static QEMUPutKBDEvent *qemu_put_kbd_event;
451 static void *qemu_put_kbd_event_opaque;
452 static QEMUPutMouseEvent *qemu_put_mouse_event;
453 static void *qemu_put_mouse_event_opaque;
454
455 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
456 {
457     qemu_put_kbd_event_opaque = opaque;
458     qemu_put_kbd_event = func;
459 }
460
461 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
462 {
463     qemu_put_mouse_event_opaque = opaque;
464     qemu_put_mouse_event = func;
465 }
466
467 void kbd_put_keycode(int keycode)
468 {
469     if (qemu_put_kbd_event) {
470         qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
471     }
472 }
473
474 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
475 {
476     if (qemu_put_mouse_event) {
477         qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
478                              dx, dy, dz, buttons_state);
479     }
480 }
481
482 /***********************************************************/
483 /* timers */
484
485 #if defined(__powerpc__)
486
487 static inline uint32_t get_tbl(void) 
488 {
489     uint32_t tbl;
490     asm volatile("mftb %0" : "=r" (tbl));
491     return tbl;
492 }
493
494 static inline uint32_t get_tbu(void) 
495 {
496         uint32_t tbl;
497         asm volatile("mftbu %0" : "=r" (tbl));
498         return tbl;
499 }
500
501 int64_t cpu_get_real_ticks(void)
502 {
503     uint32_t l, h, h1;
504     /* NOTE: we test if wrapping has occurred */
505     do {
506         h = get_tbu();
507         l = get_tbl();
508         h1 = get_tbu();
509     } while (h != h1);
510     return ((int64_t)h << 32) | l;
511 }
512
513 #elif defined(__i386__)
514
515 int64_t cpu_get_real_ticks(void)
516 {
517     int64_t val;
518     asm volatile ("rdtsc" : "=A" (val));
519     return val;
520 }
521
522 #elif defined(__x86_64__)
523
524 int64_t cpu_get_real_ticks(void)
525 {
526     uint32_t low,high;
527     int64_t val;
528     asm volatile("rdtsc" : "=a" (low), "=d" (high));
529     val = high;
530     val <<= 32;
531     val |= low;
532     return val;
533 }
534
535 #elif defined(__ia64)
536
537 int64_t cpu_get_real_ticks(void)
538 {
539         int64_t val;
540         asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
541         return val;
542 }
543
544 #elif defined(__s390__)
545
546 int64_t cpu_get_real_ticks(void)
547 {
548     int64_t val;
549     asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
550     return val;
551 }
552
553 #else
554 #error unsupported CPU
555 #endif
556
557 static int64_t cpu_ticks_offset;
558 static int cpu_ticks_enabled;
559
560 static inline int64_t cpu_get_ticks(void)
561 {
562     if (!cpu_ticks_enabled) {
563         return cpu_ticks_offset;
564     } else {
565         return cpu_get_real_ticks() + cpu_ticks_offset;
566     }
567 }
568
569 /* enable cpu_get_ticks() */
570 void cpu_enable_ticks(void)
571 {
572     if (!cpu_ticks_enabled) {
573         cpu_ticks_offset -= cpu_get_real_ticks();
574         cpu_ticks_enabled = 1;
575     }
576 }
577
578 /* disable cpu_get_ticks() : the clock is stopped. You must not call
579    cpu_get_ticks() after that.  */
580 void cpu_disable_ticks(void)
581 {
582     if (cpu_ticks_enabled) {
583         cpu_ticks_offset = cpu_get_ticks();
584         cpu_ticks_enabled = 0;
585     }
586 }
587
588 static int64_t get_clock(void)
589 {
590 #ifdef _WIN32
591     struct _timeb tb;
592     _ftime(&tb);
593     return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
594 #else
595     struct timeval tv;
596     gettimeofday(&tv, NULL);
597     return tv.tv_sec * 1000000LL + tv.tv_usec;
598 #endif
599 }
600
601 void cpu_calibrate_ticks(void)
602 {
603     int64_t usec, ticks;
604
605     usec = get_clock();
606     ticks = cpu_get_real_ticks();
607 #ifdef _WIN32
608     Sleep(50);
609 #else
610     usleep(50 * 1000);
611 #endif
612     usec = get_clock() - usec;
613     ticks = cpu_get_real_ticks() - ticks;
614     ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
615 }
616
617 /* compute with 96 bit intermediate result: (a*b)/c */
618 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
619 {
620     union {
621         uint64_t ll;
622         struct {
623 #ifdef WORDS_BIGENDIAN
624             uint32_t high, low;
625 #else
626             uint32_t low, high;
627 #endif            
628         } l;
629     } u, res;
630     uint64_t rl, rh;
631
632     u.ll = a;
633     rl = (uint64_t)u.l.low * (uint64_t)b;
634     rh = (uint64_t)u.l.high * (uint64_t)b;
635     rh += (rl >> 32);
636     res.l.high = rh / c;
637     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
638     return res.ll;
639 }
640
641 #define QEMU_TIMER_REALTIME 0
642 #define QEMU_TIMER_VIRTUAL  1
643
644 struct QEMUClock {
645     int type;
646     /* XXX: add frequency */
647 };
648
649 struct QEMUTimer {
650     QEMUClock *clock;
651     int64_t expire_time;
652     QEMUTimerCB *cb;
653     void *opaque;
654     struct QEMUTimer *next;
655 };
656
657 QEMUClock *rt_clock;
658 QEMUClock *vm_clock;
659
660 static QEMUTimer *active_timers[2];
661 #ifdef _WIN32
662 static MMRESULT timerID;
663 #else
664 /* frequency of the times() clock tick */
665 static int timer_freq;
666 #endif
667
668 QEMUClock *qemu_new_clock(int type)
669 {
670     QEMUClock *clock;
671     clock = qemu_mallocz(sizeof(QEMUClock));
672     if (!clock)
673         return NULL;
674     clock->type = type;
675     return clock;
676 }
677
678 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
679 {
680     QEMUTimer *ts;
681
682     ts = qemu_mallocz(sizeof(QEMUTimer));
683     ts->clock = clock;
684     ts->cb = cb;
685     ts->opaque = opaque;
686     return ts;
687 }
688
689 void qemu_free_timer(QEMUTimer *ts)
690 {
691     qemu_free(ts);
692 }
693
694 /* stop a timer, but do not dealloc it */
695 void qemu_del_timer(QEMUTimer *ts)
696 {
697     QEMUTimer **pt, *t;
698
699     /* NOTE: this code must be signal safe because
700        qemu_timer_expired() can be called from a signal. */
701     pt = &active_timers[ts->clock->type];
702     for(;;) {
703         t = *pt;
704         if (!t)
705             break;
706         if (t == ts) {
707             *pt = t->next;
708             break;
709         }
710         pt = &t->next;
711     }
712 }
713
714 /* modify the current timer so that it will be fired when current_time
715    >= expire_time. The corresponding callback will be called. */
716 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
717 {
718     QEMUTimer **pt, *t;
719
720     qemu_del_timer(ts);
721
722     /* add the timer in the sorted list */
723     /* NOTE: this code must be signal safe because
724        qemu_timer_expired() can be called from a signal. */
725     pt = &active_timers[ts->clock->type];
726     for(;;) {
727         t = *pt;
728         if (!t)
729             break;
730         if (t->expire_time > expire_time) 
731             break;
732         pt = &t->next;
733     }
734     ts->expire_time = expire_time;
735     ts->next = *pt;
736     *pt = ts;
737 }
738
739 int qemu_timer_pending(QEMUTimer *ts)
740 {
741     QEMUTimer *t;
742     for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
743         if (t == ts)
744             return 1;
745     }
746     return 0;
747 }
748
749 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
750 {
751     if (!timer_head)
752         return 0;
753     return (timer_head->expire_time <= current_time);
754 }
755
756 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
757 {
758     QEMUTimer *ts;
759     
760     for(;;) {
761         ts = *ptimer_head;
762         if (!ts || ts->expire_time > current_time)
763             break;
764         /* remove timer from the list before calling the callback */
765         *ptimer_head = ts->next;
766         ts->next = NULL;
767         
768         /* run the callback (the timer list can be modified) */
769         ts->cb(ts->opaque);
770     }
771 }
772
773 int64_t qemu_get_clock(QEMUClock *clock)
774 {
775     switch(clock->type) {
776     case QEMU_TIMER_REALTIME:
777 #ifdef _WIN32
778         return GetTickCount();
779 #else
780         {
781             struct tms tp;
782
783             /* Note that using gettimeofday() is not a good solution
784                for timers because its value change when the date is
785                modified. */
786             if (timer_freq == 100) {
787                 return times(&tp) * 10;
788             } else {
789                 return ((int64_t)times(&tp) * 1000) / timer_freq;
790             }
791         }
792 #endif
793     default:
794     case QEMU_TIMER_VIRTUAL:
795         return cpu_get_ticks();
796     }
797 }
798
799 /* save a timer */
800 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
801 {
802     uint64_t expire_time;
803
804     if (qemu_timer_pending(ts)) {
805         expire_time = ts->expire_time;
806     } else {
807         expire_time = -1;
808     }
809     qemu_put_be64(f, expire_time);
810 }
811
812 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
813 {
814     uint64_t expire_time;
815
816     expire_time = qemu_get_be64(f);
817     if (expire_time != -1) {
818         qemu_mod_timer(ts, expire_time);
819     } else {
820         qemu_del_timer(ts);
821     }
822 }
823
824 static void timer_save(QEMUFile *f, void *opaque)
825 {
826     if (cpu_ticks_enabled) {
827         hw_error("cannot save state if virtual timers are running");
828     }
829     qemu_put_be64s(f, &cpu_ticks_offset);
830     qemu_put_be64s(f, &ticks_per_sec);
831 }
832
833 static int timer_load(QEMUFile *f, void *opaque, int version_id)
834 {
835     if (version_id != 1)
836         return -EINVAL;
837     if (cpu_ticks_enabled) {
838         return -EINVAL;
839     }
840     qemu_get_be64s(f, &cpu_ticks_offset);
841     qemu_get_be64s(f, &ticks_per_sec);
842     return 0;
843 }
844
845 #ifdef _WIN32
846 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
847                                  DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
848 #else
849 static void host_alarm_handler(int host_signum)
850 #endif
851 {
852 #if 0
853 #define DISP_FREQ 1000
854     {
855         static int64_t delta_min = INT64_MAX;
856         static int64_t delta_max, delta_cum, last_clock, delta, ti;
857         static int count;
858         ti = qemu_get_clock(vm_clock);
859         if (last_clock != 0) {
860             delta = ti - last_clock;
861             if (delta < delta_min)
862                 delta_min = delta;
863             if (delta > delta_max)
864                 delta_max = delta;
865             delta_cum += delta;
866             if (++count == DISP_FREQ) {
867                 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
868                        muldiv64(delta_min, 1000000, ticks_per_sec),
869                        muldiv64(delta_max, 1000000, ticks_per_sec),
870                        muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
871                        (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
872                 count = 0;
873                 delta_min = INT64_MAX;
874                 delta_max = 0;
875                 delta_cum = 0;
876             }
877         }
878         last_clock = ti;
879     }
880 #endif
881     if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
882                            qemu_get_clock(vm_clock)) ||
883         qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
884                            qemu_get_clock(rt_clock))) {
885         CPUState *env = cpu_single_env;
886         if (env) {
887             /* stop the currently executing cpu because a timer occured */
888             cpu_interrupt(env, CPU_INTERRUPT_EXIT);
889 #ifdef USE_KQEMU
890             if (env->kqemu_enabled) {
891                 kqemu_cpu_interrupt(env);
892             }
893 #endif
894         }
895     }
896 }
897
898 #ifndef _WIN32
899
900 #if defined(__linux__)
901
902 #define RTC_FREQ 1024
903
904 static int rtc_fd;
905
906 static int start_rtc_timer(void)
907 {
908     rtc_fd = open("/dev/rtc", O_RDONLY);
909     if (rtc_fd < 0)
910         return -1;
911     if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
912         fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
913                 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
914                 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
915         goto fail;
916     }
917     if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
918     fail:
919         close(rtc_fd);
920         return -1;
921     }
922     pit_min_timer_count = PIT_FREQ / RTC_FREQ;
923     return 0;
924 }
925
926 #else
927
928 static int start_rtc_timer(void)
929 {
930     return -1;
931 }
932
933 #endif /* !defined(__linux__) */
934
935 #endif /* !defined(_WIN32) */
936
937 static void init_timers(void)
938 {
939     rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
940     vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
941
942 #ifdef _WIN32
943     {
944         int count=0;
945         timerID = timeSetEvent(1,     // interval (ms)
946                                0,     // resolution
947                                host_alarm_handler, // function
948                                (DWORD)&count,  // user parameter
949                                TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
950         if( !timerID ) {
951             perror("failed timer alarm");
952             exit(1);
953         }
954     }
955     pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
956 #else
957     {
958         struct sigaction act;
959         struct itimerval itv;
960         
961         /* get times() syscall frequency */
962         timer_freq = sysconf(_SC_CLK_TCK);
963         
964         /* timer signal */
965         sigfillset(&act.sa_mask);
966        act.sa_flags = 0;
967 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
968         act.sa_flags |= SA_ONSTACK;
969 #endif
970         act.sa_handler = host_alarm_handler;
971         sigaction(SIGALRM, &act, NULL);
972
973         itv.it_interval.tv_sec = 0;
974         itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
975         itv.it_value.tv_sec = 0;
976         itv.it_value.tv_usec = 10 * 1000;
977         setitimer(ITIMER_REAL, &itv, NULL);
978         /* we probe the tick duration of the kernel to inform the user if
979            the emulated kernel requested a too high timer frequency */
980         getitimer(ITIMER_REAL, &itv);
981
982 #if defined(__linux__)
983         if (itv.it_interval.tv_usec > 1000) {
984             /* try to use /dev/rtc to have a faster timer */
985             if (start_rtc_timer() < 0)
986                 goto use_itimer;
987             /* disable itimer */
988             itv.it_interval.tv_sec = 0;
989             itv.it_interval.tv_usec = 0;
990             itv.it_value.tv_sec = 0;
991             itv.it_value.tv_usec = 0;
992             setitimer(ITIMER_REAL, &itv, NULL);
993
994             /* use the RTC */
995             sigaction(SIGIO, &act, NULL);
996             fcntl(rtc_fd, F_SETFL, O_ASYNC);
997             fcntl(rtc_fd, F_SETOWN, getpid());
998         } else 
999 #endif /* defined(__linux__) */
1000         {
1001         use_itimer:
1002             pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1003                                    PIT_FREQ) / 1000000;
1004         }
1005     }
1006 #endif
1007 }
1008
1009 void quit_timers(void)
1010 {
1011 #ifdef _WIN32
1012     timeKillEvent(timerID);
1013 #endif
1014 }
1015
1016 /***********************************************************/
1017 /* character device */
1018
1019 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1020 {
1021     return s->chr_write(s, buf, len);
1022 }
1023
1024 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1025 {
1026     if (!s->chr_ioctl)
1027         return -ENOTSUP;
1028     return s->chr_ioctl(s, cmd, arg);
1029 }
1030
1031 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1032 {
1033     char buf[4096];
1034     va_list ap;
1035     va_start(ap, fmt);
1036     vsnprintf(buf, sizeof(buf), fmt, ap);
1037     qemu_chr_write(s, buf, strlen(buf));
1038     va_end(ap);
1039 }
1040
1041 void qemu_chr_send_event(CharDriverState *s, int event)
1042 {
1043     if (s->chr_send_event)
1044         s->chr_send_event(s, event);
1045 }
1046
1047 void qemu_chr_add_read_handler(CharDriverState *s, 
1048                                IOCanRWHandler *fd_can_read, 
1049                                IOReadHandler *fd_read, void *opaque)
1050 {
1051     s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1052 }
1053              
1054 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1055 {
1056     s->chr_event = chr_event;
1057 }
1058
1059 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1060 {
1061     return len;
1062 }
1063
1064 static void null_chr_add_read_handler(CharDriverState *chr, 
1065                                     IOCanRWHandler *fd_can_read, 
1066                                     IOReadHandler *fd_read, void *opaque)
1067 {
1068 }
1069
1070 CharDriverState *qemu_chr_open_null(void)
1071 {
1072     CharDriverState *chr;
1073
1074     chr = qemu_mallocz(sizeof(CharDriverState));
1075     if (!chr)
1076         return NULL;
1077     chr->chr_write = null_chr_write;
1078     chr->chr_add_read_handler = null_chr_add_read_handler;
1079     return chr;
1080 }
1081
1082 #ifdef _WIN32
1083
1084 #define socket_error() WSAGetLastError()
1085 #undef EINTR
1086 #define EWOULDBLOCK WSAEWOULDBLOCK
1087 #define EINTR       WSAEINTR
1088 #define EINPROGRESS WSAEINPROGRESS
1089
1090 static void socket_cleanup(void)
1091 {
1092     WSACleanup();
1093 }
1094
1095 static int socket_init(void)
1096 {
1097     WSADATA Data;
1098     int ret, err;
1099
1100     ret = WSAStartup(MAKEWORD(2,2), &Data);
1101     if (ret != 0) {
1102         err = WSAGetLastError();
1103         fprintf(stderr, "WSAStartup: %d\n", err);
1104         return -1;
1105     }
1106     atexit(socket_cleanup);
1107     return 0;
1108 }
1109
1110 static int send_all(int fd, const uint8_t *buf, int len1)
1111 {
1112     int ret, len;
1113     
1114     len = len1;
1115     while (len > 0) {
1116         ret = send(fd, buf, len, 0);
1117         if (ret < 0) {
1118             int errno;
1119             errno = WSAGetLastError();
1120             if (errno != WSAEWOULDBLOCK) {
1121                 return -1;
1122             }
1123         } else if (ret == 0) {
1124             break;
1125         } else {
1126             buf += ret;
1127             len -= ret;
1128         }
1129     }
1130     return len1 - len;
1131 }
1132
1133 void socket_set_nonblock(int fd)
1134 {
1135     unsigned long opt = 1;
1136     ioctlsocket(fd, FIONBIO, &opt);
1137 }
1138
1139 #else
1140
1141 #define socket_error() errno
1142 #define closesocket(s) close(s)
1143
1144 static int unix_write(int fd, const uint8_t *buf, int len1)
1145 {
1146     int ret, len;
1147
1148     len = len1;
1149     while (len > 0) {
1150         ret = write(fd, buf, len);
1151         if (ret < 0) {
1152             if (errno != EINTR && errno != EAGAIN)
1153                 return -1;
1154         } else if (ret == 0) {
1155             break;
1156         } else {
1157             buf += ret;
1158             len -= ret;
1159         }
1160     }
1161     return len1 - len;
1162 }
1163
1164 static inline int send_all(int fd, const uint8_t *buf, int len1)
1165 {
1166     return unix_write(fd, buf, len1);
1167 }
1168
1169 void socket_set_nonblock(int fd)
1170 {
1171     fcntl(fd, F_SETFL, O_NONBLOCK);
1172 }
1173 #endif /* !_WIN32 */
1174
1175 #ifndef _WIN32
1176
1177 typedef struct {
1178     int fd_in, fd_out;
1179     IOCanRWHandler *fd_can_read; 
1180     IOReadHandler *fd_read;
1181     void *fd_opaque;
1182     int max_size;
1183 } FDCharDriver;
1184
1185 #define STDIO_MAX_CLIENTS 2
1186
1187 static int stdio_nb_clients;
1188 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1189
1190 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1191 {
1192     FDCharDriver *s = chr->opaque;
1193     return unix_write(s->fd_out, buf, len);
1194 }
1195
1196 static int fd_chr_read_poll(void *opaque)
1197 {
1198     CharDriverState *chr = opaque;
1199     FDCharDriver *s = chr->opaque;
1200
1201     s->max_size = s->fd_can_read(s->fd_opaque);
1202     return s->max_size;
1203 }
1204
1205 static void fd_chr_read(void *opaque)
1206 {
1207     CharDriverState *chr = opaque;
1208     FDCharDriver *s = chr->opaque;
1209     int size, len;
1210     uint8_t buf[1024];
1211     
1212     len = sizeof(buf);
1213     if (len > s->max_size)
1214         len = s->max_size;
1215     if (len == 0)
1216         return;
1217     size = read(s->fd_in, buf, len);
1218     if (size > 0) {
1219         s->fd_read(s->fd_opaque, buf, size);
1220     }
1221 }
1222
1223 static void fd_chr_add_read_handler(CharDriverState *chr, 
1224                                     IOCanRWHandler *fd_can_read, 
1225                                     IOReadHandler *fd_read, void *opaque)
1226 {
1227     FDCharDriver *s = chr->opaque;
1228
1229     if (s->fd_in >= 0) {
1230         s->fd_can_read = fd_can_read;
1231         s->fd_read = fd_read;
1232         s->fd_opaque = opaque;
1233         if (nographic && s->fd_in == 0) {
1234         } else {
1235             qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1236                                  fd_chr_read, NULL, chr);
1237         }
1238     }
1239 }
1240
1241 /* open a character device to a unix fd */
1242 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1243 {
1244     CharDriverState *chr;
1245     FDCharDriver *s;
1246
1247     chr = qemu_mallocz(sizeof(CharDriverState));
1248     if (!chr)
1249         return NULL;
1250     s = qemu_mallocz(sizeof(FDCharDriver));
1251     if (!s) {
1252         free(chr);
1253         return NULL;
1254     }
1255     s->fd_in = fd_in;
1256     s->fd_out = fd_out;
1257     chr->opaque = s;
1258     chr->chr_write = fd_chr_write;
1259     chr->chr_add_read_handler = fd_chr_add_read_handler;
1260     return chr;
1261 }
1262
1263 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1264 {
1265     int fd_out;
1266
1267     fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY);
1268     if (fd_out < 0)
1269         return NULL;
1270     return qemu_chr_open_fd(-1, fd_out);
1271 }
1272
1273 CharDriverState *qemu_chr_open_pipe(const char *filename)
1274 {
1275     int fd;
1276
1277     fd = open(filename, O_RDWR | O_BINARY);
1278     if (fd < 0)
1279         return NULL;
1280     return qemu_chr_open_fd(fd, fd);
1281 }
1282
1283
1284 /* for STDIO, we handle the case where several clients use it
1285    (nographic mode) */
1286
1287 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1288
1289 #define TERM_FIFO_MAX_SIZE 1
1290
1291 static int term_got_escape, client_index;
1292 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1293 int term_fifo_size;
1294
1295 void term_print_help(void)
1296 {
1297     printf("\n"
1298            "C-a h    print this help\n"
1299            "C-a x    exit emulator\n"
1300            "C-a s    save disk data back to file (if -snapshot)\n"
1301            "C-a b    send break (magic sysrq)\n"
1302            "C-a c    switch between console and monitor\n"
1303            "C-a C-a  send C-a\n"
1304            );
1305 }
1306
1307 /* called when a char is received */
1308 static void stdio_received_byte(int ch)
1309 {
1310     if (term_got_escape) {
1311         term_got_escape = 0;
1312         switch(ch) {
1313         case 'h':
1314             term_print_help();
1315             break;
1316         case 'x':
1317             exit(0);
1318             break;
1319         case 's': 
1320             {
1321                 int i;
1322                 for (i = 0; i < MAX_DISKS; i++) {
1323                     if (bs_table[i])
1324                         bdrv_commit(bs_table[i]);
1325                 }
1326             }
1327             break;
1328         case 'b':
1329             if (client_index < stdio_nb_clients) {
1330                 CharDriverState *chr;
1331                 FDCharDriver *s;
1332
1333                 chr = stdio_clients[client_index];
1334                 s = chr->opaque;
1335                 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1336             }
1337             break;
1338         case 'c':
1339             client_index++;
1340             if (client_index >= stdio_nb_clients)
1341                 client_index = 0;
1342             if (client_index == 0) {
1343                 /* send a new line in the monitor to get the prompt */
1344                 ch = '\r';
1345                 goto send_char;
1346             }
1347             break;
1348         case TERM_ESCAPE:
1349             goto send_char;
1350         }
1351     } else if (ch == TERM_ESCAPE) {
1352         term_got_escape = 1;
1353     } else {
1354     send_char:
1355         if (client_index < stdio_nb_clients) {
1356             uint8_t buf[1];
1357             CharDriverState *chr;
1358             FDCharDriver *s;
1359             
1360             chr = stdio_clients[client_index];
1361             s = chr->opaque;
1362             if (s->fd_can_read(s->fd_opaque) > 0) {
1363                 buf[0] = ch;
1364                 s->fd_read(s->fd_opaque, buf, 1);
1365             } else if (term_fifo_size == 0) {
1366                 term_fifo[term_fifo_size++] = ch;
1367             }
1368         }
1369     }
1370 }
1371
1372 static int stdio_read_poll(void *opaque)
1373 {
1374     CharDriverState *chr;
1375     FDCharDriver *s;
1376
1377     if (client_index < stdio_nb_clients) {
1378         chr = stdio_clients[client_index];
1379         s = chr->opaque;
1380         /* try to flush the queue if needed */
1381         if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1382             s->fd_read(s->fd_opaque, term_fifo, 1);
1383             term_fifo_size = 0;
1384         }
1385         /* see if we can absorb more chars */
1386         if (term_fifo_size == 0)
1387             return 1;
1388         else
1389             return 0;
1390     } else {
1391         return 1;
1392     }
1393 }
1394
1395 static void stdio_read(void *opaque)
1396 {
1397     int size;
1398     uint8_t buf[1];
1399     
1400     size = read(0, buf, 1);
1401     if (size > 0)
1402         stdio_received_byte(buf[0]);
1403 }
1404
1405 /* init terminal so that we can grab keys */
1406 static struct termios oldtty;
1407 static int old_fd0_flags;
1408
1409 static void term_exit(void)
1410 {
1411     tcsetattr (0, TCSANOW, &oldtty);
1412     fcntl(0, F_SETFL, old_fd0_flags);
1413 }
1414
1415 static void term_init(void)
1416 {
1417     struct termios tty;
1418
1419     tcgetattr (0, &tty);
1420     oldtty = tty;
1421     old_fd0_flags = fcntl(0, F_GETFL);
1422
1423     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1424                           |INLCR|IGNCR|ICRNL|IXON);
1425     tty.c_oflag |= OPOST;
1426     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1427     /* if graphical mode, we allow Ctrl-C handling */
1428     if (nographic)
1429         tty.c_lflag &= ~ISIG;
1430     tty.c_cflag &= ~(CSIZE|PARENB);
1431     tty.c_cflag |= CS8;
1432     tty.c_cc[VMIN] = 1;
1433     tty.c_cc[VTIME] = 0;
1434     
1435     tcsetattr (0, TCSANOW, &tty);
1436
1437     atexit(term_exit);
1438
1439     fcntl(0, F_SETFL, O_NONBLOCK);
1440 }
1441
1442 CharDriverState *qemu_chr_open_stdio(void)
1443 {
1444     CharDriverState *chr;
1445
1446     if (nographic) {
1447         if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1448             return NULL;
1449         chr = qemu_chr_open_fd(0, 1);
1450         if (stdio_nb_clients == 0)
1451             qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1452         client_index = stdio_nb_clients;
1453     } else {
1454         if (stdio_nb_clients != 0)
1455             return NULL;
1456         chr = qemu_chr_open_fd(0, 1);
1457     }
1458     stdio_clients[stdio_nb_clients++] = chr;
1459     if (stdio_nb_clients == 1) {
1460         /* set the terminal in raw mode */
1461         term_init();
1462     }
1463     return chr;
1464 }
1465
1466 #if defined(__linux__)
1467 CharDriverState *qemu_chr_open_pty(void)
1468 {
1469     struct termios tty;
1470     char slave_name[1024];
1471     int master_fd, slave_fd;
1472     
1473     /* Not satisfying */
1474     if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1475         return NULL;
1476     }
1477     
1478     /* Disabling local echo and line-buffered output */
1479     tcgetattr (master_fd, &tty);
1480     tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1481     tty.c_cc[VMIN] = 1;
1482     tty.c_cc[VTIME] = 0;
1483     tcsetattr (master_fd, TCSAFLUSH, &tty);
1484
1485     fprintf(stderr, "char device redirected to %s\n", slave_name);
1486     return qemu_chr_open_fd(master_fd, master_fd);
1487 }
1488
1489 static void tty_serial_init(int fd, int speed, 
1490                             int parity, int data_bits, int stop_bits)
1491 {
1492     struct termios tty;
1493     speed_t spd;
1494
1495 #if 0
1496     printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1497            speed, parity, data_bits, stop_bits);
1498 #endif
1499     tcgetattr (fd, &tty);
1500
1501     switch(speed) {
1502     case 50:
1503         spd = B50;
1504         break;
1505     case 75:
1506         spd = B75;
1507         break;
1508     case 300:
1509         spd = B300;
1510         break;
1511     case 600:
1512         spd = B600;
1513         break;
1514     case 1200:
1515         spd = B1200;
1516         break;
1517     case 2400:
1518         spd = B2400;
1519         break;
1520     case 4800:
1521         spd = B4800;
1522         break;
1523     case 9600:
1524         spd = B9600;
1525         break;
1526     case 19200:
1527         spd = B19200;
1528         break;
1529     case 38400:
1530         spd = B38400;
1531         break;
1532     case 57600:
1533         spd = B57600;
1534         break;
1535     default:
1536     case 115200:
1537         spd = B115200;
1538         break;
1539     }
1540
1541     cfsetispeed(&tty, spd);
1542     cfsetospeed(&tty, spd);
1543
1544     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1545                           |INLCR|IGNCR|ICRNL|IXON);
1546     tty.c_oflag |= OPOST;
1547     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1548     tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1549     switch(data_bits) {
1550     default:
1551     case 8:
1552         tty.c_cflag |= CS8;
1553         break;
1554     case 7:
1555         tty.c_cflag |= CS7;
1556         break;
1557     case 6:
1558         tty.c_cflag |= CS6;
1559         break;
1560     case 5:
1561         tty.c_cflag |= CS5;
1562         break;
1563     }
1564     switch(parity) {
1565     default:
1566     case 'N':
1567         break;
1568     case 'E':
1569         tty.c_cflag |= PARENB;
1570         break;
1571     case 'O':
1572         tty.c_cflag |= PARENB | PARODD;
1573         break;
1574     }
1575     
1576     tcsetattr (fd, TCSANOW, &tty);
1577 }
1578
1579 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1580 {
1581     FDCharDriver *s = chr->opaque;
1582     
1583     switch(cmd) {
1584     case CHR_IOCTL_SERIAL_SET_PARAMS:
1585         {
1586             QEMUSerialSetParams *ssp = arg;
1587             tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1588                             ssp->data_bits, ssp->stop_bits);
1589         }
1590         break;
1591     case CHR_IOCTL_SERIAL_SET_BREAK:
1592         {
1593             int enable = *(int *)arg;
1594             if (enable)
1595                 tcsendbreak(s->fd_in, 1);
1596         }
1597         break;
1598     default:
1599         return -ENOTSUP;
1600     }
1601     return 0;
1602 }
1603
1604 CharDriverState *qemu_chr_open_tty(const char *filename)
1605 {
1606     CharDriverState *chr;
1607     int fd;
1608
1609     fd = open(filename, O_RDWR | O_NONBLOCK);
1610     if (fd < 0)
1611         return NULL;
1612     fcntl(fd, F_SETFL, O_NONBLOCK);
1613     tty_serial_init(fd, 115200, 'N', 8, 1);
1614     chr = qemu_chr_open_fd(fd, fd);
1615     if (!chr)
1616         return NULL;
1617     chr->chr_ioctl = tty_serial_ioctl;
1618     return chr;
1619 }
1620
1621 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1622 {
1623     int fd = (int)chr->opaque;
1624     uint8_t b;
1625
1626     switch(cmd) {
1627     case CHR_IOCTL_PP_READ_DATA:
1628         if (ioctl(fd, PPRDATA, &b) < 0)
1629             return -ENOTSUP;
1630         *(uint8_t *)arg = b;
1631         break;
1632     case CHR_IOCTL_PP_WRITE_DATA:
1633         b = *(uint8_t *)arg;
1634         if (ioctl(fd, PPWDATA, &b) < 0)
1635             return -ENOTSUP;
1636         break;
1637     case CHR_IOCTL_PP_READ_CONTROL:
1638         if (ioctl(fd, PPRCONTROL, &b) < 0)
1639             return -ENOTSUP;
1640         *(uint8_t *)arg = b;
1641         break;
1642     case CHR_IOCTL_PP_WRITE_CONTROL:
1643         b = *(uint8_t *)arg;
1644         if (ioctl(fd, PPWCONTROL, &b) < 0)
1645             return -ENOTSUP;
1646         break;
1647     case CHR_IOCTL_PP_READ_STATUS:
1648         if (ioctl(fd, PPRSTATUS, &b) < 0)
1649             return -ENOTSUP;
1650         *(uint8_t *)arg = b;
1651         break;
1652     default:
1653         return -ENOTSUP;
1654     }
1655     return 0;
1656 }
1657
1658 CharDriverState *qemu_chr_open_pp(const char *filename)
1659 {
1660     CharDriverState *chr;
1661     int fd;
1662
1663     fd = open(filename, O_RDWR);
1664     if (fd < 0)
1665         return NULL;
1666
1667     if (ioctl(fd, PPCLAIM) < 0) {
1668         close(fd);
1669         return NULL;
1670     }
1671
1672     chr = qemu_mallocz(sizeof(CharDriverState));
1673     if (!chr) {
1674         close(fd);
1675         return NULL;
1676     }
1677     chr->opaque = (void *)fd;
1678     chr->chr_write = null_chr_write;
1679     chr->chr_add_read_handler = null_chr_add_read_handler;
1680     chr->chr_ioctl = pp_ioctl;
1681     return chr;
1682 }
1683
1684 #else
1685 CharDriverState *qemu_chr_open_pty(void)
1686 {
1687     return NULL;
1688 }
1689 #endif
1690
1691 #endif /* !defined(_WIN32) */
1692
1693 CharDriverState *qemu_chr_open(const char *filename)
1694 {
1695 #ifndef _WIN32
1696     const char *p;
1697 #endif
1698
1699     if (!strcmp(filename, "vc")) {
1700         return text_console_init(&display_state);
1701     } else if (!strcmp(filename, "null")) {
1702         return qemu_chr_open_null();
1703     } else 
1704 #ifndef _WIN32
1705     if (strstart(filename, "file:", &p)) {
1706         return qemu_chr_open_file_out(p);
1707     } else if (strstart(filename, "pipe:", &p)) {
1708         return qemu_chr_open_pipe(p);
1709     } else if (!strcmp(filename, "pty")) {
1710         return qemu_chr_open_pty();
1711     } else if (!strcmp(filename, "stdio")) {
1712         return qemu_chr_open_stdio();
1713     } else 
1714 #endif
1715 #if defined(__linux__)
1716     if (strstart(filename, "/dev/parport", NULL)) {
1717         return qemu_chr_open_pp(filename);
1718     } else 
1719     if (strstart(filename, "/dev/", NULL)) {
1720         return qemu_chr_open_tty(filename);
1721     } else 
1722 #endif
1723     {
1724         return NULL;
1725     }
1726 }
1727
1728 /***********************************************************/
1729 /* network device redirectors */
1730
1731 void hex_dump(FILE *f, const uint8_t *buf, int size)
1732 {
1733     int len, i, j, c;
1734
1735     for(i=0;i<size;i+=16) {
1736         len = size - i;
1737         if (len > 16)
1738             len = 16;
1739         fprintf(f, "%08x ", i);
1740         for(j=0;j<16;j++) {
1741             if (j < len)
1742                 fprintf(f, " %02x", buf[i+j]);
1743             else
1744                 fprintf(f, "   ");
1745         }
1746         fprintf(f, " ");
1747         for(j=0;j<len;j++) {
1748             c = buf[i+j];
1749             if (c < ' ' || c > '~')
1750                 c = '.';
1751             fprintf(f, "%c", c);
1752         }
1753         fprintf(f, "\n");
1754     }
1755 }
1756
1757 static int parse_macaddr(uint8_t *macaddr, const char *p)
1758 {
1759     int i;
1760     for(i = 0; i < 6; i++) {
1761         macaddr[i] = strtol(p, (char **)&p, 16);
1762         if (i == 5) {
1763             if (*p != '\0') 
1764                 return -1;
1765         } else {
1766             if (*p != ':') 
1767                 return -1;
1768             p++;
1769         }
1770     }
1771     return 0;
1772 }
1773
1774 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1775 {
1776     const char *p, *p1;
1777     int len;
1778     p = *pp;
1779     p1 = strchr(p, sep);
1780     if (!p1)
1781         return -1;
1782     len = p1 - p;
1783     p1++;
1784     if (buf_size > 0) {
1785         if (len > buf_size - 1)
1786             len = buf_size - 1;
1787         memcpy(buf, p, len);
1788         buf[len] = '\0';
1789     }
1790     *pp = p1;
1791     return 0;
1792 }
1793
1794 int parse_host_port(struct sockaddr_in *saddr, const char *str)
1795 {
1796     char buf[512];
1797     struct hostent *he;
1798     const char *p, *r;
1799     int port;
1800
1801     p = str;
1802     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1803         return -1;
1804     saddr->sin_family = AF_INET;
1805     if (buf[0] == '\0') {
1806         saddr->sin_addr.s_addr = 0;
1807     } else {
1808         if (isdigit(buf[0])) {
1809             if (!inet_aton(buf, &saddr->sin_addr))
1810                 return -1;
1811         } else {
1812             if ((he = gethostbyname(buf)) == NULL)
1813                 return - 1;
1814             saddr->sin_addr = *(struct in_addr *)he->h_addr;
1815         }
1816     }
1817     port = strtol(p, (char **)&r, 0);
1818     if (r == p)
1819         return -1;
1820     saddr->sin_port = htons(port);
1821     return 0;
1822 }
1823
1824 /* find or alloc a new VLAN */
1825 VLANState *qemu_find_vlan(int id)
1826 {
1827     VLANState **pvlan, *vlan;
1828     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1829         if (vlan->id == id)
1830             return vlan;
1831     }
1832     vlan = qemu_mallocz(sizeof(VLANState));
1833     if (!vlan)
1834         return NULL;
1835     vlan->id = id;
1836     vlan->next = NULL;
1837     pvlan = &first_vlan;
1838     while (*pvlan != NULL)
1839         pvlan = &(*pvlan)->next;
1840     *pvlan = vlan;
1841     return vlan;
1842 }
1843
1844 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
1845                                       IOReadHandler *fd_read, void *opaque)
1846 {
1847     VLANClientState *vc, **pvc;
1848     vc = qemu_mallocz(sizeof(VLANClientState));
1849     if (!vc)
1850         return NULL;
1851     vc->fd_read = fd_read;
1852     vc->opaque = opaque;
1853     vc->vlan = vlan;
1854
1855     vc->next = NULL;
1856     pvc = &vlan->first_client;
1857     while (*pvc != NULL)
1858         pvc = &(*pvc)->next;
1859     *pvc = vc;
1860     return vc;
1861 }
1862
1863 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
1864 {
1865     VLANState *vlan = vc1->vlan;
1866     VLANClientState *vc;
1867
1868 #if 0
1869     printf("vlan %d send:\n", vlan->id);
1870     hex_dump(stdout, buf, size);
1871 #endif
1872     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1873         if (vc != vc1) {
1874             vc->fd_read(vc->opaque, buf, size);
1875         }
1876     }
1877 }
1878
1879 #if defined(CONFIG_SLIRP)
1880
1881 /* slirp network adapter */
1882
1883 static int slirp_inited;
1884 static VLANClientState *slirp_vc;
1885
1886 int slirp_can_output(void)
1887 {
1888     return 1;
1889 }
1890
1891 void slirp_output(const uint8_t *pkt, int pkt_len)
1892 {
1893 #if 0
1894     printf("slirp output:\n");
1895     hex_dump(stdout, pkt, pkt_len);
1896 #endif
1897     qemu_send_packet(slirp_vc, pkt, pkt_len);
1898 }
1899
1900 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
1901 {
1902 #if 0
1903     printf("slirp input:\n");
1904     hex_dump(stdout, buf, size);
1905 #endif
1906     slirp_input(buf, size);
1907 }
1908
1909 static int net_slirp_init(VLANState *vlan)
1910 {
1911     if (!slirp_inited) {
1912         slirp_inited = 1;
1913         slirp_init();
1914     }
1915     slirp_vc = qemu_new_vlan_client(vlan, 
1916                                     slirp_receive, NULL);
1917     snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
1918     return 0;
1919 }
1920
1921 static void net_slirp_redir(const char *redir_str)
1922 {
1923     int is_udp;
1924     char buf[256], *r;
1925     const char *p;
1926     struct in_addr guest_addr;
1927     int host_port, guest_port;
1928     
1929     if (!slirp_inited) {
1930         slirp_inited = 1;
1931         slirp_init();
1932     }
1933
1934     p = redir_str;
1935     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1936         goto fail;
1937     if (!strcmp(buf, "tcp")) {
1938         is_udp = 0;
1939     } else if (!strcmp(buf, "udp")) {
1940         is_udp = 1;
1941     } else {
1942         goto fail;
1943     }
1944
1945     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1946         goto fail;
1947     host_port = strtol(buf, &r, 0);
1948     if (r == buf)
1949         goto fail;
1950
1951     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1952         goto fail;
1953     if (buf[0] == '\0') {
1954         pstrcpy(buf, sizeof(buf), "10.0.2.15");
1955     }
1956     if (!inet_aton(buf, &guest_addr))
1957         goto fail;
1958     
1959     guest_port = strtol(p, &r, 0);
1960     if (r == p)
1961         goto fail;
1962     
1963     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1964         fprintf(stderr, "qemu: could not set up redirection\n");
1965         exit(1);
1966     }
1967     return;
1968  fail:
1969     fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1970     exit(1);
1971 }
1972     
1973 #ifndef _WIN32
1974
1975 char smb_dir[1024];
1976
1977 static void smb_exit(void)
1978 {
1979     DIR *d;
1980     struct dirent *de;
1981     char filename[1024];
1982
1983     /* erase all the files in the directory */
1984     d = opendir(smb_dir);
1985     for(;;) {
1986         de = readdir(d);
1987         if (!de)
1988             break;
1989         if (strcmp(de->d_name, ".") != 0 &&
1990             strcmp(de->d_name, "..") != 0) {
1991             snprintf(filename, sizeof(filename), "%s/%s", 
1992                      smb_dir, de->d_name);
1993             unlink(filename);
1994         }
1995     }
1996     closedir(d);
1997     rmdir(smb_dir);
1998 }
1999
2000 /* automatic user mode samba server configuration */
2001 void net_slirp_smb(const char *exported_dir)
2002 {
2003     char smb_conf[1024];
2004     char smb_cmdline[1024];
2005     FILE *f;
2006
2007     if (!slirp_inited) {
2008         slirp_inited = 1;
2009         slirp_init();
2010     }
2011
2012     /* XXX: better tmp dir construction */
2013     snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2014     if (mkdir(smb_dir, 0700) < 0) {
2015         fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2016         exit(1);
2017     }
2018     snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2019     
2020     f = fopen(smb_conf, "w");
2021     if (!f) {
2022         fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2023         exit(1);
2024     }
2025     fprintf(f, 
2026             "[global]\n"
2027             "private dir=%s\n"
2028             "smb ports=0\n"
2029             "socket address=127.0.0.1\n"
2030             "pid directory=%s\n"
2031             "lock directory=%s\n"
2032             "log file=%s/log.smbd\n"
2033             "smb passwd file=%s/smbpasswd\n"
2034             "security = share\n"
2035             "[qemu]\n"
2036             "path=%s\n"
2037             "read only=no\n"
2038             "guest ok=yes\n",
2039             smb_dir,
2040             smb_dir,
2041             smb_dir,
2042             smb_dir,
2043             smb_dir,
2044             exported_dir
2045             );
2046     fclose(f);
2047     atexit(smb_exit);
2048
2049     snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2050              smb_conf);
2051     
2052     slirp_add_exec(0, smb_cmdline, 4, 139);
2053 }
2054
2055 #endif /* !defined(_WIN32) */
2056
2057 #endif /* CONFIG_SLIRP */
2058
2059 #if !defined(_WIN32)
2060
2061 typedef struct TAPState {
2062     VLANClientState *vc;
2063     int fd;
2064 } TAPState;
2065
2066 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2067 {
2068     TAPState *s = opaque;
2069     int ret;
2070     for(;;) {
2071         ret = write(s->fd, buf, size);
2072         if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2073         } else {
2074             break;
2075         }
2076     }
2077 }
2078
2079 static void tap_send(void *opaque)
2080 {
2081     TAPState *s = opaque;
2082     uint8_t buf[4096];
2083     int size;
2084
2085     size = read(s->fd, buf, sizeof(buf));
2086     if (size > 0) {
2087         qemu_send_packet(s->vc, buf, size);
2088     }
2089 }
2090
2091 /* fd support */
2092
2093 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2094 {
2095     TAPState *s;
2096
2097     s = qemu_mallocz(sizeof(TAPState));
2098     if (!s)
2099         return NULL;
2100     s->fd = fd;
2101     s->vc = qemu_new_vlan_client(vlan, tap_receive, s);
2102     qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2103     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2104     return s;
2105 }
2106
2107 #ifdef _BSD
2108 static int tap_open(char *ifname, int ifname_size)
2109 {
2110     int fd;
2111     char *dev;
2112     struct stat s;
2113
2114     fd = open("/dev/tap", O_RDWR);
2115     if (fd < 0) {
2116         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2117         return -1;
2118     }
2119
2120     fstat(fd, &s);
2121     dev = devname(s.st_rdev, S_IFCHR);
2122     pstrcpy(ifname, ifname_size, dev);
2123
2124     fcntl(fd, F_SETFL, O_NONBLOCK);
2125     return fd;
2126 }
2127 #else
2128 static int tap_open(char *ifname, int ifname_size)
2129 {
2130     struct ifreq ifr;
2131     int fd, ret;
2132     
2133     fd = open("/dev/net/tun", O_RDWR);
2134     if (fd < 0) {
2135         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2136         return -1;
2137     }
2138     memset(&ifr, 0, sizeof(ifr));
2139     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2140     if (ifname[0] != '\0')
2141         pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2142     else
2143         pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2144     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2145     if (ret != 0) {
2146         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2147         close(fd);
2148         return -1;
2149     }
2150     pstrcpy(ifname, ifname_size, ifr.ifr_name);
2151     fcntl(fd, F_SETFL, O_NONBLOCK);
2152     return fd;
2153 }
2154 #endif
2155
2156 static int net_tap_init(VLANState *vlan, const char *ifname1,
2157                         const char *setup_script)
2158 {
2159     TAPState *s;
2160     int pid, status, fd;
2161     char *args[3];
2162     char **parg;
2163     char ifname[128];
2164
2165     if (ifname1 != NULL)
2166         pstrcpy(ifname, sizeof(ifname), ifname1);
2167     else
2168         ifname[0] = '\0';
2169     fd = tap_open(ifname, sizeof(ifname));
2170     if (fd < 0)
2171         return -1;
2172
2173     if (!setup_script)
2174         setup_script = "";
2175     if (setup_script[0] != '\0') {
2176         /* try to launch network init script */
2177         pid = fork();
2178         if (pid >= 0) {
2179             if (pid == 0) {
2180                 parg = args;
2181                 *parg++ = (char *)setup_script;
2182                 *parg++ = ifname;
2183                 *parg++ = NULL;
2184                 execv(setup_script, args);
2185                 _exit(1);
2186             }
2187             while (waitpid(pid, &status, 0) != pid);
2188             if (!WIFEXITED(status) ||
2189                 WEXITSTATUS(status) != 0) {
2190                 fprintf(stderr, "%s: could not launch network script\n",
2191                         setup_script);
2192                 return -1;
2193             }
2194         }
2195     }
2196     s = net_tap_fd_init(vlan, fd);
2197     if (!s)
2198         return -1;
2199     snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
2200              "tap: ifname=%s setup_script=%s", ifname, setup_script);
2201     return 0;
2202 }
2203
2204 #endif /* !_WIN32 */
2205
2206 /* network connection */
2207 typedef struct NetSocketState {
2208     VLANClientState *vc;
2209     int fd;
2210     int state; /* 0 = getting length, 1 = getting data */
2211     int index;
2212     int packet_len;
2213     uint8_t buf[4096];
2214     struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2215 } NetSocketState;
2216
2217 typedef struct NetSocketListenState {
2218     VLANState *vlan;
2219     int fd;
2220 } NetSocketListenState;
2221
2222 /* XXX: we consider we can send the whole packet without blocking */
2223 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2224 {
2225     NetSocketState *s = opaque;
2226     uint32_t len;
2227     len = htonl(size);
2228
2229     send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2230     send_all(s->fd, buf, size);
2231 }
2232
2233 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2234 {
2235     NetSocketState *s = opaque;
2236     sendto(s->fd, buf, size, 0, 
2237            (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2238 }
2239
2240 static void net_socket_send(void *opaque)
2241 {
2242     NetSocketState *s = opaque;
2243     int l, size, err;
2244     uint8_t buf1[4096];
2245     const uint8_t *buf;
2246
2247     size = recv(s->fd, buf1, sizeof(buf1), 0);
2248     if (size < 0) {
2249         err = socket_error();
2250         if (err != EWOULDBLOCK) 
2251             goto eoc;
2252     } else if (size == 0) {
2253         /* end of connection */
2254     eoc:
2255         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2256         closesocket(s->fd);
2257         return;
2258     }
2259     buf = buf1;
2260     while (size > 0) {
2261         /* reassemble a packet from the network */
2262         switch(s->state) {
2263         case 0:
2264             l = 4 - s->index;
2265             if (l > size)
2266                 l = size;
2267             memcpy(s->buf + s->index, buf, l);
2268             buf += l;
2269             size -= l;
2270             s->index += l;
2271             if (s->index == 4) {
2272                 /* got length */
2273                 s->packet_len = ntohl(*(uint32_t *)s->buf);
2274                 s->index = 0;
2275                 s->state = 1;
2276             }
2277             break;
2278         case 1:
2279             l = s->packet_len - s->index;
2280             if (l > size)
2281                 l = size;
2282             memcpy(s->buf + s->index, buf, l);
2283             s->index += l;
2284             buf += l;
2285             size -= l;
2286             if (s->index >= s->packet_len) {
2287                 qemu_send_packet(s->vc, s->buf, s->packet_len);
2288                 s->index = 0;
2289                 s->state = 0;
2290             }
2291             break;
2292         }
2293     }
2294 }
2295
2296 static void net_socket_send_dgram(void *opaque)
2297 {
2298     NetSocketState *s = opaque;
2299     int size;
2300
2301     size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2302     if (size < 0) 
2303         return;
2304     if (size == 0) {
2305         /* end of connection */
2306         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2307         return;
2308     }
2309     qemu_send_packet(s->vc, s->buf, size);
2310 }
2311
2312 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2313 {
2314     struct ip_mreq imr;
2315     int fd;
2316     int val, ret;
2317     if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2318         fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2319                 inet_ntoa(mcastaddr->sin_addr), 
2320                 (int)ntohl(mcastaddr->sin_addr.s_addr));
2321         return -1;
2322
2323     }
2324     fd = socket(PF_INET, SOCK_DGRAM, 0);
2325     if (fd < 0) {
2326         perror("socket(PF_INET, SOCK_DGRAM)");
2327         return -1;
2328     }
2329
2330     val = 1;
2331     ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
2332                    (const char *)&val, sizeof(val));
2333     if (ret < 0) {
2334         perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2335         goto fail;
2336     }
2337
2338     ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2339     if (ret < 0) {
2340         perror("bind");
2341         goto fail;
2342     }
2343     
2344     /* Add host to multicast group */
2345     imr.imr_multiaddr = mcastaddr->sin_addr;
2346     imr.imr_interface.s_addr = htonl(INADDR_ANY);
2347
2348     ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
2349                      (const char *)&imr, sizeof(struct ip_mreq));
2350     if (ret < 0) {
2351         perror("setsockopt(IP_ADD_MEMBERSHIP)");
2352         goto fail;
2353     }
2354
2355     /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2356     val = 1;
2357     ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
2358                    (const char *)&val, sizeof(val));
2359     if (ret < 0) {
2360         perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2361         goto fail;
2362     }
2363
2364     socket_set_nonblock(fd);
2365     return fd;
2366 fail:
2367     if (fd>=0) close(fd);
2368     return -1;
2369 }
2370
2371 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
2372                                           int is_connected)
2373 {
2374     struct sockaddr_in saddr;
2375     int newfd;
2376     socklen_t saddr_len;
2377     NetSocketState *s;
2378
2379     /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2380      * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
2381      * by ONLY ONE process: we must "clone" this dgram socket --jjo
2382      */
2383
2384     if (is_connected) {
2385         if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2386             /* must be bound */
2387             if (saddr.sin_addr.s_addr==0) {
2388                 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2389                         fd);
2390                 return NULL;
2391             }
2392             /* clone dgram socket */
2393             newfd = net_socket_mcast_create(&saddr);
2394             if (newfd < 0) {
2395                 /* error already reported by net_socket_mcast_create() */
2396                 close(fd);
2397                 return NULL;
2398             }
2399             /* clone newfd to fd, close newfd */
2400             dup2(newfd, fd);
2401             close(newfd);
2402         
2403         } else {
2404             fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2405                     fd, strerror(errno));
2406             return NULL;
2407         }
2408     }
2409
2410     s = qemu_mallocz(sizeof(NetSocketState));
2411     if (!s)
2412         return NULL;
2413     s->fd = fd;
2414
2415     s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, s);
2416     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2417
2418     /* mcast: save bound address as dst */
2419     if (is_connected) s->dgram_dst=saddr;
2420
2421     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2422             "socket: fd=%d (%s mcast=%s:%d)", 
2423             fd, is_connected? "cloned" : "",
2424             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2425     return s;
2426 }
2427
2428 static void net_socket_connect(void *opaque)
2429 {
2430     NetSocketState *s = opaque;
2431     qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2432 }
2433
2434 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
2435                                           int is_connected)
2436 {
2437     NetSocketState *s;
2438     s = qemu_mallocz(sizeof(NetSocketState));
2439     if (!s)
2440         return NULL;
2441     s->fd = fd;
2442     s->vc = qemu_new_vlan_client(vlan, 
2443                                  net_socket_receive, s);
2444     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2445              "socket: fd=%d", fd);
2446     if (is_connected) {
2447         net_socket_connect(s);
2448     } else {
2449         qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2450     }
2451     return s;
2452 }
2453
2454 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
2455                                           int is_connected)
2456 {
2457     int so_type=-1, optlen=sizeof(so_type);
2458
2459     if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2460         fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2461         return NULL;
2462     }
2463     switch(so_type) {
2464     case SOCK_DGRAM:
2465         return net_socket_fd_init_dgram(vlan, fd, is_connected);
2466     case SOCK_STREAM:
2467         return net_socket_fd_init_stream(vlan, fd, is_connected);
2468     default:
2469         /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2470         fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2471         return net_socket_fd_init_stream(vlan, fd, is_connected);
2472     }
2473     return NULL;
2474 }
2475
2476 static void net_socket_accept(void *opaque)
2477 {
2478     NetSocketListenState *s = opaque;    
2479     NetSocketState *s1;
2480     struct sockaddr_in saddr;
2481     socklen_t len;
2482     int fd;
2483
2484     for(;;) {
2485         len = sizeof(saddr);
2486         fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2487         if (fd < 0 && errno != EINTR) {
2488             return;
2489         } else if (fd >= 0) {
2490             break;
2491         }
2492     }
2493     s1 = net_socket_fd_init(s->vlan, fd, 1); 
2494     if (!s1) {
2495         close(fd);
2496     } else {
2497         snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2498                  "socket: connection from %s:%d", 
2499                  inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2500     }
2501 }
2502
2503 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2504 {
2505     NetSocketListenState *s;
2506     int fd, val, ret;
2507     struct sockaddr_in saddr;
2508
2509     if (parse_host_port(&saddr, host_str) < 0)
2510         return -1;
2511     
2512     s = qemu_mallocz(sizeof(NetSocketListenState));
2513     if (!s)
2514         return -1;
2515
2516     fd = socket(PF_INET, SOCK_STREAM, 0);
2517     if (fd < 0) {
2518         perror("socket");
2519         return -1;
2520     }
2521     socket_set_nonblock(fd);
2522
2523     /* allow fast reuse */
2524     val = 1;
2525     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2526     
2527     ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2528     if (ret < 0) {
2529         perror("bind");
2530         return -1;
2531     }
2532     ret = listen(fd, 0);
2533     if (ret < 0) {
2534         perror("listen");
2535         return -1;
2536     }
2537     s->vlan = vlan;
2538     s->fd = fd;
2539     qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2540     return 0;
2541 }
2542
2543 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2544 {
2545     NetSocketState *s;
2546     int fd, connected, ret, err;
2547     struct sockaddr_in saddr;
2548
2549     if (parse_host_port(&saddr, host_str) < 0)
2550         return -1;
2551
2552     fd = socket(PF_INET, SOCK_STREAM, 0);
2553     if (fd < 0) {
2554         perror("socket");
2555         return -1;
2556     }
2557     socket_set_nonblock(fd);
2558
2559     connected = 0;
2560     for(;;) {
2561         ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2562         if (ret < 0) {
2563             err = socket_error();
2564             if (err == EINTR || err == EWOULDBLOCK) {
2565             } else if (err == EINPROGRESS) {
2566                 break;
2567             } else {
2568                 perror("connect");
2569                 closesocket(fd);
2570                 return -1;
2571             }
2572         } else {
2573             connected = 1;
2574             break;
2575         }
2576     }
2577     s = net_socket_fd_init(vlan, fd, connected);
2578     if (!s)
2579         return -1;
2580     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2581              "socket: connect to %s:%d", 
2582              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2583     return 0;
2584 }
2585
2586 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
2587 {
2588     NetSocketState *s;
2589     int fd;
2590     struct sockaddr_in saddr;
2591
2592     if (parse_host_port(&saddr, host_str) < 0)
2593         return -1;
2594
2595
2596     fd = net_socket_mcast_create(&saddr);
2597     if (fd < 0)
2598         return -1;
2599
2600     s = net_socket_fd_init(vlan, fd, 0);
2601     if (!s)
2602         return -1;
2603
2604     s->dgram_dst = saddr;
2605     
2606     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2607              "socket: mcast=%s:%d", 
2608              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2609     return 0;
2610
2611 }
2612
2613 static int get_param_value(char *buf, int buf_size,
2614                            const char *tag, const char *str)
2615 {
2616     const char *p;
2617     char *q;
2618     char option[128];
2619
2620     p = str;
2621     for(;;) {
2622         q = option;
2623         while (*p != '\0' && *p != '=') {
2624             if ((q - option) < sizeof(option) - 1)
2625                 *q++ = *p;
2626             p++;
2627         }
2628         *q = '\0';
2629         if (*p != '=')
2630             break;
2631         p++;
2632         if (!strcmp(tag, option)) {
2633             q = buf;
2634             while (*p != '\0' && *p != ',') {
2635                 if ((q - buf) < buf_size - 1)
2636                     *q++ = *p;
2637                 p++;
2638             }
2639             *q = '\0';
2640             return q - buf;
2641         } else {
2642             while (*p != '\0' && *p != ',') {
2643                 p++;
2644             }
2645         }
2646         if (*p != ',')
2647             break;
2648         p++;
2649     }
2650     return 0;
2651 }
2652
2653 int net_client_init(const char *str)
2654 {
2655     const char *p;
2656     char *q;
2657     char device[64];
2658     char buf[1024];
2659     int vlan_id, ret;
2660     VLANState *vlan;
2661
2662     p = str;
2663     q = device;
2664     while (*p != '\0' && *p != ',') {
2665         if ((q - device) < sizeof(device) - 1)
2666             *q++ = *p;
2667         p++;
2668     }
2669     *q = '\0';
2670     if (*p == ',')
2671         p++;
2672     vlan_id = 0;
2673     if (get_param_value(buf, sizeof(buf), "vlan", p)) {
2674         vlan_id = strtol(buf, NULL, 0);
2675     }
2676     vlan = qemu_find_vlan(vlan_id);
2677     if (!vlan) {
2678         fprintf(stderr, "Could not create vlan %d\n", vlan_id);
2679         return -1;
2680     }
2681     if (!strcmp(device, "nic")) {
2682         NICInfo *nd;
2683         uint8_t *macaddr;
2684
2685         if (nb_nics >= MAX_NICS) {
2686             fprintf(stderr, "Too Many NICs\n");
2687             return -1;
2688         }
2689         nd = &nd_table[nb_nics];
2690         macaddr = nd->macaddr;
2691         macaddr[0] = 0x52;
2692         macaddr[1] = 0x54;
2693         macaddr[2] = 0x00;
2694         macaddr[3] = 0x12;
2695         macaddr[4] = 0x34;
2696         macaddr[5] = 0x56 + nb_nics;
2697
2698         if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2699             if (parse_macaddr(macaddr, buf) < 0) {
2700                 fprintf(stderr, "invalid syntax for ethernet address\n");
2701                 return -1;
2702             }
2703         }
2704         nd->vlan = vlan;
2705         nb_nics++;
2706         ret = 0;
2707     } else
2708     if (!strcmp(device, "none")) {
2709         /* does nothing. It is needed to signal that no network cards
2710            are wanted */
2711         ret = 0;
2712     } else
2713 #ifdef CONFIG_SLIRP
2714     if (!strcmp(device, "user")) {
2715         ret = net_slirp_init(vlan);
2716     } else
2717 #endif
2718 #ifdef _WIN32
2719     if (!strcmp(device, "tap")) {
2720         char ifname[64];
2721         if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
2722             fprintf(stderr, "tap: no interface name\n");
2723             return -1;
2724         }
2725         ret = tap_win32_init(vlan, ifname);
2726     } else
2727 #else
2728     if (!strcmp(device, "tap")) {
2729         char ifname[64];
2730         char setup_script[1024];
2731         int fd;
2732         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2733             fd = strtol(buf, NULL, 0);
2734             ret = -1;
2735             if (net_tap_fd_init(vlan, fd))
2736                 ret = 0;
2737         } else {
2738             get_param_value(ifname, sizeof(ifname), "ifname", p);
2739             if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2740                 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2741             }
2742             ret = net_tap_init(vlan, ifname, setup_script);
2743         }
2744     } else
2745 #endif
2746     if (!strcmp(device, "socket")) {
2747         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2748             int fd;
2749             fd = strtol(buf, NULL, 0);
2750             ret = -1;
2751             if (net_socket_fd_init(vlan, fd, 1))
2752                 ret = 0;
2753         } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2754             ret = net_socket_listen_init(vlan, buf);
2755         } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2756             ret = net_socket_connect_init(vlan, buf);
2757         } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
2758             ret = net_socket_mcast_init(vlan, buf);
2759         } else {
2760             fprintf(stderr, "Unknown socket options: %s\n", p);
2761             return -1;
2762         }
2763     } else
2764     {
2765         fprintf(stderr, "Unknown network device: %s\n", device);
2766         return -1;
2767     }
2768     if (ret < 0) {
2769         fprintf(stderr, "Could not initialize device '%s'\n", device);
2770     }
2771     
2772     return ret;
2773 }
2774
2775 void do_info_network(void)
2776 {
2777     VLANState *vlan;
2778     VLANClientState *vc;
2779
2780     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2781         term_printf("VLAN %d devices:\n", vlan->id);
2782         for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2783             term_printf("  %s\n", vc->info_str);
2784     }
2785 }
2786  
2787 /***********************************************************/
2788 /* USB devices */
2789
2790 static int usb_device_add(const char *devname)
2791 {
2792     const char *p;
2793     USBDevice *dev;
2794     int i;
2795
2796     if (!vm_usb_hub)
2797         return -1;
2798     for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2799         if (!vm_usb_ports[i]->dev)
2800             break;
2801     }
2802     if (i == MAX_VM_USB_PORTS)
2803         return -1;
2804
2805     if (strstart(devname, "host:", &p)) {
2806         dev = usb_host_device_open(p);
2807         if (!dev)
2808             return -1;
2809     } else if (!strcmp(devname, "mouse")) {
2810         dev = usb_mouse_init();
2811         if (!dev)
2812             return -1;
2813     } else {
2814         return -1;
2815     }
2816     usb_attach(vm_usb_ports[i], dev);
2817     return 0;
2818 }
2819
2820 static int usb_device_del(const char *devname)
2821 {
2822     USBDevice *dev;
2823     int bus_num, addr, i;
2824     const char *p;
2825
2826     if (!vm_usb_hub)
2827         return -1;
2828
2829     p = strchr(devname, '.');
2830     if (!p) 
2831         return -1;
2832     bus_num = strtoul(devname, NULL, 0);
2833     addr = strtoul(p + 1, NULL, 0);
2834     if (bus_num != 0)
2835         return -1;
2836     for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2837         dev = vm_usb_ports[i]->dev;
2838         if (dev && dev->addr == addr)
2839             break;
2840     }
2841     if (i == MAX_VM_USB_PORTS)
2842         return -1;
2843     usb_attach(vm_usb_ports[i], NULL);
2844     return 0;
2845 }
2846
2847 void do_usb_add(const char *devname)
2848 {
2849     int ret;
2850     ret = usb_device_add(devname);
2851     if (ret < 0) 
2852         term_printf("Could not add USB device '%s'\n", devname);
2853 }
2854
2855 void do_usb_del(const char *devname)
2856 {
2857     int ret;
2858     ret = usb_device_del(devname);
2859     if (ret < 0) 
2860         term_printf("Could not remove USB device '%s'\n", devname);
2861 }
2862
2863 void usb_info(void)
2864 {
2865     USBDevice *dev;
2866     int i;
2867     const char *speed_str;
2868
2869     if (!vm_usb_hub) {
2870         term_printf("USB support not enabled\n");
2871         return;
2872     }
2873
2874     for(i = 0; i < MAX_VM_USB_PORTS; i++) {
2875         dev = vm_usb_ports[i]->dev;
2876         if (dev) {
2877             term_printf("Hub port %d:\n", i);
2878             switch(dev->speed) {
2879             case USB_SPEED_LOW: 
2880                 speed_str = "1.5"; 
2881                 break;
2882             case USB_SPEED_FULL: 
2883                 speed_str = "12"; 
2884                 break;
2885             case USB_SPEED_HIGH: 
2886                 speed_str = "480"; 
2887                 break;
2888             default:
2889                 speed_str = "?"; 
2890                 break;
2891             }
2892             term_printf("  Device %d.%d, speed %s Mb/s\n", 
2893                         0, dev->addr, speed_str);
2894         }
2895     }
2896 }
2897
2898 /***********************************************************/
2899 /* pid file */
2900
2901 static char *pid_filename;
2902
2903 /* Remove PID file. Called on normal exit */
2904
2905 static void remove_pidfile(void) 
2906 {
2907     unlink (pid_filename);
2908 }
2909
2910 static void create_pidfile(const char *filename)
2911 {
2912     struct stat pidstat;
2913     FILE *f;
2914
2915     /* Try to write our PID to the named file */
2916     if (stat(filename, &pidstat) < 0) {
2917         if (errno == ENOENT) {
2918             if ((f = fopen (filename, "w")) == NULL) {
2919                 perror("Opening pidfile");
2920                 exit(1);
2921             }
2922             fprintf(f, "%d\n", getpid());
2923             fclose(f);
2924             pid_filename = qemu_strdup(filename);
2925             if (!pid_filename) {
2926                 fprintf(stderr, "Could not save PID filename");
2927                 exit(1);
2928             }
2929             atexit(remove_pidfile);
2930         }
2931     } else {
2932         fprintf(stderr, "%s already exists. Remove it and try again.\n", 
2933                 filename);
2934         exit(1);
2935     }
2936 }
2937
2938 /***********************************************************/
2939 /* dumb display */
2940
2941 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2942 {
2943 }
2944
2945 static void dumb_resize(DisplayState *ds, int w, int h)
2946 {
2947 }
2948
2949 static void dumb_refresh(DisplayState *ds)
2950 {
2951     vga_update_display();
2952 }
2953
2954 void dumb_display_init(DisplayState *ds)
2955 {
2956     ds->data = NULL;
2957     ds->linesize = 0;
2958     ds->depth = 0;
2959     ds->dpy_update = dumb_update;
2960     ds->dpy_resize = dumb_resize;
2961     ds->dpy_refresh = dumb_refresh;
2962 }
2963
2964 #if !defined(CONFIG_SOFTMMU)
2965 /***********************************************************/
2966 /* cpu signal handler */
2967 static void host_segv_handler(int host_signum, siginfo_t *info, 
2968                               void *puc)
2969 {
2970     if (cpu_signal_handler(host_signum, info, puc))
2971         return;
2972     if (stdio_nb_clients > 0)
2973         term_exit();
2974     abort();
2975 }
2976 #endif
2977
2978 /***********************************************************/
2979 /* I/O handling */
2980
2981 #define MAX_IO_HANDLERS 64
2982
2983 typedef struct IOHandlerRecord {
2984     int fd;
2985     IOCanRWHandler *fd_read_poll;
2986     IOHandler *fd_read;
2987     IOHandler *fd_write;
2988     void *opaque;
2989     /* temporary data */
2990     struct pollfd *ufd;
2991     struct IOHandlerRecord *next;
2992 } IOHandlerRecord;
2993
2994 static IOHandlerRecord *first_io_handler;
2995
2996 /* XXX: fd_read_poll should be suppressed, but an API change is
2997    necessary in the character devices to suppress fd_can_read(). */
2998 int qemu_set_fd_handler2(int fd, 
2999                          IOCanRWHandler *fd_read_poll, 
3000                          IOHandler *fd_read, 
3001                          IOHandler *fd_write, 
3002                          void *opaque)
3003 {
3004     IOHandlerRecord **pioh, *ioh;
3005
3006     if (!fd_read && !fd_write) {
3007         pioh = &first_io_handler;
3008         for(;;) {
3009             ioh = *pioh;
3010             if (ioh == NULL)
3011                 break;
3012             if (ioh->fd == fd) {
3013                 *pioh = ioh->next;
3014                 qemu_free(ioh);
3015                 break;
3016             }
3017             pioh = &ioh->next;
3018         }
3019     } else {
3020         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3021             if (ioh->fd == fd)
3022                 goto found;
3023         }
3024         ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3025         if (!ioh)
3026             return -1;
3027         ioh->next = first_io_handler;
3028         first_io_handler = ioh;
3029     found:
3030         ioh->fd = fd;
3031         ioh->fd_read_poll = fd_read_poll;
3032         ioh->fd_read = fd_read;
3033         ioh->fd_write = fd_write;
3034         ioh->opaque = opaque;
3035     }
3036     return 0;
3037 }
3038
3039 int qemu_set_fd_handler(int fd, 
3040                         IOHandler *fd_read, 
3041                         IOHandler *fd_write, 
3042                         void *opaque)
3043 {
3044     return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3045 }
3046
3047 /***********************************************************/
3048 /* savevm/loadvm support */
3049
3050 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3051 {
3052     fwrite(buf, 1, size, f);
3053 }
3054
3055 void qemu_put_byte(QEMUFile *f, int v)
3056 {
3057     fputc(v, f);
3058 }
3059
3060 void qemu_put_be16(QEMUFile *f, unsigned int v)
3061 {
3062     qemu_put_byte(f, v >> 8);
3063     qemu_put_byte(f, v);
3064 }
3065
3066 void qemu_put_be32(QEMUFile *f, unsigned int v)
3067 {
3068     qemu_put_byte(f, v >> 24);
3069     qemu_put_byte(f, v >> 16);
3070     qemu_put_byte(f, v >> 8);
3071     qemu_put_byte(f, v);
3072 }
3073
3074 void qemu_put_be64(QEMUFile *f, uint64_t v)
3075 {
3076     qemu_put_be32(f, v >> 32);
3077     qemu_put_be32(f, v);
3078 }
3079
3080 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3081 {
3082     return fread(buf, 1, size, f);
3083 }
3084
3085 int qemu_get_byte(QEMUFile *f)
3086 {
3087     int v;
3088     v = fgetc(f);
3089     if (v == EOF)
3090         return 0;
3091     else
3092         return v;
3093 }
3094
3095 unsigned int qemu_get_be16(QEMUFile *f)
3096 {
3097     unsigned int v;
3098     v = qemu_get_byte(f) << 8;
3099     v |= qemu_get_byte(f);
3100     return v;
3101 }
3102
3103 unsigned int qemu_get_be32(QEMUFile *f)
3104 {
3105     unsigned int v;
3106     v = qemu_get_byte(f) << 24;
3107     v |= qemu_get_byte(f) << 16;
3108     v |= qemu_get_byte(f) << 8;
3109     v |= qemu_get_byte(f);
3110     return v;
3111 }
3112
3113 uint64_t qemu_get_be64(QEMUFile *f)
3114 {
3115     uint64_t v;
3116     v = (uint64_t)qemu_get_be32(f) << 32;
3117     v |= qemu_get_be32(f);
3118     return v;
3119 }
3120
3121 int64_t qemu_ftell(QEMUFile *f)
3122 {
3123     return ftell(f);
3124 }
3125
3126 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3127 {
3128     if (fseek(f, pos, whence) < 0)
3129         return -1;
3130     return ftell(f);
3131 }
3132
3133 typedef struct SaveStateEntry {
3134     char idstr[256];
3135     int instance_id;
3136     int version_id;
3137     SaveStateHandler *save_state;
3138     LoadStateHandler *load_state;
3139     void *opaque;
3140     struct SaveStateEntry *next;
3141 } SaveStateEntry;
3142
3143 static SaveStateEntry *first_se;
3144
3145 int register_savevm(const char *idstr, 
3146                     int instance_id, 
3147                     int version_id,
3148                     SaveStateHandler *save_state,
3149                     LoadStateHandler *load_state,
3150                     void *opaque)
3151 {
3152     SaveStateEntry *se, **pse;
3153
3154     se = qemu_malloc(sizeof(SaveStateEntry));
3155     if (!se)
3156         return -1;
3157     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3158     se->instance_id = instance_id;
3159     se->version_id = version_id;
3160     se->save_state = save_state;
3161     se->load_state = load_state;
3162     se->opaque = opaque;
3163     se->next = NULL;
3164
3165     /* add at the end of list */
3166     pse = &first_se;
3167     while (*pse != NULL)
3168         pse = &(*pse)->next;
3169     *pse = se;
3170     return 0;
3171 }
3172
3173 #define QEMU_VM_FILE_MAGIC   0x5145564d
3174 #define QEMU_VM_FILE_VERSION 0x00000001
3175
3176 int qemu_savevm(const char *filename)
3177 {
3178     SaveStateEntry *se;
3179     QEMUFile *f;
3180     int len, len_pos, cur_pos, saved_vm_running, ret;
3181
3182     saved_vm_running = vm_running;
3183     vm_stop(0);
3184
3185     f = fopen(filename, "wb");
3186     if (!f) {
3187         ret = -1;
3188         goto the_end;
3189     }
3190
3191     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3192     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3193
3194     for(se = first_se; se != NULL; se = se->next) {
3195         /* ID string */
3196         len = strlen(se->idstr);
3197         qemu_put_byte(f, len);
3198         qemu_put_buffer(f, se->idstr, len);
3199
3200         qemu_put_be32(f, se->instance_id);
3201         qemu_put_be32(f, se->version_id);
3202
3203         /* record size: filled later */
3204         len_pos = ftell(f);
3205         qemu_put_be32(f, 0);
3206         
3207         se->save_state(f, se->opaque);
3208
3209         /* fill record size */
3210         cur_pos = ftell(f);
3211         len = ftell(f) - len_pos - 4;
3212         fseek(f, len_pos, SEEK_SET);
3213         qemu_put_be32(f, len);
3214         fseek(f, cur_pos, SEEK_SET);
3215     }
3216
3217     fclose(f);
3218     ret = 0;
3219  the_end:
3220     if (saved_vm_running)
3221         vm_start();
3222     return ret;
3223 }
3224
3225 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3226 {
3227     SaveStateEntry *se;
3228
3229     for(se = first_se; se != NULL; se = se->next) {
3230         if (!strcmp(se->idstr, idstr) && 
3231             instance_id == se->instance_id)
3232             return se;
3233     }
3234     return NULL;
3235 }
3236
3237 int qemu_loadvm(const char *filename)
3238 {
3239     SaveStateEntry *se;
3240     QEMUFile *f;
3241     int len, cur_pos, ret, instance_id, record_len, version_id;
3242     int saved_vm_running;
3243     unsigned int v;
3244     char idstr[256];
3245     
3246     saved_vm_running = vm_running;
3247     vm_stop(0);
3248
3249     f = fopen(filename, "rb");
3250     if (!f) {
3251         ret = -1;
3252         goto the_end;
3253     }
3254
3255     v = qemu_get_be32(f);
3256     if (v != QEMU_VM_FILE_MAGIC)
3257         goto fail;
3258     v = qemu_get_be32(f);
3259     if (v != QEMU_VM_FILE_VERSION) {
3260     fail:
3261         fclose(f);
3262         ret = -1;
3263         goto the_end;
3264     }
3265     for(;;) {
3266         len = qemu_get_byte(f);
3267         if (feof(f))
3268             break;
3269         qemu_get_buffer(f, idstr, len);
3270         idstr[len] = '\0';
3271         instance_id = qemu_get_be32(f);
3272         version_id = qemu_get_be32(f);
3273         record_len = qemu_get_be32(f);
3274 #if 0
3275         printf("idstr=%s instance=0x%x version=%d len=%d\n", 
3276                idstr, instance_id, version_id, record_len);
3277 #endif
3278         cur_pos = ftell(f);
3279         se = find_se(idstr, instance_id);
3280         if (!se) {
3281             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
3282                     instance_id, idstr);
3283         } else {
3284             ret = se->load_state(f, se->opaque, version_id);
3285             if (ret < 0) {
3286                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
3287                         instance_id, idstr);
3288             }
3289         }
3290         /* always seek to exact end of record */
3291         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3292     }
3293     fclose(f);
3294     ret = 0;
3295  the_end:
3296     if (saved_vm_running)
3297         vm_start();
3298     return ret;
3299 }
3300
3301 /***********************************************************/
3302 /* cpu save/restore */
3303
3304 #if defined(TARGET_I386)
3305
3306 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3307 {
3308     qemu_put_be32(f, dt->selector);
3309     qemu_put_betl(f, dt->base);
3310     qemu_put_be32(f, dt->limit);
3311     qemu_put_be32(f, dt->flags);
3312 }
3313
3314 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3315 {
3316     dt->selector = qemu_get_be32(f);
3317     dt->base = qemu_get_betl(f);
3318     dt->limit = qemu_get_be32(f);
3319     dt->flags = qemu_get_be32(f);
3320 }
3321
3322 void cpu_save(QEMUFile *f, void *opaque)
3323 {
3324     CPUState *env = opaque;
3325     uint16_t fptag, fpus, fpuc, fpregs_format;
3326     uint32_t hflags;
3327     int i;
3328     
3329     for(i = 0; i < CPU_NB_REGS; i++)
3330         qemu_put_betls(f, &env->regs[i]);
3331     qemu_put_betls(f, &env->eip);
3332     qemu_put_betls(f, &env->eflags);
3333     hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3334     qemu_put_be32s(f, &hflags);
3335     
3336     /* FPU */
3337     fpuc = env->fpuc;
3338     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3339     fptag = 0;
3340     for(i = 0; i < 8; i++) {
3341         fptag |= ((!env->fptags[i]) << i);
3342     }
3343     
3344     qemu_put_be16s(f, &fpuc);
3345     qemu_put_be16s(f, &fpus);
3346     qemu_put_be16s(f, &fptag);
3347
3348 #ifdef USE_X86LDOUBLE
3349     fpregs_format = 0;
3350 #else
3351     fpregs_format = 1;
3352 #endif
3353     qemu_put_be16s(f, &fpregs_format);
3354     
3355     for(i = 0; i < 8; i++) {
3356 #ifdef USE_X86LDOUBLE
3357         {
3358             uint64_t mant;
3359             uint16_t exp;
3360             /* we save the real CPU data (in case of MMX usage only 'mant'
3361                contains the MMX register */
3362             cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3363             qemu_put_be64(f, mant);
3364             qemu_put_be16(f, exp);
3365         }
3366 #else
3367         /* if we use doubles for float emulation, we save the doubles to
3368            avoid losing information in case of MMX usage. It can give
3369            problems if the image is restored on a CPU where long
3370            doubles are used instead. */
3371         qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3372 #endif
3373     }
3374
3375     for(i = 0; i < 6; i++)
3376         cpu_put_seg(f, &env->segs[i]);
3377     cpu_put_seg(f, &env->ldt);
3378     cpu_put_seg(f, &env->tr);
3379     cpu_put_seg(f, &env->gdt);
3380     cpu_put_seg(f, &env->idt);
3381     
3382     qemu_put_be32s(f, &env->sysenter_cs);
3383     qemu_put_be32s(f, &env->sysenter_esp);
3384     qemu_put_be32s(f, &env->sysenter_eip);
3385     
3386     qemu_put_betls(f, &env->cr[0]);
3387     qemu_put_betls(f, &env->cr[2]);
3388     qemu_put_betls(f, &env->cr[3]);
3389     qemu_put_betls(f, &env->cr[4]);
3390     
3391     for(i = 0; i < 8; i++)
3392         qemu_put_betls(f, &env->dr[i]);
3393
3394     /* MMU */
3395     qemu_put_be32s(f, &env->a20_mask);
3396
3397     /* XMM */
3398     qemu_put_be32s(f, &env->mxcsr);
3399     for(i = 0; i < CPU_NB_REGS; i++) {
3400         qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3401         qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3402     }
3403
3404 #ifdef TARGET_X86_64
3405     qemu_put_be64s(f, &env->efer);
3406     qemu_put_be64s(f, &env->star);
3407     qemu_put_be64s(f, &env->lstar);
3408     qemu_put_be64s(f, &env->cstar);
3409     qemu_put_be64s(f, &env->fmask);
3410     qemu_put_be64s(f, &env->kernelgsbase);
3411 #endif
3412 }
3413
3414 #ifdef USE_X86LDOUBLE
3415 /* XXX: add that in a FPU generic layer */
3416 union x86_longdouble {
3417     uint64_t mant;
3418     uint16_t exp;
3419 };
3420
3421 #define MANTD1(fp)      (fp & ((1LL << 52) - 1))
3422 #define EXPBIAS1 1023
3423 #define EXPD1(fp)       ((fp >> 52) & 0x7FF)
3424 #define SIGND1(fp)      ((fp >> 32) & 0x80000000)
3425
3426 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3427 {
3428     int e;
3429     /* mantissa */
3430     p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3431     /* exponent + sign */
3432     e = EXPD1(temp) - EXPBIAS1 + 16383;
3433     e |= SIGND1(temp) >> 16;
3434     p->exp = e;
3435 }
3436 #endif
3437
3438 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3439 {
3440     CPUState *env = opaque;
3441     int i, guess_mmx;
3442     uint32_t hflags;
3443     uint16_t fpus, fpuc, fptag, fpregs_format;
3444
3445     if (version_id != 3)
3446         return -EINVAL;
3447     for(i = 0; i < CPU_NB_REGS; i++)
3448         qemu_get_betls(f, &env->regs[i]);
3449     qemu_get_betls(f, &env->eip);
3450     qemu_get_betls(f, &env->eflags);
3451     qemu_get_be32s(f, &hflags);
3452
3453     qemu_get_be16s(f, &fpuc);
3454     qemu_get_be16s(f, &fpus);
3455     qemu_get_be16s(f, &fptag);
3456     qemu_get_be16s(f, &fpregs_format);
3457     
3458     /* NOTE: we cannot always restore the FPU state if the image come
3459        from a host with a different 'USE_X86LDOUBLE' define. We guess
3460        if we are in an MMX state to restore correctly in that case. */
3461     guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3462     for(i = 0; i < 8; i++) {
3463         uint64_t mant;
3464         uint16_t exp;
3465         
3466         switch(fpregs_format) {
3467         case 0:
3468             mant = qemu_get_be64(f);
3469             exp = qemu_get_be16(f);
3470 #ifdef USE_X86LDOUBLE
3471             env->fpregs[i].d = cpu_set_fp80(mant, exp);
3472 #else
3473             /* difficult case */
3474             if (guess_mmx)
3475                 env->fpregs[i].mmx.MMX_Q(0) = mant;
3476             else
3477                 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3478 #endif
3479             break;
3480         case 1:
3481             mant = qemu_get_be64(f);
3482 #ifdef USE_X86LDOUBLE
3483             {
3484                 union x86_longdouble *p;
3485                 /* difficult case */
3486                 p = (void *)&env->fpregs[i];
3487                 if (guess_mmx) {
3488                     p->mant = mant;
3489                     p->exp = 0xffff;
3490                 } else {
3491                     fp64_to_fp80(p, mant);
3492                 }
3493             }
3494 #else
3495             env->fpregs[i].mmx.MMX_Q(0) = mant;
3496 #endif            
3497             break;
3498         default:
3499             return -EINVAL;
3500         }
3501     }
3502
3503     env->fpuc = fpuc;
3504     /* XXX: restore FPU round state */
3505     env->fpstt = (fpus >> 11) & 7;
3506     env->fpus = fpus & ~0x3800;
3507     fptag ^= 0xff;
3508     for(i = 0; i < 8; i++) {
3509         env->fptags[i] = (fptag >> i) & 1;
3510     }
3511     
3512     for(i = 0; i < 6; i++)
3513         cpu_get_seg(f, &env->segs[i]);
3514     cpu_get_seg(f, &env->ldt);
3515     cpu_get_seg(f, &env->tr);
3516     cpu_get_seg(f, &env->gdt);
3517     cpu_get_seg(f, &env->idt);
3518     
3519     qemu_get_be32s(f, &env->sysenter_cs);
3520     qemu_get_be32s(f, &env->sysenter_esp);
3521     qemu_get_be32s(f, &env->sysenter_eip);
3522     
3523     qemu_get_betls(f, &env->cr[0]);
3524     qemu_get_betls(f, &env->cr[2]);
3525     qemu_get_betls(f, &env->cr[3]);
3526     qemu_get_betls(f, &env->cr[4]);
3527     
3528     for(i = 0; i < 8; i++)
3529         qemu_get_betls(f, &env->dr[i]);
3530
3531     /* MMU */
3532     qemu_get_be32s(f, &env->a20_mask);
3533
3534     qemu_get_be32s(f, &env->mxcsr);
3535     for(i = 0; i < CPU_NB_REGS; i++) {
3536         qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3537         qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3538     }
3539
3540 #ifdef TARGET_X86_64
3541     qemu_get_be64s(f, &env->efer);
3542     qemu_get_be64s(f, &env->star);
3543     qemu_get_be64s(f, &env->lstar);
3544     qemu_get_be64s(f, &env->cstar);
3545     qemu_get_be64s(f, &env->fmask);
3546     qemu_get_be64s(f, &env->kernelgsbase);
3547 #endif
3548
3549     /* XXX: compute hflags from scratch, except for CPL and IIF */
3550     env->hflags = hflags;
3551     tlb_flush(env, 1);
3552     return 0;
3553 }
3554
3555 #elif defined(TARGET_PPC)
3556 void cpu_save(QEMUFile *f, void *opaque)
3557 {
3558 }
3559
3560 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3561 {
3562     return 0;
3563 }
3564
3565 #elif defined(TARGET_MIPS)
3566 void cpu_save(QEMUFile *f, void *opaque)
3567 {
3568 }
3569
3570 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3571 {
3572     return 0;
3573 }
3574
3575 #elif defined(TARGET_SPARC)
3576 void cpu_save(QEMUFile *f, void *opaque)
3577 {
3578     CPUState *env = opaque;
3579     int i;
3580     uint32_t tmp;
3581
3582     for(i = 0; i < 8; i++)
3583         qemu_put_betls(f, &env->gregs[i]);
3584     for(i = 0; i < NWINDOWS * 16; i++)
3585         qemu_put_betls(f, &env->regbase[i]);
3586
3587     /* FPU */
3588     for(i = 0; i < TARGET_FPREGS; i++) {
3589         union {
3590             TARGET_FPREG_T f;
3591             target_ulong i;
3592         } u;
3593         u.f = env->fpr[i];
3594         qemu_put_betl(f, u.i);
3595     }
3596
3597     qemu_put_betls(f, &env->pc);
3598     qemu_put_betls(f, &env->npc);
3599     qemu_put_betls(f, &env->y);
3600     tmp = GET_PSR(env);
3601     qemu_put_be32(f, tmp);
3602     qemu_put_betls(f, &env->fsr);
3603     qemu_put_betls(f, &env->tbr);
3604 #ifndef TARGET_SPARC64
3605     qemu_put_be32s(f, &env->wim);
3606     /* MMU */
3607     for(i = 0; i < 16; i++)
3608         qemu_put_be32s(f, &env->mmuregs[i]);
3609 #endif
3610 }
3611
3612 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3613 {
3614     CPUState *env = opaque;
3615     int i;
3616     uint32_t tmp;
3617
3618     for(i = 0; i < 8; i++)
3619         qemu_get_betls(f, &env->gregs[i]);
3620     for(i = 0; i < NWINDOWS * 16; i++)
3621         qemu_get_betls(f, &env->regbase[i]);
3622
3623     /* FPU */
3624     for(i = 0; i < TARGET_FPREGS; i++) {
3625         union {
3626             TARGET_FPREG_T f;
3627             target_ulong i;
3628         } u;
3629         u.i = qemu_get_betl(f);
3630         env->fpr[i] = u.f;
3631     }
3632
3633     qemu_get_betls(f, &env->pc);
3634     qemu_get_betls(f, &env->npc);
3635     qemu_get_betls(f, &env->y);
3636     tmp = qemu_get_be32(f);
3637     env->cwp = 0; /* needed to ensure that the wrapping registers are
3638                      correctly updated */
3639     PUT_PSR(env, tmp);
3640     qemu_get_betls(f, &env->fsr);
3641     qemu_get_betls(f, &env->tbr);
3642 #ifndef TARGET_SPARC64
3643     qemu_get_be32s(f, &env->wim);
3644     /* MMU */
3645     for(i = 0; i < 16; i++)
3646         qemu_get_be32s(f, &env->mmuregs[i]);
3647 #endif
3648     tlb_flush(env, 1);
3649     return 0;
3650 }
3651
3652 #elif defined(TARGET_ARM)
3653
3654 /* ??? Need to implement these.  */
3655 void cpu_save(QEMUFile *f, void *opaque)
3656 {
3657 }
3658
3659 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3660 {
3661     return 0;
3662 }
3663
3664 #else
3665
3666 #warning No CPU save/restore functions
3667
3668 #endif
3669
3670 /***********************************************************/
3671 /* ram save/restore */
3672
3673 /* we just avoid storing empty pages */
3674 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
3675 {
3676     int i, v;
3677
3678     v = buf[0];
3679     for(i = 1; i < len; i++) {
3680         if (buf[i] != v)
3681             goto normal_save;
3682     }
3683     qemu_put_byte(f, 1);
3684     qemu_put_byte(f, v);
3685     return;
3686  normal_save:
3687     qemu_put_byte(f, 0); 
3688     qemu_put_buffer(f, buf, len);
3689 }
3690
3691 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3692 {
3693     int v;
3694
3695     v = qemu_get_byte(f);
3696     switch(v) {
3697     case 0:
3698         if (qemu_get_buffer(f, buf, len) != len)
3699             return -EIO;
3700         break;
3701     case 1:
3702         v = qemu_get_byte(f);
3703         memset(buf, v, len);
3704         break;
3705     default:
3706         return -EINVAL;
3707     }
3708     return 0;
3709 }
3710
3711 static void ram_save(QEMUFile *f, void *opaque)
3712 {
3713     int i;
3714     qemu_put_be32(f, phys_ram_size);
3715     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3716         ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3717     }
3718 }
3719
3720 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3721 {
3722     int i, ret;
3723
3724     if (version_id != 1)
3725         return -EINVAL;
3726     if (qemu_get_be32(f) != phys_ram_size)
3727         return -EINVAL;
3728     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3729         ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3730         if (ret)
3731             return ret;
3732     }
3733     return 0;
3734 }
3735
3736 /***********************************************************/
3737 /* machine registration */
3738
3739 QEMUMachine *first_machine = NULL;
3740
3741 int qemu_register_machine(QEMUMachine *m)
3742 {
3743     QEMUMachine **pm;
3744     pm = &first_machine;
3745     while (*pm != NULL)
3746         pm = &(*pm)->next;
3747     m->next = NULL;
3748     *pm = m;
3749     return 0;
3750 }
3751
3752 QEMUMachine *find_machine(const char *name)
3753 {
3754     QEMUMachine *m;
3755
3756     for(m = first_machine; m != NULL; m = m->next) {
3757         if (!strcmp(m->name, name))
3758             return m;
3759     }
3760     return NULL;
3761 }
3762
3763 /***********************************************************/
3764 /* main execution loop */
3765
3766 void gui_update(void *opaque)
3767 {
3768     display_state.dpy_refresh(&display_state);
3769     qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
3770 }
3771
3772 struct vm_change_state_entry {
3773     VMChangeStateHandler *cb;
3774     void *opaque;
3775     LIST_ENTRY (vm_change_state_entry) entries;
3776 };
3777
3778 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3779
3780 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3781                                                      void *opaque)
3782 {
3783     VMChangeStateEntry *e;
3784
3785     e = qemu_mallocz(sizeof (*e));
3786     if (!e)
3787         return NULL;
3788
3789     e->cb = cb;
3790     e->opaque = opaque;
3791     LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3792     return e;
3793 }
3794
3795 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3796 {
3797     LIST_REMOVE (e, entries);
3798     qemu_free (e);
3799 }
3800
3801 static void vm_state_notify(int running)
3802 {
3803     VMChangeStateEntry *e;
3804
3805     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3806         e->cb(e->opaque, running);
3807     }
3808 }
3809
3810 /* XXX: support several handlers */
3811 static VMStopHandler *vm_stop_cb;
3812 static void *vm_stop_opaque;
3813
3814 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3815 {
3816     vm_stop_cb = cb;
3817     vm_stop_opaque = opaque;
3818     return 0;
3819 }
3820
3821 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3822 {
3823     vm_stop_cb = NULL;
3824 }
3825
3826 void vm_start(void)
3827 {
3828     if (!vm_running) {
3829         cpu_enable_ticks();
3830         vm_running = 1;
3831         vm_state_notify(1);
3832     }
3833 }
3834
3835 void vm_stop(int reason) 
3836 {
3837     if (vm_running) {
3838         cpu_disable_ticks();
3839         vm_running = 0;
3840         if (reason != 0) {
3841             if (vm_stop_cb) {
3842                 vm_stop_cb(vm_stop_opaque, reason);
3843             }
3844         }
3845         vm_state_notify(0);
3846     }
3847 }
3848
3849 /* reset/shutdown handler */
3850
3851 typedef struct QEMUResetEntry {
3852     QEMUResetHandler *func;
3853     void *opaque;
3854     struct QEMUResetEntry *next;
3855 } QEMUResetEntry;
3856
3857 static QEMUResetEntry *first_reset_entry;
3858 static int reset_requested;
3859 static int shutdown_requested;
3860 static int powerdown_requested;
3861
3862 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3863 {
3864     QEMUResetEntry **pre, *re;
3865
3866     pre = &first_reset_entry;
3867     while (*pre != NULL)
3868         pre = &(*pre)->next;
3869     re = qemu_mallocz(sizeof(QEMUResetEntry));
3870     re->func = func;
3871     re->opaque = opaque;
3872     re->next = NULL;
3873     *pre = re;
3874 }
3875
3876 void qemu_system_reset(void)
3877 {
3878     QEMUResetEntry *re;
3879
3880     /* reset all devices */
3881     for(re = first_reset_entry; re != NULL; re = re->next) {
3882         re->func(re->opaque);
3883     }
3884 }
3885
3886 void qemu_system_reset_request(void)
3887 {
3888     reset_requested = 1;
3889     if (cpu_single_env)
3890         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3891 }
3892
3893 void qemu_system_shutdown_request(void)
3894 {
3895     shutdown_requested = 1;
3896     if (cpu_single_env)
3897         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3898 }
3899
3900 void qemu_system_powerdown_request(void)
3901 {
3902     powerdown_requested = 1;
3903     if (cpu_single_env)
3904         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3905 }
3906
3907 void main_loop_wait(int timeout)
3908 {
3909     IOHandlerRecord *ioh, *ioh_next;
3910     fd_set rfds, wfds;
3911     int ret, nfds;
3912     struct timeval tv;
3913
3914 #ifdef _WIN32
3915     /* XXX: see how to merge it with the select. The constraint is
3916        that the select must be interrupted by the timer */
3917     if (timeout > 0)
3918         Sleep(timeout);
3919 #endif
3920     /* poll any events */
3921     /* XXX: separate device handlers from system ones */
3922     nfds = -1;
3923     FD_ZERO(&rfds);
3924     FD_ZERO(&wfds);
3925     for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3926         if (ioh->fd_read &&
3927             (!ioh->fd_read_poll ||
3928              ioh->fd_read_poll(ioh->opaque) != 0)) {
3929             FD_SET(ioh->fd, &rfds);
3930             if (ioh->fd > nfds)
3931                 nfds = ioh->fd;
3932         }
3933         if (ioh->fd_write) {
3934             FD_SET(ioh->fd, &wfds);
3935             if (ioh->fd > nfds)
3936                 nfds = ioh->fd;
3937         }
3938     }
3939     
3940     tv.tv_sec = 0;
3941 #ifdef _WIN32
3942     tv.tv_usec = 0;
3943 #else
3944     tv.tv_usec = timeout * 1000;
3945 #endif
3946     ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
3947     if (ret > 0) {
3948         /* XXX: better handling of removal */
3949         for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
3950             ioh_next = ioh->next;
3951             if (FD_ISSET(ioh->fd, &rfds)) {
3952                 ioh->fd_read(ioh->opaque);
3953             }
3954             if (FD_ISSET(ioh->fd, &wfds)) {
3955                 ioh->fd_write(ioh->opaque);
3956             }
3957         }
3958     }
3959 #ifdef _WIN32
3960     tap_win32_poll();
3961 #endif
3962
3963 #if defined(CONFIG_SLIRP)
3964     /* XXX: merge with the previous select() */
3965     if (slirp_inited) {
3966         fd_set rfds, wfds, xfds;
3967         int nfds;
3968         struct timeval tv;
3969         
3970         nfds = -1;
3971         FD_ZERO(&rfds);
3972         FD_ZERO(&wfds);
3973         FD_ZERO(&xfds);
3974         slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3975         tv.tv_sec = 0;
3976         tv.tv_usec = 0;
3977         ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3978         if (ret >= 0) {
3979             slirp_select_poll(&rfds, &wfds, &xfds);
3980         }
3981     }
3982 #endif
3983
3984     if (vm_running) {
3985         qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
3986                         qemu_get_clock(vm_clock));
3987         /* run dma transfers, if any */
3988         DMA_run();
3989     }
3990     
3991     /* real time timers */
3992     qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
3993                     qemu_get_clock(rt_clock));
3994 }
3995
3996 static CPUState *cur_cpu;
3997
3998 int main_loop(void)
3999 {
4000     int ret, timeout;
4001     CPUState *env;
4002
4003     cur_cpu = first_cpu;
4004     for(;;) {
4005         if (vm_running) {
4006
4007             env = cur_cpu;
4008             for(;;) {
4009                 /* get next cpu */
4010                 env = env->next_cpu;
4011                 if (!env)
4012                     env = first_cpu;
4013                 ret = cpu_exec(env);
4014                 if (ret != EXCP_HALTED)
4015                     break;
4016                 /* all CPUs are halted ? */
4017                 if (env == cur_cpu) {
4018                     ret = EXCP_HLT;
4019                     break;
4020                 }
4021             }
4022             cur_cpu = env;
4023
4024             if (shutdown_requested) {
4025                 ret = EXCP_INTERRUPT;
4026                 break;
4027             }
4028             if (reset_requested) {
4029                 reset_requested = 0;
4030                 qemu_system_reset();
4031                 ret = EXCP_INTERRUPT;
4032             }
4033             if (powerdown_requested) {
4034                 powerdown_requested = 0;
4035                 qemu_system_powerdown();
4036                 ret = EXCP_INTERRUPT;
4037             }
4038             if (ret == EXCP_DEBUG) {
4039                 vm_stop(EXCP_DEBUG);
4040             }
4041             /* if hlt instruction, we wait until the next IRQ */
4042             /* XXX: use timeout computed from timers */
4043             if (ret == EXCP_HLT)
4044                 timeout = 10;
4045             else
4046                 timeout = 0;
4047         } else {
4048             timeout = 10;
4049         }
4050         main_loop_wait(timeout);
4051     }
4052     cpu_disable_ticks();
4053     return ret;
4054 }
4055
4056 void help(void)
4057 {
4058     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4059            "usage: %s [options] [disk_image]\n"
4060            "\n"
4061            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4062            "\n"
4063            "Standard options:\n"
4064            "-M machine      select emulated machine (-M ? for list)\n"
4065            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
4066            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
4067            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
4068            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4069            "-boot [a|c|d]   boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4070            "-snapshot       write to temporary files instead of disk image files\n"
4071            "-m megs         set virtual RAM size to megs MB [default=%d]\n"
4072            "-smp n          set the number of CPUs to 'n' [default=1]\n"
4073            "-nographic      disable graphical output and redirect serial I/Os to console\n"
4074 #ifndef _WIN32
4075            "-k language     use keyboard layout (for example \"fr\" for French)\n"
4076 #endif
4077 #ifdef HAS_AUDIO
4078            "-audio-help     print list of audio drivers and their options\n"
4079            "-soundhw c1,... enable audio support\n"
4080            "                and only specified sound cards (comma separated list)\n"
4081            "                use -soundhw ? to get the list of supported cards\n"
4082            "                use -soundhw all to enable all of them\n"
4083 #endif
4084            "-localtime      set the real time clock to local time [default=utc]\n"
4085            "-full-screen    start in full screen\n"
4086 #ifdef TARGET_I386
4087            "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
4088 #endif
4089            "-usb            enable the USB driver (will be the default soon)\n"
4090            "-usbdevice name add the host or guest USB device 'name'\n"
4091 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4092            "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
4093 #endif
4094            "\n"
4095            "Network options:\n"
4096            "-net nic[,vlan=n][,macaddr=addr]\n"
4097            "                create a new Network Interface Card and connect it to VLAN 'n'\n"
4098 #ifdef CONFIG_SLIRP
4099            "-net user[,vlan=n]\n"
4100            "                connect the user mode network stack to VLAN 'n'\n"
4101 #endif
4102 #ifdef _WIN32
4103            "-net tap[,vlan=n],ifname=name\n"
4104            "                connect the host TAP network interface to VLAN 'n'\n"
4105 #else
4106            "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4107            "                connect the host TAP network interface to VLAN 'n' and use\n"
4108            "                the network script 'file' (default=%s);\n"
4109            "                use 'fd=h' to connect to an already opened TAP interface\n"
4110 #endif
4111            "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4112            "                connect the vlan 'n' to another VLAN using a socket connection\n"
4113            "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4114            "                connect the vlan 'n' to multicast maddr and port\n"
4115            "-net none       use it alone to have zero network devices; if no -net option\n"
4116            "                is provided, the default is '-net nic -net user'\n"
4117            "\n"
4118 #ifdef CONFIG_SLIRP
4119            "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
4120 #ifndef _WIN32
4121            "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
4122 #endif
4123            "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4124            "                redirect TCP or UDP connections from host to guest [-net user]\n"
4125 #endif
4126            "\n"
4127            "Linux boot specific:\n"
4128            "-kernel bzImage use 'bzImage' as kernel image\n"
4129            "-append cmdline use 'cmdline' as kernel command line\n"
4130            "-initrd file    use 'file' as initial ram disk\n"
4131            "\n"
4132            "Debug/Expert options:\n"
4133            "-monitor dev    redirect the monitor to char device 'dev'\n"
4134            "-serial dev     redirect the serial port to char device 'dev'\n"
4135            "-parallel dev   redirect the parallel port to char device 'dev'\n"
4136            "-pidfile file   Write PID to 'file'\n"
4137            "-S              freeze CPU at startup (use 'c' to start execution)\n"
4138            "-s              wait gdb connection to port %d\n"
4139            "-p port         change gdb connection port\n"
4140            "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
4141            "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
4142            "                translation (t=none or lba) (usually qemu can guess them)\n"
4143            "-L path         set the directory for the BIOS and VGA BIOS\n"
4144 #ifdef USE_KQEMU
4145            "-no-kqemu       disable KQEMU kernel module usage\n"
4146 #endif
4147 #ifdef USE_CODE_COPY
4148            "-no-code-copy   disable code copy acceleration\n"
4149 #endif
4150 #ifdef TARGET_I386
4151            "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
4152            "                (default is CL-GD5446 PCI VGA)\n"
4153 #endif
4154            "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
4155            "\n"
4156            "During emulation, the following keys are useful:\n"
4157            "ctrl-alt-f      toggle full screen\n"
4158            "ctrl-alt-n      switch to virtual console 'n'\n"
4159            "ctrl-alt        toggle mouse and keyboard grab\n"
4160            "\n"
4161            "When using -nographic, press 'ctrl-a h' to get some help.\n"
4162            ,
4163 #ifdef CONFIG_SOFTMMU
4164            "qemu",
4165 #else
4166            "qemu-fast",
4167 #endif
4168            DEFAULT_RAM_SIZE,
4169 #ifndef _WIN32
4170            DEFAULT_NETWORK_SCRIPT,
4171 #endif
4172            DEFAULT_GDBSTUB_PORT,
4173            "/tmp/qemu.log");
4174 #ifndef CONFIG_SOFTMMU
4175     printf("\n"
4176            "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4177            "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4178            "PC emulation.\n");
4179 #endif
4180     exit(1);
4181 }
4182
4183 #define HAS_ARG 0x0001
4184
4185 enum {
4186     QEMU_OPTION_h,
4187
4188     QEMU_OPTION_M,
4189     QEMU_OPTION_fda,
4190     QEMU_OPTION_fdb,
4191     QEMU_OPTION_hda,
4192     QEMU_OPTION_hdb,
4193     QEMU_OPTION_hdc,
4194     QEMU_OPTION_hdd,
4195     QEMU_OPTION_cdrom,
4196     QEMU_OPTION_boot,
4197     QEMU_OPTION_snapshot,
4198     QEMU_OPTION_m,
4199     QEMU_OPTION_nographic,
4200 #ifdef HAS_AUDIO
4201     QEMU_OPTION_audio_help,
4202     QEMU_OPTION_soundhw,
4203 #endif
4204
4205     QEMU_OPTION_net,
4206     QEMU_OPTION_tftp,
4207     QEMU_OPTION_smb,
4208     QEMU_OPTION_redir,
4209
4210     QEMU_OPTION_kernel,
4211     QEMU_OPTION_append,
4212     QEMU_OPTION_initrd,
4213
4214     QEMU_OPTION_S,
4215     QEMU_OPTION_s,
4216     QEMU_OPTION_p,
4217     QEMU_OPTION_d,
4218     QEMU_OPTION_hdachs,
4219     QEMU_OPTION_L,
4220     QEMU_OPTION_no_code_copy,
4221     QEMU_OPTION_k,
4222     QEMU_OPTION_localtime,
4223     QEMU_OPTION_cirrusvga,
4224     QEMU_OPTION_g,
4225     QEMU_OPTION_std_vga,
4226     QEMU_OPTION_monitor,
4227     QEMU_OPTION_serial,
4228     QEMU_OPTION_parallel,
4229     QEMU_OPTION_loadvm,
4230     QEMU_OPTION_full_screen,
4231     QEMU_OPTION_pidfile,
4232     QEMU_OPTION_no_kqemu,
4233     QEMU_OPTION_win2k_hack,
4234     QEMU_OPTION_usb,
4235     QEMU_OPTION_usbdevice,
4236     QEMU_OPTION_smp,
4237 };
4238
4239 typedef struct QEMUOption {
4240     const char *name;
4241     int flags;
4242     int index;
4243 } QEMUOption;
4244
4245 const QEMUOption qemu_options[] = {
4246     { "h", 0, QEMU_OPTION_h },
4247
4248     { "M", HAS_ARG, QEMU_OPTION_M },
4249     { "fda", HAS_ARG, QEMU_OPTION_fda },
4250     { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4251     { "hda", HAS_ARG, QEMU_OPTION_hda },
4252     { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4253     { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4254     { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4255     { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4256     { "boot", HAS_ARG, QEMU_OPTION_boot },
4257     { "snapshot", 0, QEMU_OPTION_snapshot },
4258     { "m", HAS_ARG, QEMU_OPTION_m },
4259     { "nographic", 0, QEMU_OPTION_nographic },
4260     { "k", HAS_ARG, QEMU_OPTION_k },
4261 #ifdef HAS_AUDIO
4262     { "audio-help", 0, QEMU_OPTION_audio_help },
4263     { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4264 #endif
4265
4266     { "net", HAS_ARG, QEMU_OPTION_net},
4267 #ifdef CONFIG_SLIRP
4268     { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4269 #ifndef _WIN32
4270     { "smb", HAS_ARG, QEMU_OPTION_smb },
4271 #endif
4272     { "redir", HAS_ARG, QEMU_OPTION_redir },
4273 #endif
4274
4275     { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4276     { "append", HAS_ARG, QEMU_OPTION_append },
4277     { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4278
4279     { "S", 0, QEMU_OPTION_S },
4280     { "s", 0, QEMU_OPTION_s },
4281     { "p", HAS_ARG, QEMU_OPTION_p },
4282     { "d", HAS_ARG, QEMU_OPTION_d },
4283     { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4284     { "L", HAS_ARG, QEMU_OPTION_L },
4285     { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4286 #ifdef USE_KQEMU
4287     { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4288 #endif
4289 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4290     { "g", 1, QEMU_OPTION_g },
4291 #endif
4292     { "localtime", 0, QEMU_OPTION_localtime },
4293     { "std-vga", 0, QEMU_OPTION_std_vga },
4294     { "monitor", 1, QEMU_OPTION_monitor },
4295     { "serial", 1, QEMU_OPTION_serial },
4296     { "parallel", 1, QEMU_OPTION_parallel },
4297     { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4298     { "full-screen", 0, QEMU_OPTION_full_screen },
4299     { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4300     { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4301     { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4302     { "smp", HAS_ARG, QEMU_OPTION_smp },
4303     
4304     /* temporary options */
4305     { "usb", 0, QEMU_OPTION_usb },
4306     { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4307     { NULL },
4308 };
4309
4310 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4311
4312 /* this stack is only used during signal handling */
4313 #define SIGNAL_STACK_SIZE 32768
4314
4315 static uint8_t *signal_stack;
4316
4317 #endif
4318
4319 /* password input */
4320
4321 static BlockDriverState *get_bdrv(int index)
4322 {
4323     BlockDriverState *bs;
4324
4325     if (index < 4) {
4326         bs = bs_table[index];
4327     } else if (index < 6) {
4328         bs = fd_table[index - 4];
4329     } else {
4330         bs = NULL;
4331     }
4332     return bs;
4333 }
4334
4335 static void read_passwords(void)
4336 {
4337     BlockDriverState *bs;
4338     int i, j;
4339     char password[256];
4340
4341     for(i = 0; i < 6; i++) {
4342         bs = get_bdrv(i);
4343         if (bs && bdrv_is_encrypted(bs)) {
4344             term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4345             for(j = 0; j < 3; j++) {
4346                 monitor_readline("Password: ", 
4347                                  1, password, sizeof(password));
4348                 if (bdrv_set_key(bs, password) == 0)
4349                     break;
4350                 term_printf("invalid password\n");
4351             }
4352         }
4353     }
4354 }
4355
4356 /* XXX: currently we cannot use simultaneously different CPUs */
4357 void register_machines(void)
4358 {
4359 #if defined(TARGET_I386)
4360     qemu_register_machine(&pc_machine);
4361     qemu_register_machine(&isapc_machine);
4362 #elif defined(TARGET_PPC)
4363     qemu_register_machine(&heathrow_machine);
4364     qemu_register_machine(&core99_machine);
4365     qemu_register_machine(&prep_machine);
4366 #elif defined(TARGET_MIPS)
4367     qemu_register_machine(&mips_machine);
4368 #elif defined(TARGET_SPARC)
4369 #ifdef TARGET_SPARC64
4370     qemu_register_machine(&sun4u_machine);
4371 #else
4372     qemu_register_machine(&sun4m_machine);
4373 #endif
4374 #elif defined(TARGET_ARM)
4375     qemu_register_machine(&integratorcp_machine);
4376 #else
4377 #error unsupported CPU
4378 #endif
4379 }
4380
4381 #ifdef HAS_AUDIO
4382 struct soundhw soundhw[] = {
4383     {
4384         "sb16",
4385         "Creative Sound Blaster 16",
4386         0,
4387         1,
4388         { .init_isa = SB16_init }
4389     },
4390
4391 #ifdef CONFIG_ADLIB
4392     {
4393         "adlib",
4394 #ifdef HAS_YMF262
4395         "Yamaha YMF262 (OPL3)",
4396 #else
4397         "Yamaha YM3812 (OPL2)",
4398 #endif
4399         0,
4400         1,
4401         { .init_isa = Adlib_init }
4402     },
4403 #endif
4404
4405 #ifdef CONFIG_GUS
4406     {
4407         "gus",
4408         "Gravis Ultrasound GF1",
4409         0,
4410         1,
4411         { .init_isa = GUS_init }
4412     },
4413 #endif
4414
4415     {
4416         "es1370",
4417         "ENSONIQ AudioPCI ES1370",
4418         0,
4419         0,
4420         { .init_pci = es1370_init }
4421     },
4422
4423     { NULL, NULL, 0, 0, { NULL } }
4424 };
4425
4426 static void select_soundhw (const char *optarg)
4427 {
4428     struct soundhw *c;
4429
4430     if (*optarg == '?') {
4431     show_valid_cards:
4432
4433         printf ("Valid sound card names (comma separated):\n");
4434         for (c = soundhw; c->name; ++c) {
4435             printf ("%-11s %s\n", c->name, c->descr);
4436         }
4437         printf ("\n-soundhw all will enable all of the above\n");
4438         exit (*optarg != '?');
4439     }
4440     else {
4441         size_t l;
4442         const char *p;
4443         char *e;
4444         int bad_card = 0;
4445
4446         if (!strcmp (optarg, "all")) {
4447             for (c = soundhw; c->name; ++c) {
4448                 c->enabled = 1;
4449             }
4450             return;
4451         }
4452
4453         p = optarg;
4454         while (*p) {
4455             e = strchr (p, ',');
4456             l = !e ? strlen (p) : (size_t) (e - p);
4457
4458             for (c = soundhw; c->name; ++c) {
4459                 if (!strncmp (c->name, p, l)) {
4460                     c->enabled = 1;
4461                     break;
4462                 }
4463             }
4464
4465             if (!c->name) {
4466                 if (l > 80) {
4467                     fprintf (stderr,
4468                              "Unknown sound card name (too big to show)\n");
4469                 }
4470                 else {
4471                     fprintf (stderr, "Unknown sound card name `%.*s'\n",
4472                              (int) l, p);
4473                 }
4474                 bad_card = 1;
4475             }
4476             p += l + (e != NULL);
4477         }
4478
4479         if (bad_card)
4480             goto show_valid_cards;
4481     }
4482 }
4483 #endif
4484
4485 #define MAX_NET_CLIENTS 32
4486
4487 int main(int argc, char **argv)
4488 {
4489 #ifdef CONFIG_GDBSTUB
4490     int use_gdbstub, gdbstub_port;
4491 #endif
4492     int i, cdrom_index;
4493     int snapshot, linux_boot;
4494     const char *initrd_filename;
4495     const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4496     const char *kernel_filename, *kernel_cmdline;
4497     DisplayState *ds = &display_state;
4498     int cyls, heads, secs, translation;
4499     int start_emulation = 1;
4500     char net_clients[MAX_NET_CLIENTS][256];
4501     int nb_net_clients;
4502     int optind;
4503     const char *r, *optarg;
4504     CharDriverState *monitor_hd;
4505     char monitor_device[128];
4506     char serial_devices[MAX_SERIAL_PORTS][128];
4507     int serial_device_index;
4508     char parallel_devices[MAX_PARALLEL_PORTS][128];
4509     int parallel_device_index;
4510     const char *loadvm = NULL;
4511     QEMUMachine *machine;
4512     char usb_devices[MAX_VM_USB_PORTS][128];
4513     int usb_devices_index;
4514
4515     LIST_INIT (&vm_change_state_head);
4516 #if !defined(CONFIG_SOFTMMU)
4517     /* we never want that malloc() uses mmap() */
4518     mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
4519 #endif
4520     register_machines();
4521     machine = first_machine;
4522     initrd_filename = NULL;
4523     for(i = 0; i < MAX_FD; i++)
4524         fd_filename[i] = NULL;
4525     for(i = 0; i < MAX_DISKS; i++)
4526         hd_filename[i] = NULL;
4527     ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4528     vga_ram_size = VGA_RAM_SIZE;
4529     bios_size = BIOS_SIZE;
4530 #ifdef CONFIG_GDBSTUB
4531     use_gdbstub = 0;
4532     gdbstub_port = DEFAULT_GDBSTUB_PORT;
4533 #endif
4534     snapshot = 0;
4535     nographic = 0;
4536     kernel_filename = NULL;
4537     kernel_cmdline = "";
4538 #ifdef TARGET_PPC
4539     cdrom_index = 1;
4540 #else
4541     cdrom_index = 2;
4542 #endif
4543     cyls = heads = secs = 0;
4544     translation = BIOS_ATA_TRANSLATION_AUTO;
4545     pstrcpy(monitor_device, sizeof(monitor_device), "vc");
4546
4547     pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
4548     for(i = 1; i < MAX_SERIAL_PORTS; i++)
4549         serial_devices[i][0] = '\0';
4550     serial_device_index = 0;
4551     
4552     pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
4553     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4554         parallel_devices[i][0] = '\0';
4555     parallel_device_index = 0;
4556     
4557     usb_devices_index = 0;
4558     
4559     nb_net_clients = 0;
4560
4561     nb_nics = 0;
4562     /* default mac address of the first network interface */
4563     
4564     optind = 1;
4565     for(;;) {
4566         if (optind >= argc)
4567             break;
4568         r = argv[optind];
4569         if (r[0] != '-') {
4570             hd_filename[0] = argv[optind++];
4571         } else {
4572             const QEMUOption *popt;
4573
4574             optind++;
4575             popt = qemu_options;
4576             for(;;) {
4577                 if (!popt->name) {
4578                     fprintf(stderr, "%s: invalid option -- '%s'\n", 
4579                             argv[0], r);
4580                     exit(1);
4581                 }
4582                 if (!strcmp(popt->name, r + 1))
4583                     break;
4584                 popt++;
4585             }
4586             if (popt->flags & HAS_ARG) {
4587                 if (optind >= argc) {
4588                     fprintf(stderr, "%s: option '%s' requires an argument\n",
4589                             argv[0], r);
4590                     exit(1);
4591                 }
4592                 optarg = argv[optind++];
4593             } else {
4594                 optarg = NULL;
4595             }
4596
4597             switch(popt->index) {
4598             case QEMU_OPTION_M:
4599                 machine = find_machine(optarg);
4600                 if (!machine) {
4601                     QEMUMachine *m;
4602                     printf("Supported machines are:\n");
4603                     for(m = first_machine; m != NULL; m = m->next) {
4604                         printf("%-10s %s%s\n",
4605                                m->name, m->desc, 
4606                                m == first_machine ? " (default)" : "");
4607                     }
4608                     exit(1);
4609                 }
4610                 break;
4611             case QEMU_OPTION_initrd:
4612                 initrd_filename = optarg;
4613                 break;
4614             case QEMU_OPTION_hda:
4615             case QEMU_OPTION_hdb:
4616             case QEMU_OPTION_hdc:
4617             case QEMU_OPTION_hdd:
4618                 {
4619                     int hd_index;
4620                     hd_index = popt->index - QEMU_OPTION_hda;
4621                     hd_filename[hd_index] = optarg;
4622                     if (hd_index == cdrom_index)
4623                         cdrom_index = -1;
4624                 }
4625                 break;
4626             case QEMU_OPTION_snapshot:
4627                 snapshot = 1;
4628                 break;
4629             case QEMU_OPTION_hdachs:
4630                 {
4631                     const char *p;
4632                     p = optarg;
4633                     cyls = strtol(p, (char **)&p, 0);
4634                     if (cyls < 1 || cyls > 16383)
4635                         goto chs_fail;
4636                     if (*p != ',')
4637                         goto chs_fail;
4638                     p++;
4639                     heads = strtol(p, (char **)&p, 0);
4640                     if (heads < 1 || heads > 16)
4641                         goto chs_fail;
4642                     if (*p != ',')
4643                         goto chs_fail;
4644                     p++;
4645                     secs = strtol(p, (char **)&p, 0);
4646                     if (secs < 1 || secs > 63)
4647                         goto chs_fail;
4648                     if (*p == ',') {
4649                         p++;
4650                         if (!strcmp(p, "none"))
4651                             translation = BIOS_ATA_TRANSLATION_NONE;
4652                         else if (!strcmp(p, "lba"))
4653                             translation = BIOS_ATA_TRANSLATION_LBA;
4654                         else if (!strcmp(p, "auto"))
4655                             translation = BIOS_ATA_TRANSLATION_AUTO;
4656                         else
4657                             goto chs_fail;
4658                     } else if (*p != '\0') {
4659                     chs_fail:
4660                         fprintf(stderr, "qemu: invalid physical CHS format\n");
4661                         exit(1);
4662                     }
4663                 }
4664                 break;
4665             case QEMU_OPTION_nographic:
4666                 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
4667                 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
4668                 nographic = 1;
4669                 break;
4670             case QEMU_OPTION_kernel:
4671                 kernel_filename = optarg;
4672                 break;
4673             case QEMU_OPTION_append:
4674                 kernel_cmdline = optarg;
4675                 break;
4676             case QEMU_OPTION_cdrom:
4677                 if (cdrom_index >= 0) {
4678                     hd_filename[cdrom_index] = optarg;
4679                 }
4680                 break;
4681             case QEMU_OPTION_boot:
4682                 boot_device = optarg[0];
4683                 if (boot_device != 'a' && 
4684 #ifdef TARGET_SPARC
4685                     // Network boot
4686                     boot_device != 'n' &&
4687 #endif
4688                     boot_device != 'c' && boot_device != 'd') {
4689                     fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
4690                     exit(1);
4691                 }
4692                 break;
4693             case QEMU_OPTION_fda:
4694                 fd_filename[0] = optarg;
4695                 break;
4696             case QEMU_OPTION_fdb:
4697                 fd_filename[1] = optarg;
4698                 break;
4699             case QEMU_OPTION_no_code_copy:
4700                 code_copy_enabled = 0;
4701                 break;
4702             case QEMU_OPTION_net:
4703                 if (nb_net_clients >= MAX_NET_CLIENTS) {
4704                     fprintf(stderr, "qemu: too many network clients\n");
4705                     exit(1);
4706                 }
4707                 pstrcpy(net_clients[nb_net_clients],
4708                         sizeof(net_clients[0]),
4709                         optarg);
4710                 nb_net_clients++;
4711                 break;
4712 #ifdef CONFIG_SLIRP
4713             case QEMU_OPTION_tftp:
4714                 tftp_prefix = optarg;
4715                 break;
4716 #ifndef _WIN32
4717             case QEMU_OPTION_smb:
4718                 net_slirp_smb(optarg);
4719                 break;
4720 #endif
4721             case QEMU_OPTION_redir:
4722                 net_slirp_redir(optarg);                
4723                 break;
4724 #endif
4725 #ifdef HAS_AUDIO
4726             case QEMU_OPTION_audio_help:
4727                 AUD_help ();
4728                 exit (0);
4729                 break;
4730             case QEMU_OPTION_soundhw:
4731                 select_soundhw (optarg);
4732                 break;
4733 #endif
4734             case QEMU_OPTION_h:
4735                 help();
4736                 break;
4737             case QEMU_OPTION_m:
4738                 ram_size = atoi(optarg) * 1024 * 1024;
4739                 if (ram_size <= 0)
4740                     help();
4741                 if (ram_size > PHYS_RAM_MAX_SIZE) {
4742                     fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
4743                             PHYS_RAM_MAX_SIZE / (1024 * 1024));
4744                     exit(1);
4745                 }
4746                 break;
4747             case QEMU_OPTION_d:
4748                 {
4749                     int mask;
4750                     CPULogItem *item;
4751                     
4752                     mask = cpu_str_to_log_mask(optarg);
4753                     if (!mask) {
4754                         printf("Log items (comma separated):\n");
4755                     for(item = cpu_log_items; item->mask != 0; item++) {
4756                         printf("%-10s %s\n", item->name, item->help);
4757                     }
4758                     exit(1);
4759                     }
4760                     cpu_set_log(mask);
4761                 }
4762                 break;
4763 #ifdef CONFIG_GDBSTUB
4764             case QEMU_OPTION_s:
4765                 use_gdbstub = 1;
4766                 break;
4767             case QEMU_OPTION_p:
4768                 gdbstub_port = atoi(optarg);
4769                 break;
4770 #endif
4771             case QEMU_OPTION_L:
4772                 bios_dir = optarg;
4773                 break;
4774             case QEMU_OPTION_S:
4775                 start_emulation = 0;
4776                 break;
4777             case QEMU_OPTION_k:
4778                 keyboard_layout = optarg;
4779                 break;
4780             case QEMU_OPTION_localtime:
4781                 rtc_utc = 0;
4782                 break;
4783             case QEMU_OPTION_cirrusvga:
4784                 cirrus_vga_enabled = 1;
4785                 break;
4786             case QEMU_OPTION_std_vga:
4787                 cirrus_vga_enabled = 0;
4788                 break;
4789             case QEMU_OPTION_g:
4790                 {
4791                     const char *p;
4792                     int w, h, depth;
4793                     p = optarg;
4794                     w = strtol(p, (char **)&p, 10);
4795                     if (w <= 0) {
4796                     graphic_error:
4797                         fprintf(stderr, "qemu: invalid resolution or depth\n");
4798                         exit(1);
4799                     }
4800                     if (*p != 'x')
4801                         goto graphic_error;
4802                     p++;
4803                     h = strtol(p, (char **)&p, 10);
4804                     if (h <= 0)
4805                         goto graphic_error;
4806                     if (*p == 'x') {
4807                         p++;
4808                         depth = strtol(p, (char **)&p, 10);
4809                         if (depth != 8 && depth != 15 && depth != 16 && 
4810                             depth != 24 && depth != 32)
4811                             goto graphic_error;
4812                     } else if (*p == '\0') {
4813                         depth = graphic_depth;
4814                     } else {
4815                         goto graphic_error;
4816                     }
4817                     
4818                     graphic_width = w;
4819                     graphic_height = h;
4820                     graphic_depth = depth;
4821                 }
4822                 break;
4823             case QEMU_OPTION_monitor:
4824                 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
4825                 break;
4826             case QEMU_OPTION_serial:
4827                 if (serial_device_index >= MAX_SERIAL_PORTS) {
4828                     fprintf(stderr, "qemu: too many serial ports\n");
4829                     exit(1);
4830                 }
4831                 pstrcpy(serial_devices[serial_device_index], 
4832                         sizeof(serial_devices[0]), optarg);
4833                 serial_device_index++;
4834                 break;
4835             case QEMU_OPTION_parallel:
4836                 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4837                     fprintf(stderr, "qemu: too many parallel ports\n");
4838                     exit(1);
4839                 }
4840                 pstrcpy(parallel_devices[parallel_device_index], 
4841                         sizeof(parallel_devices[0]), optarg);
4842                 parallel_device_index++;
4843                 break;
4844             case QEMU_OPTION_loadvm:
4845                 loadvm = optarg;
4846                 break;
4847             case QEMU_OPTION_full_screen:
4848                 full_screen = 1;
4849                 break;
4850             case QEMU_OPTION_pidfile:
4851                 create_pidfile(optarg);
4852                 break;
4853 #ifdef TARGET_I386
4854             case QEMU_OPTION_win2k_hack:
4855                 win2k_install_hack = 1;
4856                 break;
4857 #endif
4858 #ifdef USE_KQEMU
4859             case QEMU_OPTION_no_kqemu:
4860                 kqemu_allowed = 0;
4861                 break;
4862 #endif
4863             case QEMU_OPTION_usb:
4864                 usb_enabled = 1;
4865                 break;
4866             case QEMU_OPTION_usbdevice:
4867                 usb_enabled = 1;
4868                 if (usb_devices_index >= MAX_VM_USB_PORTS) {
4869                     fprintf(stderr, "Too many USB devices\n");
4870                     exit(1);
4871                 }
4872                 pstrcpy(usb_devices[usb_devices_index],
4873                         sizeof(usb_devices[usb_devices_index]),
4874                         optarg);
4875                 usb_devices_index++;
4876                 break;
4877             case QEMU_OPTION_smp:
4878                 smp_cpus = atoi(optarg);
4879                 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
4880                     fprintf(stderr, "Invalid number of CPUs\n");
4881                     exit(1);
4882                 }
4883                 break;
4884             }
4885         }
4886     }
4887
4888 #ifdef USE_KQEMU
4889     if (smp_cpus > 1)
4890         kqemu_allowed = 0;
4891 #endif
4892     linux_boot = (kernel_filename != NULL);
4893         
4894     if (!linux_boot && 
4895         hd_filename[0] == '\0' && 
4896         (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
4897         fd_filename[0] == '\0')
4898         help();
4899     
4900     /* boot to cd by default if no hard disk */
4901     if (hd_filename[0] == '\0' && boot_device == 'c') {
4902         if (fd_filename[0] != '\0')
4903             boot_device = 'a';
4904         else
4905             boot_device = 'd';
4906     }
4907
4908 #if !defined(CONFIG_SOFTMMU)
4909     /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
4910     {
4911         static uint8_t stdout_buf[4096];
4912         setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
4913     }
4914 #else
4915     setvbuf(stdout, NULL, _IOLBF, 0);
4916 #endif
4917     
4918 #ifdef _WIN32
4919     socket_init();
4920 #endif
4921
4922     /* init network clients */
4923     if (nb_net_clients == 0) {
4924         /* if no clients, we use a default config */
4925         pstrcpy(net_clients[0], sizeof(net_clients[0]),
4926                 "nic");
4927         pstrcpy(net_clients[1], sizeof(net_clients[0]),
4928                 "user");
4929         nb_net_clients = 2;
4930     }
4931
4932     for(i = 0;i < nb_net_clients; i++) {
4933         if (net_client_init(net_clients[i]) < 0)
4934             exit(1);
4935     }
4936
4937     /* init the memory */
4938     phys_ram_size = ram_size + vga_ram_size + bios_size;
4939
4940 #ifdef CONFIG_SOFTMMU
4941     phys_ram_base = qemu_vmalloc(phys_ram_size);
4942     if (!phys_ram_base) {
4943         fprintf(stderr, "Could not allocate physical memory\n");
4944         exit(1);
4945     }
4946 #else
4947     /* as we must map the same page at several addresses, we must use
4948        a fd */
4949     {
4950         const char *tmpdir;
4951
4952         tmpdir = getenv("QEMU_TMPDIR");
4953         if (!tmpdir)
4954             tmpdir = "/tmp";
4955         snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
4956         if (mkstemp(phys_ram_file) < 0) {
4957             fprintf(stderr, "Could not create temporary memory file '%s'\n", 
4958                     phys_ram_file);
4959             exit(1);
4960         }
4961         phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
4962         if (phys_ram_fd < 0) {
4963             fprintf(stderr, "Could not open temporary memory file '%s'\n", 
4964                     phys_ram_file);
4965             exit(1);
4966         }
4967         ftruncate(phys_ram_fd, phys_ram_size);
4968         unlink(phys_ram_file);
4969         phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
4970                              phys_ram_size, 
4971                              PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
4972                              phys_ram_fd, 0);
4973         if (phys_ram_base == MAP_FAILED) {
4974             fprintf(stderr, "Could not map physical memory\n");
4975             exit(1);
4976         }
4977     }
4978 #endif
4979
4980     /* we always create the cdrom drive, even if no disk is there */
4981     bdrv_init();
4982     if (cdrom_index >= 0) {
4983         bs_table[cdrom_index] = bdrv_new("cdrom");
4984         bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
4985     }
4986
4987     /* open the virtual block devices */
4988     for(i = 0; i < MAX_DISKS; i++) {
4989         if (hd_filename[i]) {
4990             if (!bs_table[i]) {
4991                 char buf[64];
4992                 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
4993                 bs_table[i] = bdrv_new(buf);
4994             }
4995             if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
4996                 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
4997                         hd_filename[i]);
4998                 exit(1);
4999             }
5000             if (i == 0 && cyls != 0) {
5001                 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5002                 bdrv_set_translation_hint(bs_table[i], translation);
5003             }
5004         }
5005     }
5006
5007     /* we always create at least one floppy disk */
5008     fd_table[0] = bdrv_new("fda");
5009     bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5010
5011     for(i = 0; i < MAX_FD; i++) {
5012         if (fd_filename[i]) {
5013             if (!fd_table[i]) {
5014                 char buf[64];
5015                 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5016                 fd_table[i] = bdrv_new(buf);
5017                 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5018             }
5019             if (fd_filename[i] != '\0') {
5020                 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5021                     fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5022                             fd_filename[i]);
5023                     exit(1);
5024                 }
5025             }
5026         }
5027     }
5028
5029     /* init USB devices */
5030     if (usb_enabled) {
5031         vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5032         for(i = 0; i < usb_devices_index; i++) {
5033             if (usb_device_add(usb_devices[i]) < 0) {
5034                 fprintf(stderr, "Warning: could not add USB device %s\n",
5035                         usb_devices[i]);
5036             }
5037         }
5038     }
5039
5040     register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5041     register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5042
5043     init_ioports();
5044     cpu_calibrate_ticks();
5045
5046     /* terminal init */
5047     if (nographic) {
5048         dumb_display_init(ds);
5049     } else {
5050 #if defined(CONFIG_SDL)
5051         sdl_display_init(ds, full_screen);
5052 #elif defined(CONFIG_COCOA)
5053         cocoa_display_init(ds, full_screen);
5054 #else
5055         dumb_display_init(ds);
5056 #endif
5057     }
5058
5059     vga_console = graphic_console_init(ds);
5060     
5061     monitor_hd = qemu_chr_open(monitor_device);
5062     if (!monitor_hd) {
5063         fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5064         exit(1);
5065     }
5066     monitor_init(monitor_hd, !nographic);
5067
5068     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5069         if (serial_devices[i][0] != '\0') {
5070             serial_hds[i] = qemu_chr_open(serial_devices[i]);
5071             if (!serial_hds[i]) {
5072                 fprintf(stderr, "qemu: could not open serial device '%s'\n", 
5073                         serial_devices[i]);
5074                 exit(1);
5075             }
5076             if (!strcmp(serial_devices[i], "vc"))
5077                 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5078         }
5079     }
5080
5081     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5082         if (parallel_devices[i][0] != '\0') {
5083             parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5084             if (!parallel_hds[i]) {
5085                 fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
5086                         parallel_devices[i]);
5087                 exit(1);
5088             }
5089             if (!strcmp(parallel_devices[i], "vc"))
5090                 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5091         }
5092     }
5093
5094     /* setup cpu signal handlers for MMU / self modifying code handling */
5095 #if !defined(CONFIG_SOFTMMU)
5096     
5097 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5098     {
5099         stack_t stk;
5100         signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5101         stk.ss_sp = signal_stack;
5102         stk.ss_size = SIGNAL_STACK_SIZE;
5103         stk.ss_flags = 0;
5104
5105         if (sigaltstack(&stk, NULL) < 0) {
5106             perror("sigaltstack");
5107             exit(1);
5108         }
5109     }
5110 #endif
5111     {
5112         struct sigaction act;
5113         
5114         sigfillset(&act.sa_mask);
5115         act.sa_flags = SA_SIGINFO;
5116 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5117         act.sa_flags |= SA_ONSTACK;
5118 #endif
5119         act.sa_sigaction = host_segv_handler;
5120         sigaction(SIGSEGV, &act, NULL);
5121         sigaction(SIGBUS, &act, NULL);
5122 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5123         sigaction(SIGFPE, &act, NULL);
5124 #endif
5125     }
5126 #endif
5127
5128 #ifndef _WIN32
5129     {
5130         struct sigaction act;
5131         sigfillset(&act.sa_mask);
5132         act.sa_flags = 0;
5133         act.sa_handler = SIG_IGN;
5134         sigaction(SIGPIPE, &act, NULL);
5135     }
5136 #endif
5137     init_timers();
5138
5139     machine->init(ram_size, vga_ram_size, boot_device,
5140                   ds, fd_filename, snapshot,
5141                   kernel_filename, kernel_cmdline, initrd_filename);
5142
5143     gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5144     qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5145
5146 #ifdef CONFIG_GDBSTUB
5147     if (use_gdbstub) {
5148         if (gdbserver_start(gdbstub_port) < 0) {
5149             fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
5150                     gdbstub_port);
5151             exit(1);
5152         } else {
5153             printf("Waiting gdb connection on port %d\n", gdbstub_port);
5154         }
5155     } else 
5156 #endif
5157     if (loadvm)
5158         qemu_loadvm(loadvm);
5159
5160     {
5161         /* XXX: simplify init */
5162         read_passwords();
5163         if (start_emulation) {
5164             vm_start();
5165         }
5166     }
5167     main_loop();
5168     quit_timers();
5169     return 0;
5170 }