TFTP support (Magnus Damm)
[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 #endif /* CONFIG_SLIRP */
1386
1387 #if !defined(_WIN32)
1388 #ifdef _BSD
1389 static int tun_open(char *ifname, int ifname_size)
1390 {
1391     int fd;
1392     char *dev;
1393     struct stat s;
1394
1395     fd = open("/dev/tap", O_RDWR);
1396     if (fd < 0) {
1397         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1398         return -1;
1399     }
1400
1401     fstat(fd, &s);
1402     dev = devname(s.st_rdev, S_IFCHR);
1403     pstrcpy(ifname, ifname_size, dev);
1404
1405     fcntl(fd, F_SETFL, O_NONBLOCK);
1406     return fd;
1407 }
1408 #else
1409 static int tun_open(char *ifname, int ifname_size)
1410 {
1411     struct ifreq ifr;
1412     int fd, ret;
1413     
1414     fd = open("/dev/net/tun", O_RDWR);
1415     if (fd < 0) {
1416         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1417         return -1;
1418     }
1419     memset(&ifr, 0, sizeof(ifr));
1420     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1421     pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1422     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1423     if (ret != 0) {
1424         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1425         close(fd);
1426         return -1;
1427     }
1428     printf("Connected to host network interface: %s\n", ifr.ifr_name);
1429     pstrcpy(ifname, ifname_size, ifr.ifr_name);
1430     fcntl(fd, F_SETFL, O_NONBLOCK);
1431     return fd;
1432 }
1433 #endif
1434
1435 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1436 {
1437     write(nd->fd, buf, size);
1438 }
1439
1440 static void tun_add_read_packet(NetDriverState *nd, 
1441                                 IOCanRWHandler *fd_can_read, 
1442                                 IOReadHandler *fd_read, void *opaque)
1443 {
1444     qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1445 }
1446
1447 static int net_tun_init(NetDriverState *nd)
1448 {
1449     int pid, status;
1450     char *args[3];
1451     char **parg;
1452
1453     nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1454     if (nd->fd < 0)
1455         return -1;
1456
1457     /* try to launch network init script */
1458     pid = fork();
1459     if (pid >= 0) {
1460         if (pid == 0) {
1461             parg = args;
1462             *parg++ = network_script;
1463             *parg++ = nd->ifname;
1464             *parg++ = NULL;
1465             execv(network_script, args);
1466             exit(1);
1467         }
1468         while (waitpid(pid, &status, 0) != pid);
1469         if (!WIFEXITED(status) ||
1470             WEXITSTATUS(status) != 0) {
1471             fprintf(stderr, "%s: could not launch network script\n",
1472                     network_script);
1473         }
1474     }
1475     nd->send_packet = tun_send_packet;
1476     nd->add_read_packet = tun_add_read_packet;
1477     return 0;
1478 }
1479
1480 static int net_fd_init(NetDriverState *nd, int fd)
1481 {
1482     nd->fd = fd;
1483     nd->send_packet = tun_send_packet;
1484     nd->add_read_packet = tun_add_read_packet;
1485     pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1486     return 0;
1487 }
1488
1489 #endif /* !_WIN32 */
1490
1491 /***********************************************************/
1492 /* dumb display */
1493
1494 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1495 {
1496 }
1497
1498 static void dumb_resize(DisplayState *ds, int w, int h)
1499 {
1500 }
1501
1502 static void dumb_refresh(DisplayState *ds)
1503 {
1504     vga_update_display();
1505 }
1506
1507 void dumb_display_init(DisplayState *ds)
1508 {
1509     ds->data = NULL;
1510     ds->linesize = 0;
1511     ds->depth = 0;
1512     ds->dpy_update = dumb_update;
1513     ds->dpy_resize = dumb_resize;
1514     ds->dpy_refresh = dumb_refresh;
1515 }
1516
1517 #if !defined(CONFIG_SOFTMMU)
1518 /***********************************************************/
1519 /* cpu signal handler */
1520 static void host_segv_handler(int host_signum, siginfo_t *info, 
1521                               void *puc)
1522 {
1523     if (cpu_signal_handler(host_signum, info, puc))
1524         return;
1525     if (stdio_nb_clients > 0)
1526         term_exit();
1527     abort();
1528 }
1529 #endif
1530
1531 /***********************************************************/
1532 /* I/O handling */
1533
1534 #define MAX_IO_HANDLERS 64
1535
1536 typedef struct IOHandlerRecord {
1537     int fd;
1538     IOCanRWHandler *fd_can_read;
1539     IOReadHandler *fd_read;
1540     void *opaque;
1541     /* temporary data */
1542     struct pollfd *ufd;
1543     int max_size;
1544     struct IOHandlerRecord *next;
1545 } IOHandlerRecord;
1546
1547 static IOHandlerRecord *first_io_handler;
1548
1549 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
1550                              IOReadHandler *fd_read, void *opaque)
1551 {
1552     IOHandlerRecord *ioh;
1553
1554     ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1555     if (!ioh)
1556         return -1;
1557     ioh->fd = fd;
1558     ioh->fd_can_read = fd_can_read;
1559     ioh->fd_read = fd_read;
1560     ioh->opaque = opaque;
1561     ioh->next = first_io_handler;
1562     first_io_handler = ioh;
1563     return 0;
1564 }
1565
1566 void qemu_del_fd_read_handler(int fd)
1567 {
1568     IOHandlerRecord **pioh, *ioh;
1569
1570     pioh = &first_io_handler;
1571     for(;;) {
1572         ioh = *pioh;
1573         if (ioh == NULL)
1574             break;
1575         if (ioh->fd == fd) {
1576             *pioh = ioh->next;
1577             break;
1578         }
1579         pioh = &ioh->next;
1580     }
1581 }
1582
1583 /***********************************************************/
1584 /* savevm/loadvm support */
1585
1586 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1587 {
1588     fwrite(buf, 1, size, f);
1589 }
1590
1591 void qemu_put_byte(QEMUFile *f, int v)
1592 {
1593     fputc(v, f);
1594 }
1595
1596 void qemu_put_be16(QEMUFile *f, unsigned int v)
1597 {
1598     qemu_put_byte(f, v >> 8);
1599     qemu_put_byte(f, v);
1600 }
1601
1602 void qemu_put_be32(QEMUFile *f, unsigned int v)
1603 {
1604     qemu_put_byte(f, v >> 24);
1605     qemu_put_byte(f, v >> 16);
1606     qemu_put_byte(f, v >> 8);
1607     qemu_put_byte(f, v);
1608 }
1609
1610 void qemu_put_be64(QEMUFile *f, uint64_t v)
1611 {
1612     qemu_put_be32(f, v >> 32);
1613     qemu_put_be32(f, v);
1614 }
1615
1616 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1617 {
1618     return fread(buf, 1, size, f);
1619 }
1620
1621 int qemu_get_byte(QEMUFile *f)
1622 {
1623     int v;
1624     v = fgetc(f);
1625     if (v == EOF)
1626         return 0;
1627     else
1628         return v;
1629 }
1630
1631 unsigned int qemu_get_be16(QEMUFile *f)
1632 {
1633     unsigned int v;
1634     v = qemu_get_byte(f) << 8;
1635     v |= qemu_get_byte(f);
1636     return v;
1637 }
1638
1639 unsigned int qemu_get_be32(QEMUFile *f)
1640 {
1641     unsigned int v;
1642     v = qemu_get_byte(f) << 24;
1643     v |= qemu_get_byte(f) << 16;
1644     v |= qemu_get_byte(f) << 8;
1645     v |= qemu_get_byte(f);
1646     return v;
1647 }
1648
1649 uint64_t qemu_get_be64(QEMUFile *f)
1650 {
1651     uint64_t v;
1652     v = (uint64_t)qemu_get_be32(f) << 32;
1653     v |= qemu_get_be32(f);
1654     return v;
1655 }
1656
1657 int64_t qemu_ftell(QEMUFile *f)
1658 {
1659     return ftell(f);
1660 }
1661
1662 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1663 {
1664     if (fseek(f, pos, whence) < 0)
1665         return -1;
1666     return ftell(f);
1667 }
1668
1669 typedef struct SaveStateEntry {
1670     char idstr[256];
1671     int instance_id;
1672     int version_id;
1673     SaveStateHandler *save_state;
1674     LoadStateHandler *load_state;
1675     void *opaque;
1676     struct SaveStateEntry *next;
1677 } SaveStateEntry;
1678
1679 static SaveStateEntry *first_se;
1680
1681 int register_savevm(const char *idstr, 
1682                     int instance_id, 
1683                     int version_id,
1684                     SaveStateHandler *save_state,
1685                     LoadStateHandler *load_state,
1686                     void *opaque)
1687 {
1688     SaveStateEntry *se, **pse;
1689
1690     se = qemu_malloc(sizeof(SaveStateEntry));
1691     if (!se)
1692         return -1;
1693     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1694     se->instance_id = instance_id;
1695     se->version_id = version_id;
1696     se->save_state = save_state;
1697     se->load_state = load_state;
1698     se->opaque = opaque;
1699     se->next = NULL;
1700
1701     /* add at the end of list */
1702     pse = &first_se;
1703     while (*pse != NULL)
1704         pse = &(*pse)->next;
1705     *pse = se;
1706     return 0;
1707 }
1708
1709 #define QEMU_VM_FILE_MAGIC   0x5145564d
1710 #define QEMU_VM_FILE_VERSION 0x00000001
1711
1712 int qemu_savevm(const char *filename)
1713 {
1714     SaveStateEntry *se;
1715     QEMUFile *f;
1716     int len, len_pos, cur_pos, saved_vm_running, ret;
1717
1718     saved_vm_running = vm_running;
1719     vm_stop(0);
1720
1721     f = fopen(filename, "wb");
1722     if (!f) {
1723         ret = -1;
1724         goto the_end;
1725     }
1726
1727     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1728     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1729
1730     for(se = first_se; se != NULL; se = se->next) {
1731         /* ID string */
1732         len = strlen(se->idstr);
1733         qemu_put_byte(f, len);
1734         qemu_put_buffer(f, se->idstr, len);
1735
1736         qemu_put_be32(f, se->instance_id);
1737         qemu_put_be32(f, se->version_id);
1738
1739         /* record size: filled later */
1740         len_pos = ftell(f);
1741         qemu_put_be32(f, 0);
1742         
1743         se->save_state(f, se->opaque);
1744
1745         /* fill record size */
1746         cur_pos = ftell(f);
1747         len = ftell(f) - len_pos - 4;
1748         fseek(f, len_pos, SEEK_SET);
1749         qemu_put_be32(f, len);
1750         fseek(f, cur_pos, SEEK_SET);
1751     }
1752
1753     fclose(f);
1754     ret = 0;
1755  the_end:
1756     if (saved_vm_running)
1757         vm_start();
1758     return ret;
1759 }
1760
1761 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1762 {
1763     SaveStateEntry *se;
1764
1765     for(se = first_se; se != NULL; se = se->next) {
1766         if (!strcmp(se->idstr, idstr) && 
1767             instance_id == se->instance_id)
1768             return se;
1769     }
1770     return NULL;
1771 }
1772
1773 int qemu_loadvm(const char *filename)
1774 {
1775     SaveStateEntry *se;
1776     QEMUFile *f;
1777     int len, cur_pos, ret, instance_id, record_len, version_id;
1778     int saved_vm_running;
1779     unsigned int v;
1780     char idstr[256];
1781     
1782     saved_vm_running = vm_running;
1783     vm_stop(0);
1784
1785     f = fopen(filename, "rb");
1786     if (!f) {
1787         ret = -1;
1788         goto the_end;
1789     }
1790
1791     v = qemu_get_be32(f);
1792     if (v != QEMU_VM_FILE_MAGIC)
1793         goto fail;
1794     v = qemu_get_be32(f);
1795     if (v != QEMU_VM_FILE_VERSION) {
1796     fail:
1797         fclose(f);
1798         ret = -1;
1799         goto the_end;
1800     }
1801     for(;;) {
1802 #if defined (DO_TB_FLUSH)
1803         tb_flush(global_env);
1804 #endif
1805         len = qemu_get_byte(f);
1806         if (feof(f))
1807             break;
1808         qemu_get_buffer(f, idstr, len);
1809         idstr[len] = '\0';
1810         instance_id = qemu_get_be32(f);
1811         version_id = qemu_get_be32(f);
1812         record_len = qemu_get_be32(f);
1813 #if 0
1814         printf("idstr=%s instance=0x%x version=%d len=%d\n", 
1815                idstr, instance_id, version_id, record_len);
1816 #endif
1817         cur_pos = ftell(f);
1818         se = find_se(idstr, instance_id);
1819         if (!se) {
1820             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
1821                     instance_id, idstr);
1822         } else {
1823             ret = se->load_state(f, se->opaque, version_id);
1824             if (ret < 0) {
1825                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
1826                         instance_id, idstr);
1827             }
1828         }
1829         /* always seek to exact end of record */
1830         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1831     }
1832     fclose(f);
1833     ret = 0;
1834  the_end:
1835     if (saved_vm_running)
1836         vm_start();
1837     return ret;
1838 }
1839
1840 /***********************************************************/
1841 /* cpu save/restore */
1842
1843 #if defined(TARGET_I386)
1844
1845 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
1846 {
1847     qemu_put_be32(f, dt->selector);
1848     qemu_put_be32(f, (uint32_t)dt->base);
1849     qemu_put_be32(f, dt->limit);
1850     qemu_put_be32(f, dt->flags);
1851 }
1852
1853 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
1854 {
1855     dt->selector = qemu_get_be32(f);
1856     dt->base = (uint8_t *)qemu_get_be32(f);
1857     dt->limit = qemu_get_be32(f);
1858     dt->flags = qemu_get_be32(f);
1859 }
1860
1861 void cpu_save(QEMUFile *f, void *opaque)
1862 {
1863     CPUState *env = opaque;
1864     uint16_t fptag, fpus, fpuc;
1865     uint32_t hflags;
1866     int i;
1867
1868     for(i = 0; i < 8; i++)
1869         qemu_put_be32s(f, &env->regs[i]);
1870     qemu_put_be32s(f, &env->eip);
1871     qemu_put_be32s(f, &env->eflags);
1872     qemu_put_be32s(f, &env->eflags);
1873     hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
1874     qemu_put_be32s(f, &hflags);
1875     
1876     /* FPU */
1877     fpuc = env->fpuc;
1878     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
1879     fptag = 0;
1880     for (i=7; i>=0; i--) {
1881         fptag <<= 2;
1882         if (env->fptags[i]) {
1883             fptag |= 3;
1884         }
1885     }
1886     
1887     qemu_put_be16s(f, &fpuc);
1888     qemu_put_be16s(f, &fpus);
1889     qemu_put_be16s(f, &fptag);
1890
1891     for(i = 0; i < 8; i++) {
1892         uint64_t mant;
1893         uint16_t exp;
1894         cpu_get_fp80(&mant, &exp, env->fpregs[i]);
1895         qemu_put_be64(f, mant);
1896         qemu_put_be16(f, exp);
1897     }
1898
1899     for(i = 0; i < 6; i++)
1900         cpu_put_seg(f, &env->segs[i]);
1901     cpu_put_seg(f, &env->ldt);
1902     cpu_put_seg(f, &env->tr);
1903     cpu_put_seg(f, &env->gdt);
1904     cpu_put_seg(f, &env->idt);
1905     
1906     qemu_put_be32s(f, &env->sysenter_cs);
1907     qemu_put_be32s(f, &env->sysenter_esp);
1908     qemu_put_be32s(f, &env->sysenter_eip);
1909     
1910     qemu_put_be32s(f, &env->cr[0]);
1911     qemu_put_be32s(f, &env->cr[2]);
1912     qemu_put_be32s(f, &env->cr[3]);
1913     qemu_put_be32s(f, &env->cr[4]);
1914     
1915     for(i = 0; i < 8; i++)
1916         qemu_put_be32s(f, &env->dr[i]);
1917
1918     /* MMU */
1919     qemu_put_be32s(f, &env->a20_mask);
1920 }
1921
1922 int cpu_load(QEMUFile *f, void *opaque, int version_id)
1923 {
1924     CPUState *env = opaque;
1925     int i;
1926     uint32_t hflags;
1927     uint16_t fpus, fpuc, fptag;
1928
1929     if (version_id != 2)
1930         return -EINVAL;
1931     for(i = 0; i < 8; i++)
1932         qemu_get_be32s(f, &env->regs[i]);
1933     qemu_get_be32s(f, &env->eip);
1934     qemu_get_be32s(f, &env->eflags);
1935     qemu_get_be32s(f, &env->eflags);
1936     qemu_get_be32s(f, &hflags);
1937
1938     qemu_get_be16s(f, &fpuc);
1939     qemu_get_be16s(f, &fpus);
1940     qemu_get_be16s(f, &fptag);
1941
1942     for(i = 0; i < 8; i++) {
1943         uint64_t mant;
1944         uint16_t exp;
1945         mant = qemu_get_be64(f);
1946         exp = qemu_get_be16(f);
1947         env->fpregs[i] = cpu_set_fp80(mant, exp);
1948     }
1949
1950     env->fpuc = fpuc;
1951     env->fpstt = (fpus >> 11) & 7;
1952     env->fpus = fpus & ~0x3800;
1953     for(i = 0; i < 8; i++) {
1954         env->fptags[i] = ((fptag & 3) == 3);
1955         fptag >>= 2;
1956     }
1957     
1958     for(i = 0; i < 6; i++)
1959         cpu_get_seg(f, &env->segs[i]);
1960     cpu_get_seg(f, &env->ldt);
1961     cpu_get_seg(f, &env->tr);
1962     cpu_get_seg(f, &env->gdt);
1963     cpu_get_seg(f, &env->idt);
1964     
1965     qemu_get_be32s(f, &env->sysenter_cs);
1966     qemu_get_be32s(f, &env->sysenter_esp);
1967     qemu_get_be32s(f, &env->sysenter_eip);
1968     
1969     qemu_get_be32s(f, &env->cr[0]);
1970     qemu_get_be32s(f, &env->cr[2]);
1971     qemu_get_be32s(f, &env->cr[3]);
1972     qemu_get_be32s(f, &env->cr[4]);
1973     
1974     for(i = 0; i < 8; i++)
1975         qemu_get_be32s(f, &env->dr[i]);
1976
1977     /* MMU */
1978     qemu_get_be32s(f, &env->a20_mask);
1979
1980     /* XXX: compute hflags from scratch, except for CPL and IIF */
1981     env->hflags = hflags;
1982     tlb_flush(env, 1);
1983     return 0;
1984 }
1985
1986 #elif defined(TARGET_PPC)
1987 void cpu_save(QEMUFile *f, void *opaque)
1988 {
1989 }
1990
1991 int cpu_load(QEMUFile *f, void *opaque, int version_id)
1992 {
1993     return 0;
1994 }
1995 #else
1996
1997 #warning No CPU save/restore functions
1998
1999 #endif
2000
2001 /***********************************************************/
2002 /* ram save/restore */
2003
2004 /* we just avoid storing empty pages */
2005 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
2006 {
2007     int i, v;
2008
2009     v = buf[0];
2010     for(i = 1; i < len; i++) {
2011         if (buf[i] != v)
2012             goto normal_save;
2013     }
2014     qemu_put_byte(f, 1);
2015     qemu_put_byte(f, v);
2016     return;
2017  normal_save:
2018     qemu_put_byte(f, 0); 
2019     qemu_put_buffer(f, buf, len);
2020 }
2021
2022 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2023 {
2024     int v;
2025
2026     v = qemu_get_byte(f);
2027     switch(v) {
2028     case 0:
2029         if (qemu_get_buffer(f, buf, len) != len)
2030             return -EIO;
2031         break;
2032     case 1:
2033         v = qemu_get_byte(f);
2034         memset(buf, v, len);
2035         break;
2036     default:
2037         return -EINVAL;
2038     }
2039     return 0;
2040 }
2041
2042 static void ram_save(QEMUFile *f, void *opaque)
2043 {
2044     int i;
2045     qemu_put_be32(f, phys_ram_size);
2046     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2047         ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2048     }
2049 }
2050
2051 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2052 {
2053     int i, ret;
2054
2055     if (version_id != 1)
2056         return -EINVAL;
2057     if (qemu_get_be32(f) != phys_ram_size)
2058         return -EINVAL;
2059     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2060         ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2061         if (ret)
2062             return ret;
2063     }
2064     return 0;
2065 }
2066
2067 /***********************************************************/
2068 /* main execution loop */
2069
2070 void gui_update(void *opaque)
2071 {
2072     display_state.dpy_refresh(&display_state);
2073     qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2074 }
2075
2076 /* XXX: support several handlers */
2077 VMStopHandler *vm_stop_cb;
2078 VMStopHandler *vm_stop_opaque;
2079
2080 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2081 {
2082     vm_stop_cb = cb;
2083     vm_stop_opaque = opaque;
2084     return 0;
2085 }
2086
2087 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2088 {
2089     vm_stop_cb = NULL;
2090 }
2091
2092 void vm_start(void)
2093 {
2094     if (!vm_running) {
2095         cpu_enable_ticks();
2096         vm_running = 1;
2097     }
2098 }
2099
2100 void vm_stop(int reason) 
2101 {
2102     if (vm_running) {
2103         cpu_disable_ticks();
2104         vm_running = 0;
2105         if (reason != 0) {
2106             if (vm_stop_cb) {
2107                 vm_stop_cb(vm_stop_opaque, reason);
2108             }
2109         }
2110     }
2111 }
2112
2113 /* reset/shutdown handler */
2114
2115 typedef struct QEMUResetEntry {
2116     QEMUResetHandler *func;
2117     void *opaque;
2118     struct QEMUResetEntry *next;
2119 } QEMUResetEntry;
2120
2121 static QEMUResetEntry *first_reset_entry;
2122 static int reset_requested;
2123 static int shutdown_requested;
2124
2125 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2126 {
2127     QEMUResetEntry **pre, *re;
2128
2129     pre = &first_reset_entry;
2130     while (*pre != NULL)
2131         pre = &(*pre)->next;
2132     re = qemu_mallocz(sizeof(QEMUResetEntry));
2133     re->func = func;
2134     re->opaque = opaque;
2135     re->next = NULL;
2136     *pre = re;
2137 }
2138
2139 void qemu_system_reset(void)
2140 {
2141     QEMUResetEntry *re;
2142
2143     /* reset all devices */
2144     for(re = first_reset_entry; re != NULL; re = re->next) {
2145         re->func(re->opaque);
2146     }
2147 }
2148
2149 void qemu_system_reset_request(void)
2150 {
2151     reset_requested = 1;
2152     cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2153 }
2154
2155 void qemu_system_shutdown_request(void)
2156 {
2157     shutdown_requested = 1;
2158     cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2159 }
2160
2161 static void main_cpu_reset(void *opaque)
2162 {
2163 #ifdef TARGET_I386
2164     CPUState *env = opaque;
2165     cpu_reset(env);
2166 #endif
2167 }
2168
2169 void main_loop_wait(int timeout)
2170 {
2171 #ifndef _WIN32
2172     struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2173     IOHandlerRecord *ioh, *ioh_next;
2174     uint8_t buf[4096];
2175     int n, max_size;
2176 #endif
2177     int ret;
2178
2179 #ifdef _WIN32
2180         if (timeout > 0)
2181             Sleep(timeout);
2182 #else
2183         /* poll any events */
2184         /* XXX: separate device handlers from system ones */
2185         pf = ufds;
2186         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2187             if (!ioh->fd_can_read) {
2188                 max_size = 0;
2189                 pf->fd = ioh->fd;
2190                 pf->events = POLLIN;
2191                 ioh->ufd = pf;
2192                 pf++;
2193             } else {
2194                 max_size = ioh->fd_can_read(ioh->opaque);
2195                 if (max_size > 0) {
2196                     if (max_size > sizeof(buf))
2197                         max_size = sizeof(buf);
2198                     pf->fd = ioh->fd;
2199                     pf->events = POLLIN;
2200                     ioh->ufd = pf;
2201                     pf++;
2202                 } else {
2203                     ioh->ufd = NULL;
2204                 }
2205             }
2206             ioh->max_size = max_size;
2207         }
2208         
2209         ret = poll(ufds, pf - ufds, timeout);
2210         if (ret > 0) {
2211             /* XXX: better handling of removal */
2212             for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2213                 ioh_next = ioh->next;
2214                 pf = ioh->ufd;
2215                 if (pf) {
2216                     if (pf->revents & POLLIN) {
2217                         if (ioh->max_size == 0) {
2218                             /* just a read event */
2219                             ioh->fd_read(ioh->opaque, NULL, 0);
2220                         } else {
2221                             n = read(ioh->fd, buf, ioh->max_size);
2222                             if (n >= 0) {
2223                                 ioh->fd_read(ioh->opaque, buf, n);
2224                             } else if (errno != EAGAIN) {
2225                                 ioh->fd_read(ioh->opaque, NULL, -errno);
2226                             }
2227                         }
2228                     }
2229                 }
2230             }
2231         }
2232 #endif /* !defined(_WIN32) */
2233 #if defined(CONFIG_SLIRP)
2234         /* XXX: merge with poll() */
2235         if (slirp_inited) {
2236             fd_set rfds, wfds, xfds;
2237             int nfds;
2238             struct timeval tv;
2239
2240             nfds = -1;
2241             FD_ZERO(&rfds);
2242             FD_ZERO(&wfds);
2243             FD_ZERO(&xfds);
2244             slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2245             tv.tv_sec = 0;
2246             tv.tv_usec = 0;
2247             ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2248             if (ret >= 0) {
2249                 slirp_select_poll(&rfds, &wfds, &xfds);
2250             }
2251         }
2252 #endif
2253
2254         if (vm_running) {
2255             qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
2256                             qemu_get_clock(vm_clock));
2257             
2258             if (audio_enabled) {
2259                 /* XXX: add explicit timer */
2260                 SB16_run();
2261             }
2262             
2263             /* run dma transfers, if any */
2264             DMA_run();
2265         }
2266
2267         /* real time timers */
2268         qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
2269                         qemu_get_clock(rt_clock));
2270 }
2271
2272 int main_loop(void)
2273 {
2274     int ret, timeout;
2275     CPUState *env = global_env;
2276
2277     for(;;) {
2278         if (vm_running) {
2279             ret = cpu_exec(env);
2280             if (shutdown_requested) {
2281                 ret = EXCP_INTERRUPT; 
2282                 break;
2283             }
2284             if (reset_requested) {
2285                 reset_requested = 0;
2286                 qemu_system_reset();
2287                 ret = EXCP_INTERRUPT; 
2288             }
2289             if (ret == EXCP_DEBUG) {
2290                 vm_stop(EXCP_DEBUG);
2291             }
2292             /* if hlt instruction, we wait until the next IRQ */
2293             /* XXX: use timeout computed from timers */
2294             if (ret == EXCP_HLT) 
2295                 timeout = 10;
2296             else
2297                 timeout = 0;
2298         } else {
2299             timeout = 10;
2300         }
2301         main_loop_wait(timeout);
2302     }
2303     cpu_disable_ticks();
2304     return ret;
2305 }
2306
2307 void help(void)
2308 {
2309     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2310            "usage: %s [options] [disk_image]\n"
2311            "\n"
2312            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2313            "\n"
2314            "Standard options:\n"
2315            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
2316            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
2317            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
2318            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2319            "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
2320            "-snapshot       write to temporary files instead of disk image files\n"
2321            "-m megs         set virtual RAM size to megs MB [default=%d]\n"
2322            "-nographic      disable graphical output and redirect serial I/Os to console\n"
2323            "-enable-audio   enable audio support\n"
2324            "-localtime      set the real time clock to local time [default=utc]\n"
2325 #ifdef TARGET_PPC
2326            "-prep           Simulate a PREP system (default is PowerMAC)\n"
2327            "-g WxH[xDEPTH]  Set the initial VGA graphic mode\n"
2328 #endif
2329            "\n"
2330            "Network options:\n"
2331            "-nics n         simulate 'n' network cards [default=1]\n"
2332            "-macaddr addr   set the mac address of the first interface\n"
2333            "-n script       set tap/tun network init script [default=%s]\n"
2334            "-tun-fd fd      use this fd as already opened tap/tun interface\n"
2335 #ifdef CONFIG_SLIRP
2336            "-user-net       use user mode network stack [default if no tap/tun script]\n"
2337            "-tftp prefix    allow tftp access to files starting with prefix [only with -user-net enabled]\n"
2338 #endif
2339            "-dummy-net      use dummy network stack\n"
2340            "\n"
2341            "Linux boot specific:\n"
2342            "-kernel bzImage use 'bzImage' as kernel image\n"
2343            "-append cmdline use 'cmdline' as kernel command line\n"
2344            "-initrd file    use 'file' as initial ram disk\n"
2345            "\n"
2346            "Debug/Expert options:\n"
2347            "-monitor dev    redirect the monitor to char device 'dev'\n"
2348            "-serial dev     redirect the serial port to char device 'dev'\n"
2349            "-S              freeze CPU at startup (use 'c' to start execution)\n"
2350            "-s              wait gdb connection to port %d\n"
2351            "-p port         change gdb connection port\n"
2352            "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
2353            "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
2354            "-L path         set the directory for the BIOS and VGA BIOS\n"
2355 #ifdef USE_CODE_COPY
2356            "-no-code-copy   disable code copy acceleration\n"
2357 #endif
2358 #ifdef TARGET_I386
2359            "-isa            simulate an ISA-only system (default is PCI system)\n"
2360            "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
2361            "                (default is CL-GD5446 PCI VGA)\n"
2362 #endif
2363            "\n"
2364            "During emulation, the following keys are useful:\n"
2365            "ctrl-shift-f    toggle full screen\n"
2366            "ctrl-shift-Fn   switch to virtual console 'n'\n"
2367            "ctrl-shift      toggle mouse and keyboard grab\n"
2368            "\n"
2369            "When using -nographic, press 'ctrl-a h' to get some help.\n"
2370            ,
2371 #ifdef CONFIG_SOFTMMU
2372            "qemu",
2373 #else
2374            "qemu-fast",
2375 #endif
2376            DEFAULT_RAM_SIZE,
2377            DEFAULT_NETWORK_SCRIPT,
2378            DEFAULT_GDBSTUB_PORT,
2379            "/tmp/qemu.log");
2380 #ifndef CONFIG_SOFTMMU
2381     printf("\n"
2382            "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2383            "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2384            "PC emulation.\n");
2385 #endif
2386     exit(1);
2387 }
2388
2389 #define HAS_ARG 0x0001
2390
2391 enum {
2392     QEMU_OPTION_h,
2393
2394     QEMU_OPTION_fda,
2395     QEMU_OPTION_fdb,
2396     QEMU_OPTION_hda,
2397     QEMU_OPTION_hdb,
2398     QEMU_OPTION_hdc,
2399     QEMU_OPTION_hdd,
2400     QEMU_OPTION_cdrom,
2401     QEMU_OPTION_boot,
2402     QEMU_OPTION_snapshot,
2403     QEMU_OPTION_m,
2404     QEMU_OPTION_nographic,
2405     QEMU_OPTION_enable_audio,
2406
2407     QEMU_OPTION_nics,
2408     QEMU_OPTION_macaddr,
2409     QEMU_OPTION_n,
2410     QEMU_OPTION_tun_fd,
2411     QEMU_OPTION_user_net,
2412     QEMU_OPTION_tftp,
2413     QEMU_OPTION_dummy_net,
2414
2415     QEMU_OPTION_kernel,
2416     QEMU_OPTION_append,
2417     QEMU_OPTION_initrd,
2418
2419     QEMU_OPTION_S,
2420     QEMU_OPTION_s,
2421     QEMU_OPTION_p,
2422     QEMU_OPTION_d,
2423     QEMU_OPTION_hdachs,
2424     QEMU_OPTION_L,
2425     QEMU_OPTION_no_code_copy,
2426     QEMU_OPTION_pci,
2427     QEMU_OPTION_isa,
2428     QEMU_OPTION_prep,
2429     QEMU_OPTION_localtime,
2430     QEMU_OPTION_cirrusvga,
2431     QEMU_OPTION_g,
2432     QEMU_OPTION_std_vga,
2433     QEMU_OPTION_monitor,
2434     QEMU_OPTION_serial,
2435 };
2436
2437 typedef struct QEMUOption {
2438     const char *name;
2439     int flags;
2440     int index;
2441 } QEMUOption;
2442
2443 const QEMUOption qemu_options[] = {
2444     { "h", 0, QEMU_OPTION_h },
2445
2446     { "fda", HAS_ARG, QEMU_OPTION_fda },
2447     { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2448     { "hda", HAS_ARG, QEMU_OPTION_hda },
2449     { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2450     { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2451     { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2452     { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2453     { "boot", HAS_ARG, QEMU_OPTION_boot },
2454     { "snapshot", 0, QEMU_OPTION_snapshot },
2455     { "m", HAS_ARG, QEMU_OPTION_m },
2456     { "nographic", 0, QEMU_OPTION_nographic },
2457     { "enable-audio", 0, QEMU_OPTION_enable_audio },
2458
2459     { "nics", HAS_ARG, QEMU_OPTION_nics},
2460     { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2461     { "n", HAS_ARG, QEMU_OPTION_n },
2462     { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2463 #ifdef CONFIG_SLIRP
2464     { "user-net", 0, QEMU_OPTION_user_net },
2465     { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2466 #endif
2467     { "dummy-net", 0, QEMU_OPTION_dummy_net },
2468
2469     { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2470     { "append", HAS_ARG, QEMU_OPTION_append },
2471     { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2472
2473     { "S", 0, QEMU_OPTION_S },
2474     { "s", 0, QEMU_OPTION_s },
2475     { "p", HAS_ARG, QEMU_OPTION_p },
2476     { "d", HAS_ARG, QEMU_OPTION_d },
2477     { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2478     { "L", HAS_ARG, QEMU_OPTION_L },
2479     { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2480 #ifdef TARGET_PPC
2481     { "prep", 0, QEMU_OPTION_prep },
2482     { "g", 1, QEMU_OPTION_g },
2483 #endif
2484     { "localtime", 0, QEMU_OPTION_localtime },
2485     { "isa", 0, QEMU_OPTION_isa },
2486     { "std-vga", 0, QEMU_OPTION_std_vga },
2487     { "monitor", 1, QEMU_OPTION_monitor },
2488     { "serial", 1, QEMU_OPTION_serial },
2489     
2490     /* temporary options */
2491     { "pci", 0, QEMU_OPTION_pci },
2492     { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2493     { NULL },
2494 };
2495
2496 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2497
2498 /* this stack is only used during signal handling */
2499 #define SIGNAL_STACK_SIZE 32768
2500
2501 static uint8_t *signal_stack;
2502
2503 #endif
2504
2505 /* password input */
2506
2507 static BlockDriverState *get_bdrv(int index)
2508 {
2509     BlockDriverState *bs;
2510
2511     if (index < 4) {
2512         bs = bs_table[index];
2513     } else if (index < 6) {
2514         bs = fd_table[index - 4];
2515     } else {
2516         bs = NULL;
2517     }
2518     return bs;
2519 }
2520
2521 static void read_passwords(void)
2522 {
2523     BlockDriverState *bs;
2524     int i, j;
2525     char password[256];
2526
2527     for(i = 0; i < 6; i++) {
2528         bs = get_bdrv(i);
2529         if (bs && bdrv_is_encrypted(bs)) {
2530             term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
2531             for(j = 0; j < 3; j++) {
2532                 monitor_readline("Password: ", 
2533                                  1, password, sizeof(password));
2534                 if (bdrv_set_key(bs, password) == 0)
2535                     break;
2536                 term_printf("invalid password\n");
2537             }
2538         }
2539     }
2540 }
2541
2542 #define NET_IF_TUN   0
2543 #define NET_IF_USER  1
2544 #define NET_IF_DUMMY 2
2545
2546 int main(int argc, char **argv)
2547 {
2548 #ifdef CONFIG_GDBSTUB
2549     int use_gdbstub, gdbstub_port;
2550 #endif
2551     int i, has_cdrom;
2552     int snapshot, linux_boot;
2553     CPUState *env;
2554     const char *initrd_filename;
2555     const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2556     const char *kernel_filename, *kernel_cmdline;
2557     DisplayState *ds = &display_state;
2558     int cyls, heads, secs;
2559     int start_emulation = 1;
2560     uint8_t macaddr[6];
2561     int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2562     int optind;
2563     const char *r, *optarg;
2564     CharDriverState *monitor_hd;
2565     char monitor_device[128];
2566     char serial_devices[MAX_SERIAL_PORTS][128];
2567     int serial_device_index;
2568     
2569 #if !defined(CONFIG_SOFTMMU)
2570     /* we never want that malloc() uses mmap() */
2571     mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2572 #endif
2573     initrd_filename = NULL;
2574     for(i = 0; i < MAX_FD; i++)
2575         fd_filename[i] = NULL;
2576     for(i = 0; i < MAX_DISKS; i++)
2577         hd_filename[i] = NULL;
2578     ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2579     vga_ram_size = VGA_RAM_SIZE;
2580     bios_size = BIOS_SIZE;
2581     pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2582 #ifdef CONFIG_GDBSTUB
2583     use_gdbstub = 0;
2584     gdbstub_port = DEFAULT_GDBSTUB_PORT;
2585 #endif
2586     snapshot = 0;
2587     nographic = 0;
2588     kernel_filename = NULL;
2589     kernel_cmdline = "";
2590     has_cdrom = 1;
2591     cyls = heads = secs = 0;
2592     pstrcpy(monitor_device, sizeof(monitor_device), "vc");
2593
2594     pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
2595     for(i = 1; i < MAX_SERIAL_PORTS; i++)
2596         serial_devices[i][0] = '\0';
2597     serial_device_index = 0;
2598     
2599     nb_tun_fds = 0;
2600     net_if_type = -1;
2601     nb_nics = 1;
2602     /* default mac address of the first network interface */
2603     macaddr[0] = 0x52;
2604     macaddr[1] = 0x54;
2605     macaddr[2] = 0x00;
2606     macaddr[3] = 0x12;
2607     macaddr[4] = 0x34;
2608     macaddr[5] = 0x56;
2609     
2610     optind = 1;
2611     for(;;) {
2612         if (optind >= argc)
2613             break;
2614         r = argv[optind];
2615         if (r[0] != '-') {
2616             hd_filename[0] = argv[optind++];
2617         } else {
2618             const QEMUOption *popt;
2619
2620             optind++;
2621             popt = qemu_options;
2622             for(;;) {
2623                 if (!popt->name) {
2624                     fprintf(stderr, "%s: invalid option -- '%s'\n", 
2625                             argv[0], r);
2626                     exit(1);
2627                 }
2628                 if (!strcmp(popt->name, r + 1))
2629                     break;
2630                 popt++;
2631             }
2632             if (popt->flags & HAS_ARG) {
2633                 if (optind >= argc) {
2634                     fprintf(stderr, "%s: option '%s' requires an argument\n",
2635                             argv[0], r);
2636                     exit(1);
2637                 }
2638                 optarg = argv[optind++];
2639             } else {
2640                 optarg = NULL;
2641             }
2642
2643             switch(popt->index) {
2644             case QEMU_OPTION_initrd:
2645                 initrd_filename = optarg;
2646                 break;
2647             case QEMU_OPTION_hda:
2648                 hd_filename[0] = optarg;
2649                 break;
2650             case QEMU_OPTION_hdb:
2651                 hd_filename[1] = optarg;
2652                 break;
2653             case QEMU_OPTION_snapshot:
2654                 snapshot = 1;
2655                 break;
2656             case QEMU_OPTION_hdachs:
2657                 {
2658                     const char *p;
2659                     p = optarg;
2660                     cyls = strtol(p, (char **)&p, 0);
2661                     if (*p != ',')
2662                         goto chs_fail;
2663                     p++;
2664                     heads = strtol(p, (char **)&p, 0);
2665                     if (*p != ',')
2666                         goto chs_fail;
2667                     p++;
2668                     secs = strtol(p, (char **)&p, 0);
2669                     if (*p != '\0') {
2670                     chs_fail:
2671                         cyls = 0;
2672                     }
2673                 }
2674                 break;
2675             case QEMU_OPTION_nographic:
2676                 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
2677                 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
2678                 nographic = 1;
2679                 break;
2680             case QEMU_OPTION_kernel:
2681                 kernel_filename = optarg;
2682                 break;
2683             case QEMU_OPTION_append:
2684                 kernel_cmdline = optarg;
2685                 break;
2686             case QEMU_OPTION_tun_fd:
2687                 {
2688                     const char *p;
2689                     int fd;
2690                     net_if_type = NET_IF_TUN;
2691                     if (nb_tun_fds < MAX_NICS) {
2692                         fd = strtol(optarg, (char **)&p, 0);
2693                         if (*p != '\0') {
2694                             fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2695                             exit(1);
2696                         }
2697                         tun_fds[nb_tun_fds++] = fd;
2698                     }
2699                 }
2700                 break;
2701             case QEMU_OPTION_hdc:
2702                 hd_filename[2] = optarg;
2703                 has_cdrom = 0;
2704                 break;
2705             case QEMU_OPTION_hdd:
2706                 hd_filename[3] = optarg;
2707                 break;
2708             case QEMU_OPTION_cdrom:
2709                 hd_filename[2] = optarg;
2710                 has_cdrom = 1;
2711                 break;
2712             case QEMU_OPTION_boot:
2713                 boot_device = optarg[0];
2714                 if (boot_device != 'a' && boot_device != 'b' &&
2715                     boot_device != 'c' && boot_device != 'd') {
2716                     fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2717                     exit(1);
2718                 }
2719                 break;
2720             case QEMU_OPTION_fda:
2721                 fd_filename[0] = optarg;
2722                 break;
2723             case QEMU_OPTION_fdb:
2724                 fd_filename[1] = optarg;
2725                 break;
2726             case QEMU_OPTION_no_code_copy:
2727                 code_copy_enabled = 0;
2728                 break;
2729             case QEMU_OPTION_nics:
2730                 nb_nics = atoi(optarg);
2731                 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2732                     fprintf(stderr, "qemu: invalid number of network interfaces\n");
2733                     exit(1);
2734                 }
2735                 break;
2736             case QEMU_OPTION_macaddr:
2737                 {
2738                     const char *p;
2739                     int i;
2740                     p = optarg;
2741                     for(i = 0; i < 6; i++) {
2742                         macaddr[i] = strtol(p, (char **)&p, 16);
2743                         if (i == 5) {
2744                             if (*p != '\0') 
2745                                 goto macaddr_error;
2746                         } else {
2747                             if (*p != ':') {
2748                             macaddr_error:
2749                                 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2750                                 exit(1);
2751                             }
2752                             p++;
2753                         }
2754                     }
2755                 }
2756                 break;
2757 #ifdef CONFIG_SLIRP
2758             case QEMU_OPTION_tftp:
2759               {
2760                 extern const char *tftp_prefix;
2761                 tftp_prefix = optarg;
2762               }
2763               break;
2764             case QEMU_OPTION_user_net:
2765                 net_if_type = NET_IF_USER;
2766                 break;
2767 #endif
2768             case QEMU_OPTION_dummy_net:
2769                 net_if_type = NET_IF_DUMMY;
2770                 break;
2771             case QEMU_OPTION_enable_audio:
2772                 audio_enabled = 1;
2773                 break;
2774             case QEMU_OPTION_h:
2775                 help();
2776                 break;
2777             case QEMU_OPTION_m:
2778                 ram_size = atoi(optarg) * 1024 * 1024;
2779                 if (ram_size <= 0)
2780                     help();
2781                 if (ram_size > PHYS_RAM_MAX_SIZE) {
2782                     fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
2783                             PHYS_RAM_MAX_SIZE / (1024 * 1024));
2784                     exit(1);
2785                 }
2786                 break;
2787             case QEMU_OPTION_d:
2788                 {
2789                     int mask;
2790                     CPULogItem *item;
2791                     
2792                     mask = cpu_str_to_log_mask(optarg);
2793                     if (!mask) {
2794                         printf("Log items (comma separated):\n");
2795                     for(item = cpu_log_items; item->mask != 0; item++) {
2796                         printf("%-10s %s\n", item->name, item->help);
2797                     }
2798                     exit(1);
2799                     }
2800                     cpu_set_log(mask);
2801                 }
2802                 break;
2803             case QEMU_OPTION_n:
2804                 pstrcpy(network_script, sizeof(network_script), optarg);
2805                 break;
2806 #ifdef CONFIG_GDBSTUB
2807             case QEMU_OPTION_s:
2808                 use_gdbstub = 1;
2809                 break;
2810             case QEMU_OPTION_p:
2811                 gdbstub_port = atoi(optarg);
2812                 break;
2813 #endif
2814             case QEMU_OPTION_L:
2815                 bios_dir = optarg;
2816                 break;
2817             case QEMU_OPTION_S:
2818                 start_emulation = 0;
2819                 break;
2820             case QEMU_OPTION_pci:
2821                 pci_enabled = 1;
2822                 break;
2823             case QEMU_OPTION_isa:
2824                 pci_enabled = 0;
2825                 break;
2826             case QEMU_OPTION_prep:
2827                 prep_enabled = 1;
2828                 break;
2829             case QEMU_OPTION_localtime:
2830                 rtc_utc = 0;
2831                 break;
2832             case QEMU_OPTION_cirrusvga:
2833                 cirrus_vga_enabled = 1;
2834                 break;
2835             case QEMU_OPTION_std_vga:
2836                 cirrus_vga_enabled = 0;
2837                 break;
2838             case QEMU_OPTION_g:
2839                 {
2840                     const char *p;
2841                     int w, h, depth;
2842                     p = optarg;
2843                     w = strtol(p, (char **)&p, 10);
2844                     if (w <= 0) {
2845                     graphic_error:
2846                         fprintf(stderr, "qemu: invalid resolution or depth\n");
2847                         exit(1);
2848                     }
2849                     if (*p != 'x')
2850                         goto graphic_error;
2851                     p++;
2852                     h = strtol(p, (char **)&p, 10);
2853                     if (h <= 0)
2854                         goto graphic_error;
2855                     if (*p == 'x') {
2856                         p++;
2857                         depth = strtol(p, (char **)&p, 10);
2858                         if (depth != 8 && depth != 15 && depth != 16 && 
2859                             depth != 24 && depth != 32)
2860                             goto graphic_error;
2861                     } else if (*p == '\0') {
2862                         depth = graphic_depth;
2863                     } else {
2864                         goto graphic_error;
2865                     }
2866                     
2867                     graphic_width = w;
2868                     graphic_height = h;
2869                     graphic_depth = depth;
2870                 }
2871                 break;
2872             case QEMU_OPTION_monitor:
2873                 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
2874                 break;
2875             case QEMU_OPTION_serial:
2876                 if (serial_device_index >= MAX_SERIAL_PORTS) {
2877                     fprintf(stderr, "qemu: too many serial ports\n");
2878                     exit(1);
2879                 }
2880                 pstrcpy(serial_devices[serial_device_index], 
2881                         sizeof(serial_devices[0]), optarg);
2882                 serial_device_index++;
2883                 break;
2884             }
2885         }
2886     }
2887
2888     linux_boot = (kernel_filename != NULL);
2889         
2890     if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2891         fd_filename[0] == '\0')
2892         help();
2893     
2894     /* boot to cd by default if no hard disk */
2895     if (hd_filename[0] == '\0' && boot_device == 'c') {
2896         if (fd_filename[0] != '\0')
2897             boot_device = 'a';
2898         else
2899             boot_device = 'd';
2900     }
2901
2902 #if !defined(CONFIG_SOFTMMU)
2903     /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2904     {
2905         static uint8_t stdout_buf[4096];
2906         setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2907     }
2908 #else
2909     setvbuf(stdout, NULL, _IOLBF, 0);
2910 #endif
2911
2912     /* init host network redirectors */
2913     if (net_if_type == -1) {
2914         net_if_type = NET_IF_TUN;
2915 #if defined(CONFIG_SLIRP)
2916         if (access(network_script, R_OK) < 0) {
2917             net_if_type = NET_IF_USER;
2918         }
2919 #endif
2920     }
2921
2922     for(i = 0; i < nb_nics; i++) {
2923         NetDriverState *nd = &nd_table[i];
2924         nd->index = i;
2925         /* init virtual mac address */
2926         nd->macaddr[0] = macaddr[0];
2927         nd->macaddr[1] = macaddr[1];
2928         nd->macaddr[2] = macaddr[2];
2929         nd->macaddr[3] = macaddr[3];
2930         nd->macaddr[4] = macaddr[4];
2931         nd->macaddr[5] = macaddr[5] + i;
2932         switch(net_if_type) {
2933 #if defined(CONFIG_SLIRP)
2934         case NET_IF_USER:
2935             net_slirp_init(nd);
2936             break;
2937 #endif
2938 #if !defined(_WIN32)
2939         case NET_IF_TUN:
2940             if (i < nb_tun_fds) {
2941                 net_fd_init(nd, tun_fds[i]);
2942             } else {
2943                 if (net_tun_init(nd) < 0)
2944                     net_dummy_init(nd);
2945             }
2946             break;
2947 #endif
2948         case NET_IF_DUMMY:
2949         default:
2950             net_dummy_init(nd);
2951             break;
2952         }
2953     }
2954
2955     /* init the memory */
2956     phys_ram_size = ram_size + vga_ram_size + bios_size;
2957
2958 #ifdef CONFIG_SOFTMMU
2959 #ifdef _BSD
2960     /* mallocs are always aligned on BSD. valloc is better for correctness */
2961     phys_ram_base = valloc(phys_ram_size);
2962 #else
2963     phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
2964 #endif
2965     if (!phys_ram_base) {
2966         fprintf(stderr, "Could not allocate physical memory\n");
2967         exit(1);
2968     }
2969 #else
2970     /* as we must map the same page at several addresses, we must use
2971        a fd */
2972     {
2973         const char *tmpdir;
2974
2975         tmpdir = getenv("QEMU_TMPDIR");
2976         if (!tmpdir)
2977             tmpdir = "/tmp";
2978         snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
2979         if (mkstemp(phys_ram_file) < 0) {
2980             fprintf(stderr, "Could not create temporary memory file '%s'\n", 
2981                     phys_ram_file);
2982             exit(1);
2983         }
2984         phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
2985         if (phys_ram_fd < 0) {
2986             fprintf(stderr, "Could not open temporary memory file '%s'\n", 
2987                     phys_ram_file);
2988             exit(1);
2989         }
2990         ftruncate(phys_ram_fd, phys_ram_size);
2991         unlink(phys_ram_file);
2992         phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
2993                              phys_ram_size, 
2994                              PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
2995                              phys_ram_fd, 0);
2996         if (phys_ram_base == MAP_FAILED) {
2997             fprintf(stderr, "Could not map physical memory\n");
2998             exit(1);
2999         }
3000     }
3001 #endif
3002
3003     /* we always create the cdrom drive, even if no disk is there */
3004     bdrv_init();
3005     if (has_cdrom) {
3006         bs_table[2] = bdrv_new("cdrom");
3007         bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
3008     }
3009
3010     /* open the virtual block devices */
3011     for(i = 0; i < MAX_DISKS; i++) {
3012         if (hd_filename[i]) {
3013             if (!bs_table[i]) {
3014                 char buf[64];
3015                 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3016                 bs_table[i] = bdrv_new(buf);
3017             }
3018             if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3019                 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3020                         hd_filename[i]);
3021                 exit(1);
3022             }
3023             if (i == 0 && cyls != 0) 
3024                 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3025         }
3026     }
3027
3028     /* we always create at least one floppy disk */
3029     fd_table[0] = bdrv_new("fda");
3030     bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3031
3032     for(i = 0; i < MAX_FD; i++) {
3033         if (fd_filename[i]) {
3034             if (!fd_table[i]) {
3035                 char buf[64];
3036                 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3037                 fd_table[i] = bdrv_new(buf);
3038                 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3039             }
3040             if (fd_filename[i] != '\0') {
3041                 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3042                     fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3043                             fd_filename[i]);
3044                     exit(1);
3045                 }
3046             }
3047         }
3048     }
3049
3050     /* init CPU state */
3051     env = cpu_init();
3052     global_env = env;
3053     cpu_single_env = env;
3054
3055     register_savevm("timer", 0, 1, timer_save, timer_load, env);
3056     register_savevm("cpu", 0, 2, cpu_save, cpu_load, env);
3057     register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
3058     qemu_register_reset(main_cpu_reset, global_env);
3059
3060     init_ioports();
3061     cpu_calibrate_ticks();
3062
3063     /* terminal init */
3064     if (nographic) {
3065         dumb_display_init(ds);
3066     } else {
3067 #ifdef CONFIG_SDL
3068         sdl_display_init(ds);
3069 #else
3070         dumb_display_init(ds);
3071 #endif
3072     }
3073
3074     vga_console = graphic_console_init(ds);
3075     
3076     monitor_hd = qemu_chr_open(monitor_device);
3077     if (!monitor_hd) {
3078         fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3079         exit(1);
3080     }
3081     monitor_init(monitor_hd, !nographic);
3082
3083     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3084         if (serial_devices[i][0] != '\0') {
3085             serial_hds[i] = qemu_chr_open(serial_devices[i]);
3086             if (!serial_hds[i]) {
3087                 fprintf(stderr, "qemu: could not open serial device '%s'\n", 
3088                         serial_devices[i]);
3089                 exit(1);
3090             }
3091             if (!strcmp(serial_devices[i], "vc"))
3092                 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3093         }
3094     }
3095
3096     /* setup cpu signal handlers for MMU / self modifying code handling */
3097 #if !defined(CONFIG_SOFTMMU)
3098     
3099 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3100     {
3101         stack_t stk;
3102         signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3103         stk.ss_sp = signal_stack;
3104         stk.ss_size = SIGNAL_STACK_SIZE;
3105         stk.ss_flags = 0;
3106
3107         if (sigaltstack(&stk, NULL) < 0) {
3108             perror("sigaltstack");
3109             exit(1);
3110         }
3111     }
3112 #endif
3113     {
3114         struct sigaction act;
3115         
3116         sigfillset(&act.sa_mask);
3117         act.sa_flags = SA_SIGINFO;
3118 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3119         act.sa_flags |= SA_ONSTACK;
3120 #endif
3121         act.sa_sigaction = host_segv_handler;
3122         sigaction(SIGSEGV, &act, NULL);
3123         sigaction(SIGBUS, &act, NULL);
3124 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3125         sigaction(SIGFPE, &act, NULL);
3126 #endif
3127     }
3128 #endif
3129
3130 #ifndef _WIN32
3131     {
3132         struct sigaction act;
3133         sigfillset(&act.sa_mask);
3134         act.sa_flags = 0;
3135         act.sa_handler = SIG_IGN;
3136         sigaction(SIGPIPE, &act, NULL);
3137     }
3138 #endif
3139     init_timers();
3140
3141 #if defined(TARGET_I386)
3142     pc_init(ram_size, vga_ram_size, boot_device,
3143             ds, fd_filename, snapshot,
3144             kernel_filename, kernel_cmdline, initrd_filename);
3145 #elif defined(TARGET_PPC)
3146     ppc_init(ram_size, vga_ram_size, boot_device,
3147              ds, fd_filename, snapshot,
3148              kernel_filename, kernel_cmdline, initrd_filename);
3149 #endif
3150
3151     gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3152     qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3153
3154 #ifdef CONFIG_GDBSTUB
3155     if (use_gdbstub) {
3156         if (gdbserver_start(gdbstub_port) < 0) {
3157             fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
3158                     gdbstub_port);
3159             exit(1);
3160         } else {
3161             printf("Waiting gdb connection on port %d\n", gdbstub_port);
3162         }
3163     } else 
3164 #endif
3165     {
3166         /* XXX: simplify init */
3167         read_passwords();
3168         if (start_emulation) {
3169             vm_start();
3170         }
3171     }
3172     main_loop();
3173     quit_timers();
3174     return 0;
3175 }