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