port redirection support
[qemu] / vl.c
1 /*
2  * QEMU System Emulator
3  * 
4  * Copyright (c) 2003-2004 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 #ifdef _BSD
42 #include <sys/stat.h>
43 #ifndef __APPLE__
44 #include <libutil.h>
45 #endif
46 #else
47 #include <linux/if.h>
48 #include <linux/if_tun.h>
49 #include <pty.h>
50 #include <malloc.h>
51 #include <linux/rtc.h>
52 #endif
53 #endif
54
55 #if defined(CONFIG_SLIRP)
56 #include "libslirp.h"
57 #endif
58
59 #ifdef _WIN32
60 #include <malloc.h>
61 #include <sys/timeb.h>
62 #include <windows.h>
63 #define getopt_long_only getopt_long
64 #define memalign(align, size) malloc(size)
65 #endif
66
67 #ifdef CONFIG_SDL
68 #ifdef __APPLE__
69 #include <SDL/SDL.h>
70 #endif
71 #endif /* CONFIG_SDL */
72
73 #include "disas.h"
74
75 #include "exec-all.h"
76
77 //#define DO_TB_FLUSH
78
79 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
80
81 //#define DEBUG_UNUSED_IOPORT
82 //#define DEBUG_IOPORT
83
84 #if !defined(CONFIG_SOFTMMU)
85 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
86 #else
87 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
88 #endif
89
90 #ifdef TARGET_PPC
91 #define DEFAULT_RAM_SIZE 144
92 #else
93 #define DEFAULT_RAM_SIZE 128
94 #endif
95 /* in ms */
96 #define GUI_REFRESH_INTERVAL 30
97
98 /* XXX: use a two level table to limit memory usage */
99 #define MAX_IOPORTS 65536
100
101 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
102 char phys_ram_file[1024];
103 CPUState *global_env;
104 CPUState *cpu_single_env;
105 void *ioport_opaque[MAX_IOPORTS];
106 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
107 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
108 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
109 int vga_ram_size;
110 int bios_size;
111 static DisplayState display_state;
112 int nographic;
113 int64_t ticks_per_sec;
114 int boot_device = 'c';
115 int ram_size;
116 static char network_script[1024];
117 int pit_min_timer_count = 0;
118 int nb_nics;
119 NetDriverState nd_table[MAX_NICS];
120 QEMUTimer *gui_timer;
121 int vm_running;
122 int audio_enabled = 0;
123 int pci_enabled = 1;
124 int prep_enabled = 0;
125 int rtc_utc = 1;
126 int cirrus_vga_enabled = 1;
127 int graphic_width = 800;
128 int graphic_height = 600;
129 int graphic_depth = 15;
130 TextConsole *vga_console;
131 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
132
133 /***********************************************************/
134 /* x86 ISA bus support */
135
136 target_phys_addr_t isa_mem_base = 0;
137
138 uint32_t default_ioport_readb(void *opaque, uint32_t address)
139 {
140 #ifdef DEBUG_UNUSED_IOPORT
141     fprintf(stderr, "inb: port=0x%04x\n", address);
142 #endif
143     return 0xff;
144 }
145
146 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
147 {
148 #ifdef DEBUG_UNUSED_IOPORT
149     fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
150 #endif
151 }
152
153 /* default is to make two byte accesses */
154 uint32_t default_ioport_readw(void *opaque, uint32_t address)
155 {
156     uint32_t data;
157     data = ioport_read_table[0][address](ioport_opaque[address], address);
158     address = (address + 1) & (MAX_IOPORTS - 1);
159     data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
160     return data;
161 }
162
163 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
164 {
165     ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
166     address = (address + 1) & (MAX_IOPORTS - 1);
167     ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
168 }
169
170 uint32_t default_ioport_readl(void *opaque, uint32_t address)
171 {
172 #ifdef DEBUG_UNUSED_IOPORT
173     fprintf(stderr, "inl: port=0x%04x\n", address);
174 #endif
175     return 0xffffffff;
176 }
177
178 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
179 {
180 #ifdef DEBUG_UNUSED_IOPORT
181     fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
182 #endif
183 }
184
185 void init_ioports(void)
186 {
187     int i;
188
189     for(i = 0; i < MAX_IOPORTS; i++) {
190         ioport_read_table[0][i] = default_ioport_readb;
191         ioport_write_table[0][i] = default_ioport_writeb;
192         ioport_read_table[1][i] = default_ioport_readw;
193         ioport_write_table[1][i] = default_ioport_writew;
194         ioport_read_table[2][i] = default_ioport_readl;
195         ioport_write_table[2][i] = default_ioport_writel;
196     }
197 }
198
199 /* size is the word size in byte */
200 int register_ioport_read(int start, int length, int size, 
201                          IOPortReadFunc *func, void *opaque)
202 {
203     int i, bsize;
204
205     if (size == 1) {
206         bsize = 0;
207     } else if (size == 2) {
208         bsize = 1;
209     } else if (size == 4) {
210         bsize = 2;
211     } else {
212         hw_error("register_ioport_read: invalid size");
213         return -1;
214     }
215     for(i = start; i < start + length; i += size) {
216         ioport_read_table[bsize][i] = func;
217         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
218             hw_error("register_ioport_read: invalid opaque");
219         ioport_opaque[i] = opaque;
220     }
221     return 0;
222 }
223
224 /* size is the word size in byte */
225 int register_ioport_write(int start, int length, int size, 
226                           IOPortWriteFunc *func, void *opaque)
227 {
228     int i, bsize;
229
230     if (size == 1) {
231         bsize = 0;
232     } else if (size == 2) {
233         bsize = 1;
234     } else if (size == 4) {
235         bsize = 2;
236     } else {
237         hw_error("register_ioport_write: invalid size");
238         return -1;
239     }
240     for(i = start; i < start + length; i += size) {
241         ioport_write_table[bsize][i] = func;
242         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
243             hw_error("register_ioport_read: invalid opaque");
244         ioport_opaque[i] = opaque;
245     }
246     return 0;
247 }
248
249 void isa_unassign_ioport(int start, int length)
250 {
251     int i;
252
253     for(i = start; i < start + length; i++) {
254         ioport_read_table[0][i] = default_ioport_readb;
255         ioport_read_table[1][i] = default_ioport_readw;
256         ioport_read_table[2][i] = default_ioport_readl;
257
258         ioport_write_table[0][i] = default_ioport_writeb;
259         ioport_write_table[1][i] = default_ioport_writew;
260         ioport_write_table[2][i] = default_ioport_writel;
261     }
262 }
263
264 void pstrcpy(char *buf, int buf_size, const char *str)
265 {
266     int c;
267     char *q = buf;
268
269     if (buf_size <= 0)
270         return;
271
272     for(;;) {
273         c = *str++;
274         if (c == 0 || q >= buf + buf_size - 1)
275             break;
276         *q++ = c;
277     }
278     *q = '\0';
279 }
280
281 /* strcat and truncate. */
282 char *pstrcat(char *buf, int buf_size, const char *s)
283 {
284     int len;
285     len = strlen(buf);
286     if (len < buf_size) 
287         pstrcpy(buf + len, buf_size - len, s);
288     return buf;
289 }
290
291 int strstart(const char *str, const char *val, const char **ptr)
292 {
293     const char *p, *q;
294     p = str;
295     q = val;
296     while (*q != '\0') {
297         if (*p != *q)
298             return 0;
299         p++;
300         q++;
301     }
302     if (ptr)
303         *ptr = p;
304     return 1;
305 }
306
307 /* return the size or -1 if error */
308 int get_image_size(const char *filename)
309 {
310     int fd, size;
311     fd = open(filename, O_RDONLY | O_BINARY);
312     if (fd < 0)
313         return -1;
314     size = lseek(fd, 0, SEEK_END);
315     close(fd);
316     return size;
317 }
318
319 /* return the size or -1 if error */
320 int load_image(const char *filename, uint8_t *addr)
321 {
322     int fd, size;
323     fd = open(filename, O_RDONLY | O_BINARY);
324     if (fd < 0)
325         return -1;
326     size = lseek(fd, 0, SEEK_END);
327     lseek(fd, 0, SEEK_SET);
328     if (read(fd, addr, size) != size) {
329         close(fd);
330         return -1;
331     }
332     close(fd);
333     return size;
334 }
335
336 void cpu_outb(CPUState *env, int addr, int val)
337 {
338 #ifdef DEBUG_IOPORT
339     if (loglevel & CPU_LOG_IOPORT)
340         fprintf(logfile, "outb: %04x %02x\n", addr, val);
341 #endif    
342     ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
343 }
344
345 void cpu_outw(CPUState *env, int addr, int val)
346 {
347 #ifdef DEBUG_IOPORT
348     if (loglevel & CPU_LOG_IOPORT)
349         fprintf(logfile, "outw: %04x %04x\n", addr, val);
350 #endif    
351     ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
352 }
353
354 void cpu_outl(CPUState *env, int addr, int val)
355 {
356 #ifdef DEBUG_IOPORT
357     if (loglevel & CPU_LOG_IOPORT)
358         fprintf(logfile, "outl: %04x %08x\n", addr, val);
359 #endif
360     ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
361 }
362
363 int cpu_inb(CPUState *env, int addr)
364 {
365     int val;
366     val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
367 #ifdef DEBUG_IOPORT
368     if (loglevel & CPU_LOG_IOPORT)
369         fprintf(logfile, "inb : %04x %02x\n", addr, val);
370 #endif
371     return val;
372 }
373
374 int cpu_inw(CPUState *env, int addr)
375 {
376     int val;
377     val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
378 #ifdef DEBUG_IOPORT
379     if (loglevel & CPU_LOG_IOPORT)
380         fprintf(logfile, "inw : %04x %04x\n", addr, val);
381 #endif
382     return val;
383 }
384
385 int cpu_inl(CPUState *env, int addr)
386 {
387     int val;
388     val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
389 #ifdef DEBUG_IOPORT
390     if (loglevel & CPU_LOG_IOPORT)
391         fprintf(logfile, "inl : %04x %08x\n", addr, val);
392 #endif
393     return val;
394 }
395
396 /***********************************************************/
397 void hw_error(const char *fmt, ...)
398 {
399     va_list ap;
400
401     va_start(ap, fmt);
402     fprintf(stderr, "qemu: hardware error: ");
403     vfprintf(stderr, fmt, ap);
404     fprintf(stderr, "\n");
405 #ifdef TARGET_I386
406     cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
407 #else
408     cpu_dump_state(global_env, stderr, 0);
409 #endif
410     va_end(ap);
411     abort();
412 }
413
414 /***********************************************************/
415 /* keyboard/mouse */
416
417 static QEMUPutKBDEvent *qemu_put_kbd_event;
418 static void *qemu_put_kbd_event_opaque;
419 static QEMUPutMouseEvent *qemu_put_mouse_event;
420 static void *qemu_put_mouse_event_opaque;
421
422 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
423 {
424     qemu_put_kbd_event_opaque = opaque;
425     qemu_put_kbd_event = func;
426 }
427
428 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
429 {
430     qemu_put_mouse_event_opaque = opaque;
431     qemu_put_mouse_event = func;
432 }
433
434 void kbd_put_keycode(int keycode)
435 {
436     if (qemu_put_kbd_event) {
437         qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
438     }
439 }
440
441 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
442 {
443     if (qemu_put_mouse_event) {
444         qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
445                              dx, dy, dz, buttons_state);
446     }
447 }
448
449 /***********************************************************/
450 /* timers */
451
452 #if defined(__powerpc__)
453
454 static inline uint32_t get_tbl(void) 
455 {
456     uint32_t tbl;
457     asm volatile("mftb %0" : "=r" (tbl));
458     return tbl;
459 }
460
461 static inline uint32_t get_tbu(void) 
462 {
463         uint32_t tbl;
464         asm volatile("mftbu %0" : "=r" (tbl));
465         return tbl;
466 }
467
468 int64_t cpu_get_real_ticks(void)
469 {
470     uint32_t l, h, h1;
471     /* NOTE: we test if wrapping has occurred */
472     do {
473         h = get_tbu();
474         l = get_tbl();
475         h1 = get_tbu();
476     } while (h != h1);
477     return ((int64_t)h << 32) | l;
478 }
479
480 #elif defined(__i386__)
481
482 int64_t cpu_get_real_ticks(void)
483 {
484     int64_t val;
485     asm volatile ("rdtsc" : "=A" (val));
486     return val;
487 }
488
489 #elif defined(__x86_64__)
490
491 int64_t cpu_get_real_ticks(void)
492 {
493     uint32_t low,high;
494     int64_t val;
495     asm volatile("rdtsc" : "=a" (low), "=d" (high));
496     val = high;
497     val <<= 32;
498     val |= low;
499     return val;
500 }
501
502 #else
503 #error unsupported CPU
504 #endif
505
506 static int64_t cpu_ticks_offset;
507 static int cpu_ticks_enabled;
508
509 static inline int64_t cpu_get_ticks(void)
510 {
511     if (!cpu_ticks_enabled) {
512         return cpu_ticks_offset;
513     } else {
514         return cpu_get_real_ticks() + cpu_ticks_offset;
515     }
516 }
517
518 /* enable cpu_get_ticks() */
519 void cpu_enable_ticks(void)
520 {
521     if (!cpu_ticks_enabled) {
522         cpu_ticks_offset -= cpu_get_real_ticks();
523         cpu_ticks_enabled = 1;
524     }
525 }
526
527 /* disable cpu_get_ticks() : the clock is stopped. You must not call
528    cpu_get_ticks() after that.  */
529 void cpu_disable_ticks(void)
530 {
531     if (cpu_ticks_enabled) {
532         cpu_ticks_offset = cpu_get_ticks();
533         cpu_ticks_enabled = 0;
534     }
535 }
536
537 static int64_t get_clock(void)
538 {
539 #ifdef _WIN32
540     struct _timeb tb;
541     _ftime(&tb);
542     return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
543 #else
544     struct timeval tv;
545     gettimeofday(&tv, NULL);
546     return tv.tv_sec * 1000000LL + tv.tv_usec;
547 #endif
548 }
549
550 void cpu_calibrate_ticks(void)
551 {
552     int64_t usec, ticks;
553
554     usec = get_clock();
555     ticks = cpu_get_real_ticks();
556 #ifdef _WIN32
557     Sleep(50);
558 #else
559     usleep(50 * 1000);
560 #endif
561     usec = get_clock() - usec;
562     ticks = cpu_get_real_ticks() - ticks;
563     ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
564 }
565
566 /* compute with 96 bit intermediate result: (a*b)/c */
567 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
568 {
569     union {
570         uint64_t ll;
571         struct {
572 #ifdef WORDS_BIGENDIAN
573             uint32_t high, low;
574 #else
575             uint32_t low, high;
576 #endif            
577         } l;
578     } u, res;
579     uint64_t rl, rh;
580
581     u.ll = a;
582     rl = (uint64_t)u.l.low * (uint64_t)b;
583     rh = (uint64_t)u.l.high * (uint64_t)b;
584     rh += (rl >> 32);
585     res.l.high = rh / c;
586     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
587     return res.ll;
588 }
589
590 #define QEMU_TIMER_REALTIME 0
591 #define QEMU_TIMER_VIRTUAL  1
592
593 struct QEMUClock {
594     int type;
595     /* XXX: add frequency */
596 };
597
598 struct QEMUTimer {
599     QEMUClock *clock;
600     int64_t expire_time;
601     QEMUTimerCB *cb;
602     void *opaque;
603     struct QEMUTimer *next;
604 };
605
606 QEMUClock *rt_clock;
607 QEMUClock *vm_clock;
608
609 static QEMUTimer *active_timers[2];
610 #ifdef _WIN32
611 static MMRESULT timerID;
612 #else
613 /* frequency of the times() clock tick */
614 static int timer_freq;
615 #endif
616
617 QEMUClock *qemu_new_clock(int type)
618 {
619     QEMUClock *clock;
620     clock = qemu_mallocz(sizeof(QEMUClock));
621     if (!clock)
622         return NULL;
623     clock->type = type;
624     return clock;
625 }
626
627 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
628 {
629     QEMUTimer *ts;
630
631     ts = qemu_mallocz(sizeof(QEMUTimer));
632     ts->clock = clock;
633     ts->cb = cb;
634     ts->opaque = opaque;
635     return ts;
636 }
637
638 void qemu_free_timer(QEMUTimer *ts)
639 {
640     qemu_free(ts);
641 }
642
643 /* stop a timer, but do not dealloc it */
644 void qemu_del_timer(QEMUTimer *ts)
645 {
646     QEMUTimer **pt, *t;
647
648     /* NOTE: this code must be signal safe because
649        qemu_timer_expired() can be called from a signal. */
650     pt = &active_timers[ts->clock->type];
651     for(;;) {
652         t = *pt;
653         if (!t)
654             break;
655         if (t == ts) {
656             *pt = t->next;
657             break;
658         }
659         pt = &t->next;
660     }
661 }
662
663 /* modify the current timer so that it will be fired when current_time
664    >= expire_time. The corresponding callback will be called. */
665 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
666 {
667     QEMUTimer **pt, *t;
668
669     qemu_del_timer(ts);
670
671     /* add the timer in the sorted list */
672     /* NOTE: this code must be signal safe because
673        qemu_timer_expired() can be called from a signal. */
674     pt = &active_timers[ts->clock->type];
675     for(;;) {
676         t = *pt;
677         if (!t)
678             break;
679         if (t->expire_time > expire_time) 
680             break;
681         pt = &t->next;
682     }
683     ts->expire_time = expire_time;
684     ts->next = *pt;
685     *pt = ts;
686 }
687
688 int qemu_timer_pending(QEMUTimer *ts)
689 {
690     QEMUTimer *t;
691     for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
692         if (t == ts)
693             return 1;
694     }
695     return 0;
696 }
697
698 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
699 {
700     if (!timer_head)
701         return 0;
702     return (timer_head->expire_time <= current_time);
703 }
704
705 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
706 {
707     QEMUTimer *ts;
708     
709     for(;;) {
710         ts = *ptimer_head;
711         if (ts->expire_time > current_time)
712             break;
713         /* remove timer from the list before calling the callback */
714         *ptimer_head = ts->next;
715         ts->next = NULL;
716         
717         /* run the callback (the timer list can be modified) */
718         ts->cb(ts->opaque);
719     }
720 }
721
722 int64_t qemu_get_clock(QEMUClock *clock)
723 {
724     switch(clock->type) {
725     case QEMU_TIMER_REALTIME:
726 #ifdef _WIN32
727         return GetTickCount();
728 #else
729         {
730             struct tms tp;
731
732             /* Note that using gettimeofday() is not a good solution
733                for timers because its value change when the date is
734                modified. */
735             if (timer_freq == 100) {
736                 return times(&tp) * 10;
737             } else {
738                 return ((int64_t)times(&tp) * 1000) / timer_freq;
739             }
740         }
741 #endif
742     default:
743     case QEMU_TIMER_VIRTUAL:
744         return cpu_get_ticks();
745     }
746 }
747
748 /* save a timer */
749 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
750 {
751     uint64_t expire_time;
752
753     if (qemu_timer_pending(ts)) {
754         expire_time = ts->expire_time;
755     } else {
756         expire_time = -1;
757     }
758     qemu_put_be64(f, expire_time);
759 }
760
761 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
762 {
763     uint64_t expire_time;
764
765     expire_time = qemu_get_be64(f);
766     if (expire_time != -1) {
767         qemu_mod_timer(ts, expire_time);
768     } else {
769         qemu_del_timer(ts);
770     }
771 }
772
773 static void timer_save(QEMUFile *f, void *opaque)
774 {
775     if (cpu_ticks_enabled) {
776         hw_error("cannot save state if virtual timers are running");
777     }
778     qemu_put_be64s(f, &cpu_ticks_offset);
779     qemu_put_be64s(f, &ticks_per_sec);
780 }
781
782 static int timer_load(QEMUFile *f, void *opaque, int version_id)
783 {
784     if (version_id != 1)
785         return -EINVAL;
786     if (cpu_ticks_enabled) {
787         return -EINVAL;
788     }
789     qemu_get_be64s(f, &cpu_ticks_offset);
790     qemu_get_be64s(f, &ticks_per_sec);
791     return 0;
792 }
793
794 #ifdef _WIN32
795 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
796                                  DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
797 #else
798 static void host_alarm_handler(int host_signum)
799 #endif
800 {
801 #if 0
802 #define DISP_FREQ 1000
803     {
804         static int64_t delta_min = INT64_MAX;
805         static int64_t delta_max, delta_cum, last_clock, delta, ti;
806         static int count;
807         ti = qemu_get_clock(vm_clock);
808         if (last_clock != 0) {
809             delta = ti - last_clock;
810             if (delta < delta_min)
811                 delta_min = delta;
812             if (delta > delta_max)
813                 delta_max = delta;
814             delta_cum += delta;
815             if (++count == DISP_FREQ) {
816                 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
817                        muldiv64(delta_min, 1000000, ticks_per_sec),
818                        muldiv64(delta_max, 1000000, ticks_per_sec),
819                        muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
820                        (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
821                 count = 0;
822                 delta_min = INT64_MAX;
823                 delta_max = 0;
824                 delta_cum = 0;
825             }
826         }
827         last_clock = ti;
828     }
829 #endif
830     if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
831                            qemu_get_clock(vm_clock)) ||
832         qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
833                            qemu_get_clock(rt_clock))) {
834         /* stop the cpu because a timer occured */
835         cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
836     }
837 }
838
839 #ifndef _WIN32
840
841 #if defined(__linux__)
842
843 #define RTC_FREQ 1024
844
845 static int rtc_fd;
846
847 static int start_rtc_timer(void)
848 {
849     rtc_fd = open("/dev/rtc", O_RDONLY);
850     if (rtc_fd < 0)
851         return -1;
852     if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
853         fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
854                 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
855                 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
856         goto fail;
857     }
858     if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
859     fail:
860         close(rtc_fd);
861         return -1;
862     }
863     pit_min_timer_count = PIT_FREQ / RTC_FREQ;
864     return 0;
865 }
866
867 #else
868
869 static int start_rtc_timer(void)
870 {
871     return -1;
872 }
873
874 #endif /* !defined(__linux__) */
875
876 #endif /* !defined(_WIN32) */
877
878 static void init_timers(void)
879 {
880     rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
881     vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
882
883 #ifdef _WIN32
884     {
885         int count=0;
886         timerID = timeSetEvent(10,    // interval (ms)
887                                0,     // resolution
888                                host_alarm_handler, // function
889                                (DWORD)&count,  // user parameter
890                                TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
891         if( !timerID ) {
892             perror("failed timer alarm");
893             exit(1);
894         }
895     }
896     pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
897 #else
898     {
899         struct sigaction act;
900         struct itimerval itv;
901         
902         /* get times() syscall frequency */
903         timer_freq = sysconf(_SC_CLK_TCK);
904         
905         /* timer signal */
906         sigfillset(&act.sa_mask);
907         act.sa_flags = 0;
908 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
909         act.sa_flags |= SA_ONSTACK;
910 #endif
911         act.sa_handler = host_alarm_handler;
912         sigaction(SIGALRM, &act, NULL);
913
914         itv.it_interval.tv_sec = 0;
915         itv.it_interval.tv_usec = 1000;
916         itv.it_value.tv_sec = 0;
917         itv.it_value.tv_usec = 10 * 1000;
918         setitimer(ITIMER_REAL, &itv, NULL);
919         /* we probe the tick duration of the kernel to inform the user if
920            the emulated kernel requested a too high timer frequency */
921         getitimer(ITIMER_REAL, &itv);
922
923 #if defined(__linux__)
924         if (itv.it_interval.tv_usec > 1000) {
925             /* try to use /dev/rtc to have a faster timer */
926             if (start_rtc_timer() < 0)
927                 goto use_itimer;
928             /* disable itimer */
929             itv.it_interval.tv_sec = 0;
930             itv.it_interval.tv_usec = 0;
931             itv.it_value.tv_sec = 0;
932             itv.it_value.tv_usec = 0;
933             setitimer(ITIMER_REAL, &itv, NULL);
934
935             /* use the RTC */
936             sigaction(SIGIO, &act, NULL);
937             fcntl(rtc_fd, F_SETFL, O_ASYNC);
938             fcntl(rtc_fd, F_SETOWN, getpid());
939         } else 
940 #endif /* defined(__linux__) */
941         {
942         use_itimer:
943             pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
944                                    PIT_FREQ) / 1000000;
945         }
946     }
947 #endif
948 }
949
950 void quit_timers(void)
951 {
952 #ifdef _WIN32
953     timeKillEvent(timerID);
954 #endif
955 }
956
957 /***********************************************************/
958 /* character device */
959
960 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
961 {
962     return s->chr_write(s, buf, len);
963 }
964
965 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
966 {
967     char buf[4096];
968     va_list ap;
969     va_start(ap, fmt);
970     vsnprintf(buf, sizeof(buf), fmt, ap);
971     qemu_chr_write(s, buf, strlen(buf));
972     va_end(ap);
973 }
974
975 void qemu_chr_send_event(CharDriverState *s, int event)
976 {
977     if (s->chr_send_event)
978         s->chr_send_event(s, event);
979 }
980
981 void qemu_chr_add_read_handler(CharDriverState *s, 
982                                IOCanRWHandler *fd_can_read, 
983                                IOReadHandler *fd_read, void *opaque)
984 {
985     s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
986 }
987              
988 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
989 {
990     s->chr_event = chr_event;
991 }
992
993 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
994 {
995     return len;
996 }
997
998 static void null_chr_add_read_handler(CharDriverState *chr, 
999                                     IOCanRWHandler *fd_can_read, 
1000                                     IOReadHandler *fd_read, void *opaque)
1001 {
1002 }
1003
1004 CharDriverState *qemu_chr_open_null(void)
1005 {
1006     CharDriverState *chr;
1007
1008     chr = qemu_mallocz(sizeof(CharDriverState));
1009     if (!chr)
1010         return NULL;
1011     chr->chr_write = null_chr_write;
1012     chr->chr_add_read_handler = null_chr_add_read_handler;
1013     return chr;
1014 }
1015
1016 #ifndef _WIN32
1017
1018 typedef struct {
1019     int fd_in, fd_out;
1020     /* for nographic stdio only */
1021     IOCanRWHandler *fd_can_read; 
1022     IOReadHandler *fd_read;
1023     void *fd_opaque;
1024 } FDCharDriver;
1025
1026 #define STDIO_MAX_CLIENTS 2
1027
1028 static int stdio_nb_clients;
1029 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1030
1031 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1032 {
1033     FDCharDriver *s = chr->opaque;
1034     return write(s->fd_out, buf, len);
1035 }
1036
1037 static void fd_chr_add_read_handler(CharDriverState *chr, 
1038                                     IOCanRWHandler *fd_can_read, 
1039                                     IOReadHandler *fd_read, void *opaque)
1040 {
1041     FDCharDriver *s = chr->opaque;
1042
1043     if (nographic && s->fd_in == 0) {
1044         s->fd_can_read = fd_can_read;
1045         s->fd_read = fd_read;
1046         s->fd_opaque = opaque;
1047     } else {
1048         qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
1049     }
1050 }
1051
1052 /* open a character device to a unix fd */
1053 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1054 {
1055     CharDriverState *chr;
1056     FDCharDriver *s;
1057
1058     chr = qemu_mallocz(sizeof(CharDriverState));
1059     if (!chr)
1060         return NULL;
1061     s = qemu_mallocz(sizeof(FDCharDriver));
1062     if (!s) {
1063         free(chr);
1064         return NULL;
1065     }
1066     s->fd_in = fd_in;
1067     s->fd_out = fd_out;
1068     chr->opaque = s;
1069     chr->chr_write = fd_chr_write;
1070     chr->chr_add_read_handler = fd_chr_add_read_handler;
1071     return chr;
1072 }
1073
1074 /* for STDIO, we handle the case where several clients use it
1075    (nographic mode) */
1076
1077 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1078
1079 static int term_got_escape, client_index;
1080
1081 void term_print_help(void)
1082 {
1083     printf("\n"
1084            "C-a h    print this help\n"
1085            "C-a x    exit emulator\n"
1086            "C-a s    save disk data back to file (if -snapshot)\n"
1087            "C-a b    send break (magic sysrq)\n"
1088            "C-a c    switch between console and monitor\n"
1089            "C-a C-a  send C-a\n"
1090            );
1091 }
1092
1093 /* called when a char is received */
1094 static void stdio_received_byte(int ch)
1095 {
1096     if (term_got_escape) {
1097         term_got_escape = 0;
1098         switch(ch) {
1099         case 'h':
1100             term_print_help();
1101             break;
1102         case 'x':
1103             exit(0);
1104             break;
1105         case 's': 
1106             {
1107                 int i;
1108                 for (i = 0; i < MAX_DISKS; i++) {
1109                     if (bs_table[i])
1110                         bdrv_commit(bs_table[i]);
1111                 }
1112             }
1113             break;
1114         case 'b':
1115             if (client_index < stdio_nb_clients) {
1116                 CharDriverState *chr;
1117                 FDCharDriver *s;
1118
1119                 chr = stdio_clients[client_index];
1120                 s = chr->opaque;
1121                 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1122             }
1123             break;
1124         case 'c':
1125             client_index++;
1126             if (client_index >= stdio_nb_clients)
1127                 client_index = 0;
1128             if (client_index == 0) {
1129                 /* send a new line in the monitor to get the prompt */
1130                 ch = '\r';
1131                 goto send_char;
1132             }
1133             break;
1134         case TERM_ESCAPE:
1135             goto send_char;
1136         }
1137     } else if (ch == TERM_ESCAPE) {
1138         term_got_escape = 1;
1139     } else {
1140     send_char:
1141         if (client_index < stdio_nb_clients) {
1142             uint8_t buf[1];
1143             CharDriverState *chr;
1144             FDCharDriver *s;
1145             
1146             chr = stdio_clients[client_index];
1147             s = chr->opaque;
1148             buf[0] = ch;
1149             /* XXX: should queue the char if the device is not
1150                ready */
1151             if (s->fd_can_read(s->fd_opaque) > 0) 
1152                 s->fd_read(s->fd_opaque, buf, 1);
1153         }
1154     }
1155 }
1156
1157 static int stdio_can_read(void *opaque)
1158 {
1159     /* XXX: not strictly correct */
1160     return 1;
1161 }
1162
1163 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1164 {
1165     int i;
1166     for(i = 0; i < size; i++)
1167         stdio_received_byte(buf[i]);
1168 }
1169
1170 /* init terminal so that we can grab keys */
1171 static struct termios oldtty;
1172 static int old_fd0_flags;
1173
1174 static void term_exit(void)
1175 {
1176     tcsetattr (0, TCSANOW, &oldtty);
1177     fcntl(0, F_SETFL, old_fd0_flags);
1178 }
1179
1180 static void term_init(void)
1181 {
1182     struct termios tty;
1183
1184     tcgetattr (0, &tty);
1185     oldtty = tty;
1186     old_fd0_flags = fcntl(0, F_GETFL);
1187
1188     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1189                           |INLCR|IGNCR|ICRNL|IXON);
1190     tty.c_oflag |= OPOST;
1191     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1192     /* if graphical mode, we allow Ctrl-C handling */
1193     if (nographic)
1194         tty.c_lflag &= ~ISIG;
1195     tty.c_cflag &= ~(CSIZE|PARENB);
1196     tty.c_cflag |= CS8;
1197     tty.c_cc[VMIN] = 1;
1198     tty.c_cc[VTIME] = 0;
1199     
1200     tcsetattr (0, TCSANOW, &tty);
1201
1202     atexit(term_exit);
1203
1204     fcntl(0, F_SETFL, O_NONBLOCK);
1205 }
1206
1207 CharDriverState *qemu_chr_open_stdio(void)
1208 {
1209     CharDriverState *chr;
1210
1211     if (nographic) {
1212         if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1213             return NULL;
1214         chr = qemu_chr_open_fd(0, 1);
1215         if (stdio_nb_clients == 0)
1216             qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1217         client_index = stdio_nb_clients;
1218     } else {
1219         if (stdio_nb_clients != 0)
1220             return NULL;
1221         chr = qemu_chr_open_fd(0, 1);
1222     }
1223     stdio_clients[stdio_nb_clients++] = chr;
1224     if (stdio_nb_clients == 1) {
1225         /* set the terminal in raw mode */
1226         term_init();
1227     }
1228     return chr;
1229 }
1230
1231 #if defined(__linux__)
1232 CharDriverState *qemu_chr_open_pty(void)
1233 {
1234     char slave_name[1024];
1235     int master_fd, slave_fd;
1236     
1237     /* Not satisfying */
1238     if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1239         return NULL;
1240     }
1241     fprintf(stderr, "char device redirected to %s\n", slave_name);
1242     return qemu_chr_open_fd(master_fd, master_fd);
1243 }
1244 #else
1245 CharDriverState *qemu_chr_open_pty(void)
1246 {
1247     return NULL;
1248 }
1249 #endif
1250
1251 #endif /* !defined(_WIN32) */
1252
1253 CharDriverState *qemu_chr_open(const char *filename)
1254 {
1255     if (!strcmp(filename, "vc")) {
1256         return text_console_init(&display_state);
1257     } else if (!strcmp(filename, "null")) {
1258         return qemu_chr_open_null();
1259     } else 
1260 #ifndef _WIN32
1261     if (!strcmp(filename, "pty")) {
1262         return qemu_chr_open_pty();
1263     } else if (!strcmp(filename, "stdio")) {
1264         return qemu_chr_open_stdio();
1265     } else 
1266 #endif
1267     {
1268         return NULL;
1269     }
1270 }
1271
1272 /***********************************************************/
1273 /* Linux network device redirectors */
1274
1275 void hex_dump(FILE *f, const uint8_t *buf, int size)
1276 {
1277     int len, i, j, c;
1278
1279     for(i=0;i<size;i+=16) {
1280         len = size - i;
1281         if (len > 16)
1282             len = 16;
1283         fprintf(f, "%08x ", i);
1284         for(j=0;j<16;j++) {
1285             if (j < len)
1286                 fprintf(f, " %02x", buf[i+j]);
1287             else
1288                 fprintf(f, "   ");
1289         }
1290         fprintf(f, " ");
1291         for(j=0;j<len;j++) {
1292             c = buf[i+j];
1293             if (c < ' ' || c > '~')
1294                 c = '.';
1295             fprintf(f, "%c", c);
1296         }
1297         fprintf(f, "\n");
1298     }
1299 }
1300
1301 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1302 {
1303     nd->send_packet(nd, buf, size);
1304 }
1305
1306 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read, 
1307                           IOReadHandler *fd_read, void *opaque)
1308 {
1309     nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1310 }
1311
1312 /* dummy network adapter */
1313
1314 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1315 {
1316 }
1317
1318 static void dummy_add_read_packet(NetDriverState *nd, 
1319                                   IOCanRWHandler *fd_can_read, 
1320                                   IOReadHandler *fd_read, void *opaque)
1321 {
1322 }
1323
1324 static int net_dummy_init(NetDriverState *nd)
1325 {
1326     nd->send_packet = dummy_send_packet;
1327     nd->add_read_packet = dummy_add_read_packet;
1328     pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1329     return 0;
1330 }
1331
1332 #if defined(CONFIG_SLIRP)
1333
1334 /* slirp network adapter */
1335
1336 static void *slirp_fd_opaque;
1337 static IOCanRWHandler *slirp_fd_can_read;
1338 static IOReadHandler *slirp_fd_read;
1339 static int slirp_inited;
1340
1341 int slirp_can_output(void)
1342 {
1343     return slirp_fd_can_read(slirp_fd_opaque);
1344 }
1345
1346 void slirp_output(const uint8_t *pkt, int pkt_len)
1347 {
1348 #if 0
1349     printf("output:\n");
1350     hex_dump(stdout, pkt, pkt_len);
1351 #endif
1352     slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1353 }
1354
1355 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1356 {
1357 #if 0
1358     printf("input:\n");
1359     hex_dump(stdout, buf, size);
1360 #endif
1361     slirp_input(buf, size);
1362 }
1363
1364 static void slirp_add_read_packet(NetDriverState *nd, 
1365                                   IOCanRWHandler *fd_can_read, 
1366                                   IOReadHandler *fd_read, void *opaque)
1367 {
1368     slirp_fd_opaque = opaque;
1369     slirp_fd_can_read = fd_can_read;
1370     slirp_fd_read = fd_read;
1371 }
1372
1373 static int net_slirp_init(NetDriverState *nd)
1374 {
1375     if (!slirp_inited) {
1376         slirp_inited = 1;
1377         slirp_init();
1378     }
1379     nd->send_packet = slirp_send_packet;
1380     nd->add_read_packet = slirp_add_read_packet;
1381     pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1382     return 0;
1383 }
1384
1385 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1386 {
1387     const char *p, *p1;
1388     int len;
1389     p = *pp;
1390     p1 = strchr(p, sep);
1391     if (!p1)
1392         return -1;
1393     len = p1 - p;
1394     p1++;
1395     if (buf_size > 0) {
1396         if (len > buf_size - 1)
1397             len = buf_size - 1;
1398         memcpy(buf, p, len);
1399         buf[len] = '\0';
1400     }
1401     *pp = p1;
1402     return 0;
1403 }
1404
1405 static void net_slirp_redir(const char *redir_str)
1406 {
1407     int is_udp;
1408     char buf[256], *r;
1409     const char *p;
1410     struct in_addr guest_addr;
1411     int host_port, guest_port;
1412     
1413     if (!slirp_inited) {
1414         slirp_inited = 1;
1415         slirp_init();
1416     }
1417
1418     p = redir_str;
1419     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1420         goto fail;
1421     if (!strcmp(buf, "tcp")) {
1422         is_udp = 0;
1423     } else if (!strcmp(buf, "udp")) {
1424         is_udp = 1;
1425     } else {
1426         goto fail;
1427     }
1428
1429     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1430         goto fail;
1431     host_port = strtol(buf, &r, 0);
1432     if (r == buf)
1433         goto fail;
1434
1435     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1436         goto fail;
1437     if (buf[0] == '\0') {
1438         pstrcpy(buf, sizeof(buf), "10.0.2.15");
1439     }
1440     if (!inet_aton(buf, &guest_addr))
1441         goto fail;
1442     
1443     guest_port = strtol(p, &r, 0);
1444     if (r == p)
1445         goto fail;
1446     
1447     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1448         fprintf(stderr, "qemu: could not set up redirection\n");
1449         exit(1);
1450     }
1451     return;
1452  fail:
1453     fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1454     exit(1);
1455 }
1456
1457 #endif /* CONFIG_SLIRP */
1458
1459 #if !defined(_WIN32)
1460 #ifdef _BSD
1461 static int tun_open(char *ifname, int ifname_size)
1462 {
1463     int fd;
1464     char *dev;
1465     struct stat s;
1466
1467     fd = open("/dev/tap", O_RDWR);
1468     if (fd < 0) {
1469         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1470         return -1;
1471     }
1472
1473     fstat(fd, &s);
1474     dev = devname(s.st_rdev, S_IFCHR);
1475     pstrcpy(ifname, ifname_size, dev);
1476
1477     fcntl(fd, F_SETFL, O_NONBLOCK);
1478     return fd;
1479 }
1480 #else
1481 static int tun_open(char *ifname, int ifname_size)
1482 {
1483     struct ifreq ifr;
1484     int fd, ret;
1485     
1486     fd = open("/dev/net/tun", O_RDWR);
1487     if (fd < 0) {
1488         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1489         return -1;
1490     }
1491     memset(&ifr, 0, sizeof(ifr));
1492     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1493     pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1494     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1495     if (ret != 0) {
1496         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1497         close(fd);
1498         return -1;
1499     }
1500     printf("Connected to host network interface: %s\n", ifr.ifr_name);
1501     pstrcpy(ifname, ifname_size, ifr.ifr_name);
1502     fcntl(fd, F_SETFL, O_NONBLOCK);
1503     return fd;
1504 }
1505 #endif
1506
1507 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1508 {
1509     write(nd->fd, buf, size);
1510 }
1511
1512 static void tun_add_read_packet(NetDriverState *nd, 
1513                                 IOCanRWHandler *fd_can_read, 
1514                                 IOReadHandler *fd_read, void *opaque)
1515 {
1516     qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1517 }
1518
1519 static int net_tun_init(NetDriverState *nd)
1520 {
1521     int pid, status;
1522     char *args[3];
1523     char **parg;
1524
1525     nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1526     if (nd->fd < 0)
1527         return -1;
1528
1529     /* try to launch network init script */
1530     pid = fork();
1531     if (pid >= 0) {
1532         if (pid == 0) {
1533             parg = args;
1534             *parg++ = network_script;
1535             *parg++ = nd->ifname;
1536             *parg++ = NULL;
1537             execv(network_script, args);
1538             exit(1);
1539         }
1540         while (waitpid(pid, &status, 0) != pid);
1541         if (!WIFEXITED(status) ||
1542             WEXITSTATUS(status) != 0) {
1543             fprintf(stderr, "%s: could not launch network script\n",
1544                     network_script);
1545         }
1546     }
1547     nd->send_packet = tun_send_packet;
1548     nd->add_read_packet = tun_add_read_packet;
1549     return 0;
1550 }
1551
1552 static int net_fd_init(NetDriverState *nd, int fd)
1553 {
1554     nd->fd = fd;
1555     nd->send_packet = tun_send_packet;
1556     nd->add_read_packet = tun_add_read_packet;
1557     pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1558     return 0;
1559 }
1560
1561 #endif /* !_WIN32 */
1562
1563 /***********************************************************/
1564 /* dumb display */
1565
1566 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1567 {
1568 }
1569
1570 static void dumb_resize(DisplayState *ds, int w, int h)
1571 {
1572 }
1573
1574 static void dumb_refresh(DisplayState *ds)
1575 {
1576     vga_update_display();
1577 }
1578
1579 void dumb_display_init(DisplayState *ds)
1580 {
1581     ds->data = NULL;
1582     ds->linesize = 0;
1583     ds->depth = 0;
1584     ds->dpy_update = dumb_update;
1585     ds->dpy_resize = dumb_resize;
1586     ds->dpy_refresh = dumb_refresh;
1587 }
1588
1589 #if !defined(CONFIG_SOFTMMU)
1590 /***********************************************************/
1591 /* cpu signal handler */
1592 static void host_segv_handler(int host_signum, siginfo_t *info, 
1593                               void *puc)
1594 {
1595     if (cpu_signal_handler(host_signum, info, puc))
1596         return;
1597     if (stdio_nb_clients > 0)
1598         term_exit();
1599     abort();
1600 }
1601 #endif
1602
1603 /***********************************************************/
1604 /* I/O handling */
1605
1606 #define MAX_IO_HANDLERS 64
1607
1608 typedef struct IOHandlerRecord {
1609     int fd;
1610     IOCanRWHandler *fd_can_read;
1611     IOReadHandler *fd_read;
1612     void *opaque;
1613     /* temporary data */
1614     struct pollfd *ufd;
1615     int max_size;
1616     struct IOHandlerRecord *next;
1617 } IOHandlerRecord;
1618
1619 static IOHandlerRecord *first_io_handler;
1620
1621 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
1622                              IOReadHandler *fd_read, void *opaque)
1623 {
1624     IOHandlerRecord *ioh;
1625
1626     ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1627     if (!ioh)
1628         return -1;
1629     ioh->fd = fd;
1630     ioh->fd_can_read = fd_can_read;
1631     ioh->fd_read = fd_read;
1632     ioh->opaque = opaque;
1633     ioh->next = first_io_handler;
1634     first_io_handler = ioh;
1635     return 0;
1636 }
1637
1638 void qemu_del_fd_read_handler(int fd)
1639 {
1640     IOHandlerRecord **pioh, *ioh;
1641
1642     pioh = &first_io_handler;
1643     for(;;) {
1644         ioh = *pioh;
1645         if (ioh == NULL)
1646             break;
1647         if (ioh->fd == fd) {
1648             *pioh = ioh->next;
1649             break;
1650         }
1651         pioh = &ioh->next;
1652     }
1653 }
1654
1655 /***********************************************************/
1656 /* savevm/loadvm support */
1657
1658 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1659 {
1660     fwrite(buf, 1, size, f);
1661 }
1662
1663 void qemu_put_byte(QEMUFile *f, int v)
1664 {
1665     fputc(v, f);
1666 }
1667
1668 void qemu_put_be16(QEMUFile *f, unsigned int v)
1669 {
1670     qemu_put_byte(f, v >> 8);
1671     qemu_put_byte(f, v);
1672 }
1673
1674 void qemu_put_be32(QEMUFile *f, unsigned int v)
1675 {
1676     qemu_put_byte(f, v >> 24);
1677     qemu_put_byte(f, v >> 16);
1678     qemu_put_byte(f, v >> 8);
1679     qemu_put_byte(f, v);
1680 }
1681
1682 void qemu_put_be64(QEMUFile *f, uint64_t v)
1683 {
1684     qemu_put_be32(f, v >> 32);
1685     qemu_put_be32(f, v);
1686 }
1687
1688 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1689 {
1690     return fread(buf, 1, size, f);
1691 }
1692
1693 int qemu_get_byte(QEMUFile *f)
1694 {
1695     int v;
1696     v = fgetc(f);
1697     if (v == EOF)
1698         return 0;
1699     else
1700         return v;
1701 }
1702
1703 unsigned int qemu_get_be16(QEMUFile *f)
1704 {
1705     unsigned int v;
1706     v = qemu_get_byte(f) << 8;
1707     v |= qemu_get_byte(f);
1708     return v;
1709 }
1710
1711 unsigned int qemu_get_be32(QEMUFile *f)
1712 {
1713     unsigned int v;
1714     v = qemu_get_byte(f) << 24;
1715     v |= qemu_get_byte(f) << 16;
1716     v |= qemu_get_byte(f) << 8;
1717     v |= qemu_get_byte(f);
1718     return v;
1719 }
1720
1721 uint64_t qemu_get_be64(QEMUFile *f)
1722 {
1723     uint64_t v;
1724     v = (uint64_t)qemu_get_be32(f) << 32;
1725     v |= qemu_get_be32(f);
1726     return v;
1727 }
1728
1729 int64_t qemu_ftell(QEMUFile *f)
1730 {
1731     return ftell(f);
1732 }
1733
1734 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1735 {
1736     if (fseek(f, pos, whence) < 0)
1737         return -1;
1738     return ftell(f);
1739 }
1740
1741 typedef struct SaveStateEntry {
1742     char idstr[256];
1743     int instance_id;
1744     int version_id;
1745     SaveStateHandler *save_state;
1746     LoadStateHandler *load_state;
1747     void *opaque;
1748     struct SaveStateEntry *next;
1749 } SaveStateEntry;
1750
1751 static SaveStateEntry *first_se;
1752
1753 int register_savevm(const char *idstr, 
1754                     int instance_id, 
1755                     int version_id,
1756                     SaveStateHandler *save_state,
1757                     LoadStateHandler *load_state,
1758                     void *opaque)
1759 {
1760     SaveStateEntry *se, **pse;
1761
1762     se = qemu_malloc(sizeof(SaveStateEntry));
1763     if (!se)
1764         return -1;
1765     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1766     se->instance_id = instance_id;
1767     se->version_id = version_id;
1768     se->save_state = save_state;
1769     se->load_state = load_state;
1770     se->opaque = opaque;
1771     se->next = NULL;
1772
1773     /* add at the end of list */
1774     pse = &first_se;
1775     while (*pse != NULL)
1776         pse = &(*pse)->next;
1777     *pse = se;
1778     return 0;
1779 }
1780
1781 #define QEMU_VM_FILE_MAGIC   0x5145564d
1782 #define QEMU_VM_FILE_VERSION 0x00000001
1783
1784 int qemu_savevm(const char *filename)
1785 {
1786     SaveStateEntry *se;
1787     QEMUFile *f;
1788     int len, len_pos, cur_pos, saved_vm_running, ret;
1789
1790     saved_vm_running = vm_running;
1791     vm_stop(0);
1792
1793     f = fopen(filename, "wb");
1794     if (!f) {
1795         ret = -1;
1796         goto the_end;
1797     }
1798
1799     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1800     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1801
1802     for(se = first_se; se != NULL; se = se->next) {
1803         /* ID string */
1804         len = strlen(se->idstr);
1805         qemu_put_byte(f, len);
1806         qemu_put_buffer(f, se->idstr, len);
1807
1808         qemu_put_be32(f, se->instance_id);
1809         qemu_put_be32(f, se->version_id);
1810
1811         /* record size: filled later */
1812         len_pos = ftell(f);
1813         qemu_put_be32(f, 0);
1814         
1815         se->save_state(f, se->opaque);
1816
1817         /* fill record size */
1818         cur_pos = ftell(f);
1819         len = ftell(f) - len_pos - 4;
1820         fseek(f, len_pos, SEEK_SET);
1821         qemu_put_be32(f, len);
1822         fseek(f, cur_pos, SEEK_SET);
1823     }
1824
1825     fclose(f);
1826     ret = 0;
1827  the_end:
1828     if (saved_vm_running)
1829         vm_start();
1830     return ret;
1831 }
1832
1833 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1834 {
1835     SaveStateEntry *se;
1836
1837     for(se = first_se; se != NULL; se = se->next) {
1838         if (!strcmp(se->idstr, idstr) && 
1839             instance_id == se->instance_id)
1840             return se;
1841     }
1842     return NULL;
1843 }
1844
1845 int qemu_loadvm(const char *filename)
1846 {
1847     SaveStateEntry *se;
1848     QEMUFile *f;
1849     int len, cur_pos, ret, instance_id, record_len, version_id;
1850     int saved_vm_running;
1851     unsigned int v;
1852     char idstr[256];
1853     
1854     saved_vm_running = vm_running;
1855     vm_stop(0);
1856
1857     f = fopen(filename, "rb");
1858     if (!f) {
1859         ret = -1;
1860         goto the_end;
1861     }
1862
1863     v = qemu_get_be32(f);
1864     if (v != QEMU_VM_FILE_MAGIC)
1865         goto fail;
1866     v = qemu_get_be32(f);
1867     if (v != QEMU_VM_FILE_VERSION) {
1868     fail:
1869         fclose(f);
1870         ret = -1;
1871         goto the_end;
1872     }
1873     for(;;) {
1874 #if defined (DO_TB_FLUSH)
1875         tb_flush(global_env);
1876 #endif
1877         len = qemu_get_byte(f);
1878         if (feof(f))
1879             break;
1880         qemu_get_buffer(f, idstr, len);
1881         idstr[len] = '\0';
1882         instance_id = qemu_get_be32(f);
1883         version_id = qemu_get_be32(f);
1884         record_len = qemu_get_be32(f);
1885 #if 0
1886         printf("idstr=%s instance=0x%x version=%d len=%d\n", 
1887                idstr, instance_id, version_id, record_len);
1888 #endif
1889         cur_pos = ftell(f);
1890         se = find_se(idstr, instance_id);
1891         if (!se) {
1892             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
1893                     instance_id, idstr);
1894         } else {
1895             ret = se->load_state(f, se->opaque, version_id);
1896             if (ret < 0) {
1897                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
1898                         instance_id, idstr);
1899             }
1900         }
1901         /* always seek to exact end of record */
1902         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1903     }
1904     fclose(f);
1905     ret = 0;
1906  the_end:
1907     if (saved_vm_running)
1908         vm_start();
1909     return ret;
1910 }
1911
1912 /***********************************************************/
1913 /* cpu save/restore */
1914
1915 #if defined(TARGET_I386)
1916
1917 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
1918 {
1919     qemu_put_be32(f, dt->selector);
1920     qemu_put_be32(f, (uint32_t)dt->base);
1921     qemu_put_be32(f, dt->limit);
1922     qemu_put_be32(f, dt->flags);
1923 }
1924
1925 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
1926 {
1927     dt->selector = qemu_get_be32(f);
1928     dt->base = (uint8_t *)qemu_get_be32(f);
1929     dt->limit = qemu_get_be32(f);
1930     dt->flags = qemu_get_be32(f);
1931 }
1932
1933 void cpu_save(QEMUFile *f, void *opaque)
1934 {
1935     CPUState *env = opaque;
1936     uint16_t fptag, fpus, fpuc;
1937     uint32_t hflags;
1938     int i;
1939
1940     for(i = 0; i < 8; i++)
1941         qemu_put_be32s(f, &env->regs[i]);
1942     qemu_put_be32s(f, &env->eip);
1943     qemu_put_be32s(f, &env->eflags);
1944     qemu_put_be32s(f, &env->eflags);
1945     hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
1946     qemu_put_be32s(f, &hflags);
1947     
1948     /* FPU */
1949     fpuc = env->fpuc;
1950     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
1951     fptag = 0;
1952     for (i=7; i>=0; i--) {
1953         fptag <<= 2;
1954         if (env->fptags[i]) {
1955             fptag |= 3;
1956         }
1957     }
1958     
1959     qemu_put_be16s(f, &fpuc);
1960     qemu_put_be16s(f, &fpus);
1961     qemu_put_be16s(f, &fptag);
1962
1963     for(i = 0; i < 8; i++) {
1964         uint64_t mant;
1965         uint16_t exp;
1966         cpu_get_fp80(&mant, &exp, env->fpregs[i]);
1967         qemu_put_be64(f, mant);
1968         qemu_put_be16(f, exp);
1969     }
1970
1971     for(i = 0; i < 6; i++)
1972         cpu_put_seg(f, &env->segs[i]);
1973     cpu_put_seg(f, &env->ldt);
1974     cpu_put_seg(f, &env->tr);
1975     cpu_put_seg(f, &env->gdt);
1976     cpu_put_seg(f, &env->idt);
1977     
1978     qemu_put_be32s(f, &env->sysenter_cs);
1979     qemu_put_be32s(f, &env->sysenter_esp);
1980     qemu_put_be32s(f, &env->sysenter_eip);
1981     
1982     qemu_put_be32s(f, &env->cr[0]);
1983     qemu_put_be32s(f, &env->cr[2]);
1984     qemu_put_be32s(f, &env->cr[3]);
1985     qemu_put_be32s(f, &env->cr[4]);
1986     
1987     for(i = 0; i < 8; i++)
1988         qemu_put_be32s(f, &env->dr[i]);
1989
1990     /* MMU */
1991     qemu_put_be32s(f, &env->a20_mask);
1992 }
1993
1994 int cpu_load(QEMUFile *f, void *opaque, int version_id)
1995 {
1996     CPUState *env = opaque;
1997     int i;
1998     uint32_t hflags;
1999     uint16_t fpus, fpuc, fptag;
2000
2001     if (version_id != 2)
2002         return -EINVAL;
2003     for(i = 0; i < 8; i++)
2004         qemu_get_be32s(f, &env->regs[i]);
2005     qemu_get_be32s(f, &env->eip);
2006     qemu_get_be32s(f, &env->eflags);
2007     qemu_get_be32s(f, &env->eflags);
2008     qemu_get_be32s(f, &hflags);
2009
2010     qemu_get_be16s(f, &fpuc);
2011     qemu_get_be16s(f, &fpus);
2012     qemu_get_be16s(f, &fptag);
2013
2014     for(i = 0; i < 8; i++) {
2015         uint64_t mant;
2016         uint16_t exp;
2017         mant = qemu_get_be64(f);
2018         exp = qemu_get_be16(f);
2019         env->fpregs[i] = cpu_set_fp80(mant, exp);
2020     }
2021
2022     env->fpuc = fpuc;
2023     env->fpstt = (fpus >> 11) & 7;
2024     env->fpus = fpus & ~0x3800;
2025     for(i = 0; i < 8; i++) {
2026         env->fptags[i] = ((fptag & 3) == 3);
2027         fptag >>= 2;
2028     }
2029     
2030     for(i = 0; i < 6; i++)
2031         cpu_get_seg(f, &env->segs[i]);
2032     cpu_get_seg(f, &env->ldt);
2033     cpu_get_seg(f, &env->tr);
2034     cpu_get_seg(f, &env->gdt);
2035     cpu_get_seg(f, &env->idt);
2036     
2037     qemu_get_be32s(f, &env->sysenter_cs);
2038     qemu_get_be32s(f, &env->sysenter_esp);
2039     qemu_get_be32s(f, &env->sysenter_eip);
2040     
2041     qemu_get_be32s(f, &env->cr[0]);
2042     qemu_get_be32s(f, &env->cr[2]);
2043     qemu_get_be32s(f, &env->cr[3]);
2044     qemu_get_be32s(f, &env->cr[4]);
2045     
2046     for(i = 0; i < 8; i++)
2047         qemu_get_be32s(f, &env->dr[i]);
2048
2049     /* MMU */
2050     qemu_get_be32s(f, &env->a20_mask);
2051
2052     /* XXX: compute hflags from scratch, except for CPL and IIF */
2053     env->hflags = hflags;
2054     tlb_flush(env, 1);
2055     return 0;
2056 }
2057
2058 #elif defined(TARGET_PPC)
2059 void cpu_save(QEMUFile *f, void *opaque)
2060 {
2061 }
2062
2063 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2064 {
2065     return 0;
2066 }
2067 #else
2068
2069 #warning No CPU save/restore functions
2070
2071 #endif
2072
2073 /***********************************************************/
2074 /* ram save/restore */
2075
2076 /* we just avoid storing empty pages */
2077 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
2078 {
2079     int i, v;
2080
2081     v = buf[0];
2082     for(i = 1; i < len; i++) {
2083         if (buf[i] != v)
2084             goto normal_save;
2085     }
2086     qemu_put_byte(f, 1);
2087     qemu_put_byte(f, v);
2088     return;
2089  normal_save:
2090     qemu_put_byte(f, 0); 
2091     qemu_put_buffer(f, buf, len);
2092 }
2093
2094 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2095 {
2096     int v;
2097
2098     v = qemu_get_byte(f);
2099     switch(v) {
2100     case 0:
2101         if (qemu_get_buffer(f, buf, len) != len)
2102             return -EIO;
2103         break;
2104     case 1:
2105         v = qemu_get_byte(f);
2106         memset(buf, v, len);
2107         break;
2108     default:
2109         return -EINVAL;
2110     }
2111     return 0;
2112 }
2113
2114 static void ram_save(QEMUFile *f, void *opaque)
2115 {
2116     int i;
2117     qemu_put_be32(f, phys_ram_size);
2118     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2119         ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2120     }
2121 }
2122
2123 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2124 {
2125     int i, ret;
2126
2127     if (version_id != 1)
2128         return -EINVAL;
2129     if (qemu_get_be32(f) != phys_ram_size)
2130         return -EINVAL;
2131     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2132         ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2133         if (ret)
2134             return ret;
2135     }
2136     return 0;
2137 }
2138
2139 /***********************************************************/
2140 /* main execution loop */
2141
2142 void gui_update(void *opaque)
2143 {
2144     display_state.dpy_refresh(&display_state);
2145     qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2146 }
2147
2148 /* XXX: support several handlers */
2149 VMStopHandler *vm_stop_cb;
2150 VMStopHandler *vm_stop_opaque;
2151
2152 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2153 {
2154     vm_stop_cb = cb;
2155     vm_stop_opaque = opaque;
2156     return 0;
2157 }
2158
2159 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2160 {
2161     vm_stop_cb = NULL;
2162 }
2163
2164 void vm_start(void)
2165 {
2166     if (!vm_running) {
2167         cpu_enable_ticks();
2168         vm_running = 1;
2169     }
2170 }
2171
2172 void vm_stop(int reason) 
2173 {
2174     if (vm_running) {
2175         cpu_disable_ticks();
2176         vm_running = 0;
2177         if (reason != 0) {
2178             if (vm_stop_cb) {
2179                 vm_stop_cb(vm_stop_opaque, reason);
2180             }
2181         }
2182     }
2183 }
2184
2185 /* reset/shutdown handler */
2186
2187 typedef struct QEMUResetEntry {
2188     QEMUResetHandler *func;
2189     void *opaque;
2190     struct QEMUResetEntry *next;
2191 } QEMUResetEntry;
2192
2193 static QEMUResetEntry *first_reset_entry;
2194 static int reset_requested;
2195 static int shutdown_requested;
2196
2197 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2198 {
2199     QEMUResetEntry **pre, *re;
2200
2201     pre = &first_reset_entry;
2202     while (*pre != NULL)
2203         pre = &(*pre)->next;
2204     re = qemu_mallocz(sizeof(QEMUResetEntry));
2205     re->func = func;
2206     re->opaque = opaque;
2207     re->next = NULL;
2208     *pre = re;
2209 }
2210
2211 void qemu_system_reset(void)
2212 {
2213     QEMUResetEntry *re;
2214
2215     /* reset all devices */
2216     for(re = first_reset_entry; re != NULL; re = re->next) {
2217         re->func(re->opaque);
2218     }
2219 }
2220
2221 void qemu_system_reset_request(void)
2222 {
2223     reset_requested = 1;
2224     cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2225 }
2226
2227 void qemu_system_shutdown_request(void)
2228 {
2229     shutdown_requested = 1;
2230     cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2231 }
2232
2233 static void main_cpu_reset(void *opaque)
2234 {
2235 #ifdef TARGET_I386
2236     CPUState *env = opaque;
2237     cpu_reset(env);
2238 #endif
2239 }
2240
2241 void main_loop_wait(int timeout)
2242 {
2243 #ifndef _WIN32
2244     struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2245     IOHandlerRecord *ioh, *ioh_next;
2246     uint8_t buf[4096];
2247     int n, max_size;
2248 #endif
2249     int ret;
2250
2251 #ifdef _WIN32
2252         if (timeout > 0)
2253             Sleep(timeout);
2254 #else
2255         /* poll any events */
2256         /* XXX: separate device handlers from system ones */
2257         pf = ufds;
2258         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2259             if (!ioh->fd_can_read) {
2260                 max_size = 0;
2261                 pf->fd = ioh->fd;
2262                 pf->events = POLLIN;
2263                 ioh->ufd = pf;
2264                 pf++;
2265             } else {
2266                 max_size = ioh->fd_can_read(ioh->opaque);
2267                 if (max_size > 0) {
2268                     if (max_size > sizeof(buf))
2269                         max_size = sizeof(buf);
2270                     pf->fd = ioh->fd;
2271                     pf->events = POLLIN;
2272                     ioh->ufd = pf;
2273                     pf++;
2274                 } else {
2275                     ioh->ufd = NULL;
2276                 }
2277             }
2278             ioh->max_size = max_size;
2279         }
2280         
2281         ret = poll(ufds, pf - ufds, timeout);
2282         if (ret > 0) {
2283             /* XXX: better handling of removal */
2284             for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2285                 ioh_next = ioh->next;
2286                 pf = ioh->ufd;
2287                 if (pf) {
2288                     if (pf->revents & POLLIN) {
2289                         if (ioh->max_size == 0) {
2290                             /* just a read event */
2291                             ioh->fd_read(ioh->opaque, NULL, 0);
2292                         } else {
2293                             n = read(ioh->fd, buf, ioh->max_size);
2294                             if (n >= 0) {
2295                                 ioh->fd_read(ioh->opaque, buf, n);
2296                             } else if (errno != EAGAIN) {
2297                                 ioh->fd_read(ioh->opaque, NULL, -errno);
2298                             }
2299                         }
2300                     }
2301                 }
2302             }
2303         }
2304 #endif /* !defined(_WIN32) */
2305 #if defined(CONFIG_SLIRP)
2306         /* XXX: merge with poll() */
2307         if (slirp_inited) {
2308             fd_set rfds, wfds, xfds;
2309             int nfds;
2310             struct timeval tv;
2311
2312             nfds = -1;
2313             FD_ZERO(&rfds);
2314             FD_ZERO(&wfds);
2315             FD_ZERO(&xfds);
2316             slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2317             tv.tv_sec = 0;
2318             tv.tv_usec = 0;
2319             ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2320             if (ret >= 0) {
2321                 slirp_select_poll(&rfds, &wfds, &xfds);
2322             }
2323         }
2324 #endif
2325
2326         if (vm_running) {
2327             qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
2328                             qemu_get_clock(vm_clock));
2329             
2330             if (audio_enabled) {
2331                 /* XXX: add explicit timer */
2332                 SB16_run();
2333             }
2334             
2335             /* run dma transfers, if any */
2336             DMA_run();
2337         }
2338
2339         /* real time timers */
2340         qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
2341                         qemu_get_clock(rt_clock));
2342 }
2343
2344 int main_loop(void)
2345 {
2346     int ret, timeout;
2347     CPUState *env = global_env;
2348
2349     for(;;) {
2350         if (vm_running) {
2351             ret = cpu_exec(env);
2352             if (shutdown_requested) {
2353                 ret = EXCP_INTERRUPT; 
2354                 break;
2355             }
2356             if (reset_requested) {
2357                 reset_requested = 0;
2358                 qemu_system_reset();
2359                 ret = EXCP_INTERRUPT; 
2360             }
2361             if (ret == EXCP_DEBUG) {
2362                 vm_stop(EXCP_DEBUG);
2363             }
2364             /* if hlt instruction, we wait until the next IRQ */
2365             /* XXX: use timeout computed from timers */
2366             if (ret == EXCP_HLT) 
2367                 timeout = 10;
2368             else
2369                 timeout = 0;
2370         } else {
2371             timeout = 10;
2372         }
2373         main_loop_wait(timeout);
2374     }
2375     cpu_disable_ticks();
2376     return ret;
2377 }
2378
2379 void help(void)
2380 {
2381     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2382            "usage: %s [options] [disk_image]\n"
2383            "\n"
2384            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2385            "\n"
2386            "Standard options:\n"
2387            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
2388            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
2389            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
2390            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2391            "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
2392            "-snapshot       write to temporary files instead of disk image files\n"
2393            "-m megs         set virtual RAM size to megs MB [default=%d]\n"
2394            "-nographic      disable graphical output and redirect serial I/Os to console\n"
2395            "-enable-audio   enable audio support\n"
2396            "-localtime      set the real time clock to local time [default=utc]\n"
2397 #ifdef TARGET_PPC
2398            "-prep           Simulate a PREP system (default is PowerMAC)\n"
2399            "-g WxH[xDEPTH]  Set the initial VGA graphic mode\n"
2400 #endif
2401            "\n"
2402            "Network options:\n"
2403            "-nics n         simulate 'n' network cards [default=1]\n"
2404            "-macaddr addr   set the mac address of the first interface\n"
2405            "-n script       set tap/tun network init script [default=%s]\n"
2406            "-tun-fd fd      use this fd as already opened tap/tun interface\n"
2407 #ifdef CONFIG_SLIRP
2408            "-user-net       use user mode network stack [default if no tap/tun script]\n"
2409            "-tftp prefix    allow tftp access to files starting with prefix [-user-net]\n"
2410            "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2411            "                redirect TCP or UDP connections from host to guest [-user-net]\n"
2412 #endif
2413            "-dummy-net      use dummy network stack\n"
2414            "\n"
2415            "Linux boot specific:\n"
2416            "-kernel bzImage use 'bzImage' as kernel image\n"
2417            "-append cmdline use 'cmdline' as kernel command line\n"
2418            "-initrd file    use 'file' as initial ram disk\n"
2419            "\n"
2420            "Debug/Expert options:\n"
2421            "-monitor dev    redirect the monitor to char device 'dev'\n"
2422            "-serial dev     redirect the serial port to char device 'dev'\n"
2423            "-S              freeze CPU at startup (use 'c' to start execution)\n"
2424            "-s              wait gdb connection to port %d\n"
2425            "-p port         change gdb connection port\n"
2426            "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
2427            "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
2428            "-L path         set the directory for the BIOS and VGA BIOS\n"
2429 #ifdef USE_CODE_COPY
2430            "-no-code-copy   disable code copy acceleration\n"
2431 #endif
2432 #ifdef TARGET_I386
2433            "-isa            simulate an ISA-only system (default is PCI system)\n"
2434            "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
2435            "                (default is CL-GD5446 PCI VGA)\n"
2436 #endif
2437            "\n"
2438            "During emulation, the following keys are useful:\n"
2439            "ctrl-shift-f    toggle full screen\n"
2440            "ctrl-shift-Fn   switch to virtual console 'n'\n"
2441            "ctrl-shift      toggle mouse and keyboard grab\n"
2442            "\n"
2443            "When using -nographic, press 'ctrl-a h' to get some help.\n"
2444            ,
2445 #ifdef CONFIG_SOFTMMU
2446            "qemu",
2447 #else
2448            "qemu-fast",
2449 #endif
2450            DEFAULT_RAM_SIZE,
2451            DEFAULT_NETWORK_SCRIPT,
2452            DEFAULT_GDBSTUB_PORT,
2453            "/tmp/qemu.log");
2454 #ifndef CONFIG_SOFTMMU
2455     printf("\n"
2456            "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2457            "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2458            "PC emulation.\n");
2459 #endif
2460     exit(1);
2461 }
2462
2463 #define HAS_ARG 0x0001
2464
2465 enum {
2466     QEMU_OPTION_h,
2467
2468     QEMU_OPTION_fda,
2469     QEMU_OPTION_fdb,
2470     QEMU_OPTION_hda,
2471     QEMU_OPTION_hdb,
2472     QEMU_OPTION_hdc,
2473     QEMU_OPTION_hdd,
2474     QEMU_OPTION_cdrom,
2475     QEMU_OPTION_boot,
2476     QEMU_OPTION_snapshot,
2477     QEMU_OPTION_m,
2478     QEMU_OPTION_nographic,
2479     QEMU_OPTION_enable_audio,
2480
2481     QEMU_OPTION_nics,
2482     QEMU_OPTION_macaddr,
2483     QEMU_OPTION_n,
2484     QEMU_OPTION_tun_fd,
2485     QEMU_OPTION_user_net,
2486     QEMU_OPTION_tftp,
2487     QEMU_OPTION_redir,
2488     QEMU_OPTION_dummy_net,
2489
2490     QEMU_OPTION_kernel,
2491     QEMU_OPTION_append,
2492     QEMU_OPTION_initrd,
2493
2494     QEMU_OPTION_S,
2495     QEMU_OPTION_s,
2496     QEMU_OPTION_p,
2497     QEMU_OPTION_d,
2498     QEMU_OPTION_hdachs,
2499     QEMU_OPTION_L,
2500     QEMU_OPTION_no_code_copy,
2501     QEMU_OPTION_pci,
2502     QEMU_OPTION_isa,
2503     QEMU_OPTION_prep,
2504     QEMU_OPTION_localtime,
2505     QEMU_OPTION_cirrusvga,
2506     QEMU_OPTION_g,
2507     QEMU_OPTION_std_vga,
2508     QEMU_OPTION_monitor,
2509     QEMU_OPTION_serial,
2510 };
2511
2512 typedef struct QEMUOption {
2513     const char *name;
2514     int flags;
2515     int index;
2516 } QEMUOption;
2517
2518 const QEMUOption qemu_options[] = {
2519     { "h", 0, QEMU_OPTION_h },
2520
2521     { "fda", HAS_ARG, QEMU_OPTION_fda },
2522     { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2523     { "hda", HAS_ARG, QEMU_OPTION_hda },
2524     { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2525     { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2526     { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2527     { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2528     { "boot", HAS_ARG, QEMU_OPTION_boot },
2529     { "snapshot", 0, QEMU_OPTION_snapshot },
2530     { "m", HAS_ARG, QEMU_OPTION_m },
2531     { "nographic", 0, QEMU_OPTION_nographic },
2532     { "enable-audio", 0, QEMU_OPTION_enable_audio },
2533
2534     { "nics", HAS_ARG, QEMU_OPTION_nics},
2535     { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2536     { "n", HAS_ARG, QEMU_OPTION_n },
2537     { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2538 #ifdef CONFIG_SLIRP
2539     { "user-net", 0, QEMU_OPTION_user_net },
2540     { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2541     { "redir", HAS_ARG, QEMU_OPTION_redir },
2542 #endif
2543     { "dummy-net", 0, QEMU_OPTION_dummy_net },
2544
2545     { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2546     { "append", HAS_ARG, QEMU_OPTION_append },
2547     { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2548
2549     { "S", 0, QEMU_OPTION_S },
2550     { "s", 0, QEMU_OPTION_s },
2551     { "p", HAS_ARG, QEMU_OPTION_p },
2552     { "d", HAS_ARG, QEMU_OPTION_d },
2553     { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2554     { "L", HAS_ARG, QEMU_OPTION_L },
2555     { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2556 #ifdef TARGET_PPC
2557     { "prep", 0, QEMU_OPTION_prep },
2558     { "g", 1, QEMU_OPTION_g },
2559 #endif
2560     { "localtime", 0, QEMU_OPTION_localtime },
2561     { "isa", 0, QEMU_OPTION_isa },
2562     { "std-vga", 0, QEMU_OPTION_std_vga },
2563     { "monitor", 1, QEMU_OPTION_monitor },
2564     { "serial", 1, QEMU_OPTION_serial },
2565     
2566     /* temporary options */
2567     { "pci", 0, QEMU_OPTION_pci },
2568     { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2569     { NULL },
2570 };
2571
2572 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2573
2574 /* this stack is only used during signal handling */
2575 #define SIGNAL_STACK_SIZE 32768
2576
2577 static uint8_t *signal_stack;
2578
2579 #endif
2580
2581 /* password input */
2582
2583 static BlockDriverState *get_bdrv(int index)
2584 {
2585     BlockDriverState *bs;
2586
2587     if (index < 4) {
2588         bs = bs_table[index];
2589     } else if (index < 6) {
2590         bs = fd_table[index - 4];
2591     } else {
2592         bs = NULL;
2593     }
2594     return bs;
2595 }
2596
2597 static void read_passwords(void)
2598 {
2599     BlockDriverState *bs;
2600     int i, j;
2601     char password[256];
2602
2603     for(i = 0; i < 6; i++) {
2604         bs = get_bdrv(i);
2605         if (bs && bdrv_is_encrypted(bs)) {
2606             term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
2607             for(j = 0; j < 3; j++) {
2608                 monitor_readline("Password: ", 
2609                                  1, password, sizeof(password));
2610                 if (bdrv_set_key(bs, password) == 0)
2611                     break;
2612                 term_printf("invalid password\n");
2613             }
2614         }
2615     }
2616 }
2617
2618 #define NET_IF_TUN   0
2619 #define NET_IF_USER  1
2620 #define NET_IF_DUMMY 2
2621
2622 int main(int argc, char **argv)
2623 {
2624 #ifdef CONFIG_GDBSTUB
2625     int use_gdbstub, gdbstub_port;
2626 #endif
2627     int i, has_cdrom;
2628     int snapshot, linux_boot;
2629     CPUState *env;
2630     const char *initrd_filename;
2631     const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2632     const char *kernel_filename, *kernel_cmdline;
2633     DisplayState *ds = &display_state;
2634     int cyls, heads, secs;
2635     int start_emulation = 1;
2636     uint8_t macaddr[6];
2637     int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2638     int optind;
2639     const char *r, *optarg;
2640     CharDriverState *monitor_hd;
2641     char monitor_device[128];
2642     char serial_devices[MAX_SERIAL_PORTS][128];
2643     int serial_device_index;
2644     
2645 #if !defined(CONFIG_SOFTMMU)
2646     /* we never want that malloc() uses mmap() */
2647     mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2648 #endif
2649     initrd_filename = NULL;
2650     for(i = 0; i < MAX_FD; i++)
2651         fd_filename[i] = NULL;
2652     for(i = 0; i < MAX_DISKS; i++)
2653         hd_filename[i] = NULL;
2654     ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2655     vga_ram_size = VGA_RAM_SIZE;
2656     bios_size = BIOS_SIZE;
2657     pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2658 #ifdef CONFIG_GDBSTUB
2659     use_gdbstub = 0;
2660     gdbstub_port = DEFAULT_GDBSTUB_PORT;
2661 #endif
2662     snapshot = 0;
2663     nographic = 0;
2664     kernel_filename = NULL;
2665     kernel_cmdline = "";
2666     has_cdrom = 1;
2667     cyls = heads = secs = 0;
2668     pstrcpy(monitor_device, sizeof(monitor_device), "vc");
2669
2670     pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
2671     for(i = 1; i < MAX_SERIAL_PORTS; i++)
2672         serial_devices[i][0] = '\0';
2673     serial_device_index = 0;
2674     
2675     nb_tun_fds = 0;
2676     net_if_type = -1;
2677     nb_nics = 1;
2678     /* default mac address of the first network interface */
2679     macaddr[0] = 0x52;
2680     macaddr[1] = 0x54;
2681     macaddr[2] = 0x00;
2682     macaddr[3] = 0x12;
2683     macaddr[4] = 0x34;
2684     macaddr[5] = 0x56;
2685     
2686     optind = 1;
2687     for(;;) {
2688         if (optind >= argc)
2689             break;
2690         r = argv[optind];
2691         if (r[0] != '-') {
2692             hd_filename[0] = argv[optind++];
2693         } else {
2694             const QEMUOption *popt;
2695
2696             optind++;
2697             popt = qemu_options;
2698             for(;;) {
2699                 if (!popt->name) {
2700                     fprintf(stderr, "%s: invalid option -- '%s'\n", 
2701                             argv[0], r);
2702                     exit(1);
2703                 }
2704                 if (!strcmp(popt->name, r + 1))
2705                     break;
2706                 popt++;
2707             }
2708             if (popt->flags & HAS_ARG) {
2709                 if (optind >= argc) {
2710                     fprintf(stderr, "%s: option '%s' requires an argument\n",
2711                             argv[0], r);
2712                     exit(1);
2713                 }
2714                 optarg = argv[optind++];
2715             } else {
2716                 optarg = NULL;
2717             }
2718
2719             switch(popt->index) {
2720             case QEMU_OPTION_initrd:
2721                 initrd_filename = optarg;
2722                 break;
2723             case QEMU_OPTION_hda:
2724                 hd_filename[0] = optarg;
2725                 break;
2726             case QEMU_OPTION_hdb:
2727                 hd_filename[1] = optarg;
2728                 break;
2729             case QEMU_OPTION_snapshot:
2730                 snapshot = 1;
2731                 break;
2732             case QEMU_OPTION_hdachs:
2733                 {
2734                     const char *p;
2735                     p = optarg;
2736                     cyls = strtol(p, (char **)&p, 0);
2737                     if (*p != ',')
2738                         goto chs_fail;
2739                     p++;
2740                     heads = strtol(p, (char **)&p, 0);
2741                     if (*p != ',')
2742                         goto chs_fail;
2743                     p++;
2744                     secs = strtol(p, (char **)&p, 0);
2745                     if (*p != '\0') {
2746                     chs_fail:
2747                         cyls = 0;
2748                     }
2749                 }
2750                 break;
2751             case QEMU_OPTION_nographic:
2752                 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
2753                 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
2754                 nographic = 1;
2755                 break;
2756             case QEMU_OPTION_kernel:
2757                 kernel_filename = optarg;
2758                 break;
2759             case QEMU_OPTION_append:
2760                 kernel_cmdline = optarg;
2761                 break;
2762             case QEMU_OPTION_tun_fd:
2763                 {
2764                     const char *p;
2765                     int fd;
2766                     net_if_type = NET_IF_TUN;
2767                     if (nb_tun_fds < MAX_NICS) {
2768                         fd = strtol(optarg, (char **)&p, 0);
2769                         if (*p != '\0') {
2770                             fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2771                             exit(1);
2772                         }
2773                         tun_fds[nb_tun_fds++] = fd;
2774                     }
2775                 }
2776                 break;
2777             case QEMU_OPTION_hdc:
2778                 hd_filename[2] = optarg;
2779                 has_cdrom = 0;
2780                 break;
2781             case QEMU_OPTION_hdd:
2782                 hd_filename[3] = optarg;
2783                 break;
2784             case QEMU_OPTION_cdrom:
2785                 hd_filename[2] = optarg;
2786                 has_cdrom = 1;
2787                 break;
2788             case QEMU_OPTION_boot:
2789                 boot_device = optarg[0];
2790                 if (boot_device != 'a' && boot_device != 'b' &&
2791                     boot_device != 'c' && boot_device != 'd') {
2792                     fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2793                     exit(1);
2794                 }
2795                 break;
2796             case QEMU_OPTION_fda:
2797                 fd_filename[0] = optarg;
2798                 break;
2799             case QEMU_OPTION_fdb:
2800                 fd_filename[1] = optarg;
2801                 break;
2802             case QEMU_OPTION_no_code_copy:
2803                 code_copy_enabled = 0;
2804                 break;
2805             case QEMU_OPTION_nics:
2806                 nb_nics = atoi(optarg);
2807                 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2808                     fprintf(stderr, "qemu: invalid number of network interfaces\n");
2809                     exit(1);
2810                 }
2811                 break;
2812             case QEMU_OPTION_macaddr:
2813                 {
2814                     const char *p;
2815                     int i;
2816                     p = optarg;
2817                     for(i = 0; i < 6; i++) {
2818                         macaddr[i] = strtol(p, (char **)&p, 16);
2819                         if (i == 5) {
2820                             if (*p != '\0') 
2821                                 goto macaddr_error;
2822                         } else {
2823                             if (*p != ':') {
2824                             macaddr_error:
2825                                 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2826                                 exit(1);
2827                             }
2828                             p++;
2829                         }
2830                     }
2831                 }
2832                 break;
2833 #ifdef CONFIG_SLIRP
2834             case QEMU_OPTION_tftp:
2835                 tftp_prefix = optarg;
2836                 break;
2837             case QEMU_OPTION_user_net:
2838                 net_if_type = NET_IF_USER;
2839                 break;
2840             case QEMU_OPTION_redir:
2841                 net_slirp_redir(optarg);                
2842                 break;
2843 #endif
2844             case QEMU_OPTION_dummy_net:
2845                 net_if_type = NET_IF_DUMMY;
2846                 break;
2847             case QEMU_OPTION_enable_audio:
2848                 audio_enabled = 1;
2849                 break;
2850             case QEMU_OPTION_h:
2851                 help();
2852                 break;
2853             case QEMU_OPTION_m:
2854                 ram_size = atoi(optarg) * 1024 * 1024;
2855                 if (ram_size <= 0)
2856                     help();
2857                 if (ram_size > PHYS_RAM_MAX_SIZE) {
2858                     fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
2859                             PHYS_RAM_MAX_SIZE / (1024 * 1024));
2860                     exit(1);
2861                 }
2862                 break;
2863             case QEMU_OPTION_d:
2864                 {
2865                     int mask;
2866                     CPULogItem *item;
2867                     
2868                     mask = cpu_str_to_log_mask(optarg);
2869                     if (!mask) {
2870                         printf("Log items (comma separated):\n");
2871                     for(item = cpu_log_items; item->mask != 0; item++) {
2872                         printf("%-10s %s\n", item->name, item->help);
2873                     }
2874                     exit(1);
2875                     }
2876                     cpu_set_log(mask);
2877                 }
2878                 break;
2879             case QEMU_OPTION_n:
2880                 pstrcpy(network_script, sizeof(network_script), optarg);
2881                 break;
2882 #ifdef CONFIG_GDBSTUB
2883             case QEMU_OPTION_s:
2884                 use_gdbstub = 1;
2885                 break;
2886             case QEMU_OPTION_p:
2887                 gdbstub_port = atoi(optarg);
2888                 break;
2889 #endif
2890             case QEMU_OPTION_L:
2891                 bios_dir = optarg;
2892                 break;
2893             case QEMU_OPTION_S:
2894                 start_emulation = 0;
2895                 break;
2896             case QEMU_OPTION_pci:
2897                 pci_enabled = 1;
2898                 break;
2899             case QEMU_OPTION_isa:
2900                 pci_enabled = 0;
2901                 break;
2902             case QEMU_OPTION_prep:
2903                 prep_enabled = 1;
2904                 break;
2905             case QEMU_OPTION_localtime:
2906                 rtc_utc = 0;
2907                 break;
2908             case QEMU_OPTION_cirrusvga:
2909                 cirrus_vga_enabled = 1;
2910                 break;
2911             case QEMU_OPTION_std_vga:
2912                 cirrus_vga_enabled = 0;
2913                 break;
2914             case QEMU_OPTION_g:
2915                 {
2916                     const char *p;
2917                     int w, h, depth;
2918                     p = optarg;
2919                     w = strtol(p, (char **)&p, 10);
2920                     if (w <= 0) {
2921                     graphic_error:
2922                         fprintf(stderr, "qemu: invalid resolution or depth\n");
2923                         exit(1);
2924                     }
2925                     if (*p != 'x')
2926                         goto graphic_error;
2927                     p++;
2928                     h = strtol(p, (char **)&p, 10);
2929                     if (h <= 0)
2930                         goto graphic_error;
2931                     if (*p == 'x') {
2932                         p++;
2933                         depth = strtol(p, (char **)&p, 10);
2934                         if (depth != 8 && depth != 15 && depth != 16 && 
2935                             depth != 24 && depth != 32)
2936                             goto graphic_error;
2937                     } else if (*p == '\0') {
2938                         depth = graphic_depth;
2939                     } else {
2940                         goto graphic_error;
2941                     }
2942                     
2943                     graphic_width = w;
2944                     graphic_height = h;
2945                     graphic_depth = depth;
2946                 }
2947                 break;
2948             case QEMU_OPTION_monitor:
2949                 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
2950                 break;
2951             case QEMU_OPTION_serial:
2952                 if (serial_device_index >= MAX_SERIAL_PORTS) {
2953                     fprintf(stderr, "qemu: too many serial ports\n");
2954                     exit(1);
2955                 }
2956                 pstrcpy(serial_devices[serial_device_index], 
2957                         sizeof(serial_devices[0]), optarg);
2958                 serial_device_index++;
2959                 break;
2960             }
2961         }
2962     }
2963
2964     linux_boot = (kernel_filename != NULL);
2965         
2966     if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2967         fd_filename[0] == '\0')
2968         help();
2969     
2970     /* boot to cd by default if no hard disk */
2971     if (hd_filename[0] == '\0' && boot_device == 'c') {
2972         if (fd_filename[0] != '\0')
2973             boot_device = 'a';
2974         else
2975             boot_device = 'd';
2976     }
2977
2978 #if !defined(CONFIG_SOFTMMU)
2979     /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2980     {
2981         static uint8_t stdout_buf[4096];
2982         setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2983     }
2984 #else
2985     setvbuf(stdout, NULL, _IOLBF, 0);
2986 #endif
2987
2988     /* init host network redirectors */
2989     if (net_if_type == -1) {
2990         net_if_type = NET_IF_TUN;
2991 #if defined(CONFIG_SLIRP)
2992         if (access(network_script, R_OK) < 0) {
2993             net_if_type = NET_IF_USER;
2994         }
2995 #endif
2996     }
2997
2998     for(i = 0; i < nb_nics; i++) {
2999         NetDriverState *nd = &nd_table[i];
3000         nd->index = i;
3001         /* init virtual mac address */
3002         nd->macaddr[0] = macaddr[0];
3003         nd->macaddr[1] = macaddr[1];
3004         nd->macaddr[2] = macaddr[2];
3005         nd->macaddr[3] = macaddr[3];
3006         nd->macaddr[4] = macaddr[4];
3007         nd->macaddr[5] = macaddr[5] + i;
3008         switch(net_if_type) {
3009 #if defined(CONFIG_SLIRP)
3010         case NET_IF_USER:
3011             net_slirp_init(nd);
3012             break;
3013 #endif
3014 #if !defined(_WIN32)
3015         case NET_IF_TUN:
3016             if (i < nb_tun_fds) {
3017                 net_fd_init(nd, tun_fds[i]);
3018             } else {
3019                 if (net_tun_init(nd) < 0)
3020                     net_dummy_init(nd);
3021             }
3022             break;
3023 #endif
3024         case NET_IF_DUMMY:
3025         default:
3026             net_dummy_init(nd);
3027             break;
3028         }
3029     }
3030
3031     /* init the memory */
3032     phys_ram_size = ram_size + vga_ram_size + bios_size;
3033
3034 #ifdef CONFIG_SOFTMMU
3035 #ifdef _BSD
3036     /* mallocs are always aligned on BSD. valloc is better for correctness */
3037     phys_ram_base = valloc(phys_ram_size);
3038 #else
3039     phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
3040 #endif
3041     if (!phys_ram_base) {
3042         fprintf(stderr, "Could not allocate physical memory\n");
3043         exit(1);
3044     }
3045 #else
3046     /* as we must map the same page at several addresses, we must use
3047        a fd */
3048     {
3049         const char *tmpdir;
3050
3051         tmpdir = getenv("QEMU_TMPDIR");
3052         if (!tmpdir)
3053             tmpdir = "/tmp";
3054         snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
3055         if (mkstemp(phys_ram_file) < 0) {
3056             fprintf(stderr, "Could not create temporary memory file '%s'\n", 
3057                     phys_ram_file);
3058             exit(1);
3059         }
3060         phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
3061         if (phys_ram_fd < 0) {
3062             fprintf(stderr, "Could not open temporary memory file '%s'\n", 
3063                     phys_ram_file);
3064             exit(1);
3065         }
3066         ftruncate(phys_ram_fd, phys_ram_size);
3067         unlink(phys_ram_file);
3068         phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
3069                              phys_ram_size, 
3070                              PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
3071                              phys_ram_fd, 0);
3072         if (phys_ram_base == MAP_FAILED) {
3073             fprintf(stderr, "Could not map physical memory\n");
3074             exit(1);
3075         }
3076     }
3077 #endif
3078
3079     /* we always create the cdrom drive, even if no disk is there */
3080     bdrv_init();
3081     if (has_cdrom) {
3082         bs_table[2] = bdrv_new("cdrom");
3083         bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
3084     }
3085
3086     /* open the virtual block devices */
3087     for(i = 0; i < MAX_DISKS; i++) {
3088         if (hd_filename[i]) {
3089             if (!bs_table[i]) {
3090                 char buf[64];
3091                 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3092                 bs_table[i] = bdrv_new(buf);
3093             }
3094             if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3095                 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3096                         hd_filename[i]);
3097                 exit(1);
3098             }
3099             if (i == 0 && cyls != 0) 
3100                 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3101         }
3102     }
3103
3104     /* we always create at least one floppy disk */
3105     fd_table[0] = bdrv_new("fda");
3106     bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3107
3108     for(i = 0; i < MAX_FD; i++) {
3109         if (fd_filename[i]) {
3110             if (!fd_table[i]) {
3111                 char buf[64];
3112                 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3113                 fd_table[i] = bdrv_new(buf);
3114                 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3115             }
3116             if (fd_filename[i] != '\0') {
3117                 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3118                     fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3119                             fd_filename[i]);
3120                     exit(1);
3121                 }
3122             }
3123         }
3124     }
3125
3126     /* init CPU state */
3127     env = cpu_init();
3128     global_env = env;
3129     cpu_single_env = env;
3130
3131     register_savevm("timer", 0, 1, timer_save, timer_load, env);
3132     register_savevm("cpu", 0, 2, cpu_save, cpu_load, env);
3133     register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
3134     qemu_register_reset(main_cpu_reset, global_env);
3135
3136     init_ioports();
3137     cpu_calibrate_ticks();
3138
3139     /* terminal init */
3140     if (nographic) {
3141         dumb_display_init(ds);
3142     } else {
3143 #ifdef CONFIG_SDL
3144         sdl_display_init(ds);
3145 #else
3146         dumb_display_init(ds);
3147 #endif
3148     }
3149
3150     vga_console = graphic_console_init(ds);
3151     
3152     monitor_hd = qemu_chr_open(monitor_device);
3153     if (!monitor_hd) {
3154         fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3155         exit(1);
3156     }
3157     monitor_init(monitor_hd, !nographic);
3158
3159     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3160         if (serial_devices[i][0] != '\0') {
3161             serial_hds[i] = qemu_chr_open(serial_devices[i]);
3162             if (!serial_hds[i]) {
3163                 fprintf(stderr, "qemu: could not open serial device '%s'\n", 
3164                         serial_devices[i]);
3165                 exit(1);
3166             }
3167             if (!strcmp(serial_devices[i], "vc"))
3168                 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3169         }
3170     }
3171
3172     /* setup cpu signal handlers for MMU / self modifying code handling */
3173 #if !defined(CONFIG_SOFTMMU)
3174     
3175 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3176     {
3177         stack_t stk;
3178         signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3179         stk.ss_sp = signal_stack;
3180         stk.ss_size = SIGNAL_STACK_SIZE;
3181         stk.ss_flags = 0;
3182
3183         if (sigaltstack(&stk, NULL) < 0) {
3184             perror("sigaltstack");
3185             exit(1);
3186         }
3187     }
3188 #endif
3189     {
3190         struct sigaction act;
3191         
3192         sigfillset(&act.sa_mask);
3193         act.sa_flags = SA_SIGINFO;
3194 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3195         act.sa_flags |= SA_ONSTACK;
3196 #endif
3197         act.sa_sigaction = host_segv_handler;
3198         sigaction(SIGSEGV, &act, NULL);
3199         sigaction(SIGBUS, &act, NULL);
3200 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3201         sigaction(SIGFPE, &act, NULL);
3202 #endif
3203     }
3204 #endif
3205
3206 #ifndef _WIN32
3207     {
3208         struct sigaction act;
3209         sigfillset(&act.sa_mask);
3210         act.sa_flags = 0;
3211         act.sa_handler = SIG_IGN;
3212         sigaction(SIGPIPE, &act, NULL);
3213     }
3214 #endif
3215     init_timers();
3216
3217 #if defined(TARGET_I386)
3218     pc_init(ram_size, vga_ram_size, boot_device,
3219             ds, fd_filename, snapshot,
3220             kernel_filename, kernel_cmdline, initrd_filename);
3221 #elif defined(TARGET_PPC)
3222     ppc_init(ram_size, vga_ram_size, boot_device,
3223              ds, fd_filename, snapshot,
3224              kernel_filename, kernel_cmdline, initrd_filename);
3225 #endif
3226
3227     gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3228     qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3229
3230 #ifdef CONFIG_GDBSTUB
3231     if (use_gdbstub) {
3232         if (gdbserver_start(gdbstub_port) < 0) {
3233             fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
3234                     gdbstub_port);
3235             exit(1);
3236         } else {
3237             printf("Waiting gdb connection on port %d\n", gdbstub_port);
3238         }
3239     } else 
3240 #endif
3241     {
3242         /* XXX: simplify init */
3243         read_passwords();
3244         if (start_emulation) {
3245             vm_start();
3246         }
3247     }
3248     main_loop();
3249     quit_timers();
3250     return 0;
3251 }