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