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