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