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