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