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