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