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