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