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