78f968eb17ac53d4c0b2bc2dcf7f79784f1921c8
[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 #include <netinet/in.h>
42 #include <dirent.h>
43 #ifdef _BSD
44 #include <sys/stat.h>
45 #ifndef __APPLE__
46 #include <libutil.h>
47 #endif
48 #else
49 #include <linux/if.h>
50 #include <linux/if_tun.h>
51 #include <pty.h>
52 #include <malloc.h>
53 #include <linux/rtc.h>
54 #endif
55 #endif
56
57 #if defined(CONFIG_SLIRP)
58 #include "libslirp.h"
59 #endif
60
61 #ifdef _WIN32
62 #include <malloc.h>
63 #include <sys/timeb.h>
64 #include <windows.h>
65 #define getopt_long_only getopt_long
66 #define memalign(align, size) malloc(size)
67 #endif
68
69 #ifdef CONFIG_SDL
70 #ifdef __APPLE__
71 #include <SDL/SDL.h>
72 #endif
73 #endif /* CONFIG_SDL */
74
75 #include "disas.h"
76
77 #include "exec-all.h"
78
79 //#define DO_TB_FLUSH
80
81 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
82
83 //#define DEBUG_UNUSED_IOPORT
84 //#define DEBUG_IOPORT
85
86 #if !defined(CONFIG_SOFTMMU)
87 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
88 #else
89 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
90 #endif
91
92 #ifdef TARGET_PPC
93 #define DEFAULT_RAM_SIZE 144
94 #else
95 #define DEFAULT_RAM_SIZE 128
96 #endif
97 /* in ms */
98 #define GUI_REFRESH_INTERVAL 30
99
100 /* XXX: use a two level table to limit memory usage */
101 #define MAX_IOPORTS 65536
102
103 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
104 char phys_ram_file[1024];
105 CPUState *global_env;
106 CPUState *cpu_single_env;
107 void *ioport_opaque[MAX_IOPORTS];
108 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
109 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
110 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
111 int vga_ram_size;
112 int bios_size;
113 static DisplayState display_state;
114 int nographic;
115 const char* keyboard_layout = NULL;
116 int64_t ticks_per_sec;
117 int boot_device = 'c';
118 int ram_size;
119 static char network_script[1024];
120 int pit_min_timer_count = 0;
121 int nb_nics;
122 NetDriverState nd_table[MAX_NICS];
123 QEMUTimer *gui_timer;
124 int vm_running;
125 int audio_enabled = 0;
126 int sb16_enabled = 1;
127 int adlib_enabled = 1;
128 int gus_enabled = 1;
129 int pci_enabled = 1;
130 int prep_enabled = 0;
131 int rtc_utc = 1;
132 int cirrus_vga_enabled = 1;
133 int graphic_width = 800;
134 int graphic_height = 600;
135 int graphic_depth = 15;
136 int full_screen = 0;
137 TextConsole *vga_console;
138 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
139
140 /***********************************************************/
141 /* x86 ISA bus support */
142
143 target_phys_addr_t isa_mem_base = 0;
144
145 uint32_t default_ioport_readb(void *opaque, uint32_t address)
146 {
147 #ifdef DEBUG_UNUSED_IOPORT
148     fprintf(stderr, "inb: port=0x%04x\n", address);
149 #endif
150     return 0xff;
151 }
152
153 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
154 {
155 #ifdef DEBUG_UNUSED_IOPORT
156     fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
157 #endif
158 }
159
160 /* default is to make two byte accesses */
161 uint32_t default_ioport_readw(void *opaque, uint32_t address)
162 {
163     uint32_t data;
164     data = ioport_read_table[0][address](ioport_opaque[address], address);
165     address = (address + 1) & (MAX_IOPORTS - 1);
166     data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
167     return data;
168 }
169
170 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
171 {
172     ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
173     address = (address + 1) & (MAX_IOPORTS - 1);
174     ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
175 }
176
177 uint32_t default_ioport_readl(void *opaque, uint32_t address)
178 {
179 #ifdef DEBUG_UNUSED_IOPORT
180     fprintf(stderr, "inl: port=0x%04x\n", address);
181 #endif
182     return 0xffffffff;
183 }
184
185 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
186 {
187 #ifdef DEBUG_UNUSED_IOPORT
188     fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
189 #endif
190 }
191
192 void init_ioports(void)
193 {
194     int i;
195
196     for(i = 0; i < MAX_IOPORTS; i++) {
197         ioport_read_table[0][i] = default_ioport_readb;
198         ioport_write_table[0][i] = default_ioport_writeb;
199         ioport_read_table[1][i] = default_ioport_readw;
200         ioport_write_table[1][i] = default_ioport_writew;
201         ioport_read_table[2][i] = default_ioport_readl;
202         ioport_write_table[2][i] = default_ioport_writel;
203     }
204 }
205
206 /* size is the word size in byte */
207 int register_ioport_read(int start, int length, int size, 
208                          IOPortReadFunc *func, void *opaque)
209 {
210     int i, bsize;
211
212     if (size == 1) {
213         bsize = 0;
214     } else if (size == 2) {
215         bsize = 1;
216     } else if (size == 4) {
217         bsize = 2;
218     } else {
219         hw_error("register_ioport_read: invalid size");
220         return -1;
221     }
222     for(i = start; i < start + length; i += size) {
223         ioport_read_table[bsize][i] = func;
224         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
225             hw_error("register_ioport_read: invalid opaque");
226         ioport_opaque[i] = opaque;
227     }
228     return 0;
229 }
230
231 /* size is the word size in byte */
232 int register_ioport_write(int start, int length, int size, 
233                           IOPortWriteFunc *func, void *opaque)
234 {
235     int i, bsize;
236
237     if (size == 1) {
238         bsize = 0;
239     } else if (size == 2) {
240         bsize = 1;
241     } else if (size == 4) {
242         bsize = 2;
243     } else {
244         hw_error("register_ioport_write: invalid size");
245         return -1;
246     }
247     for(i = start; i < start + length; i += size) {
248         ioport_write_table[bsize][i] = func;
249         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
250             hw_error("register_ioport_read: invalid opaque");
251         ioport_opaque[i] = opaque;
252     }
253     return 0;
254 }
255
256 void isa_unassign_ioport(int start, int length)
257 {
258     int i;
259
260     for(i = start; i < start + length; i++) {
261         ioport_read_table[0][i] = default_ioport_readb;
262         ioport_read_table[1][i] = default_ioport_readw;
263         ioport_read_table[2][i] = default_ioport_readl;
264
265         ioport_write_table[0][i] = default_ioport_writeb;
266         ioport_write_table[1][i] = default_ioport_writew;
267         ioport_write_table[2][i] = default_ioport_writel;
268     }
269 }
270
271 void pstrcpy(char *buf, int buf_size, const char *str)
272 {
273     int c;
274     char *q = buf;
275
276     if (buf_size <= 0)
277         return;
278
279     for(;;) {
280         c = *str++;
281         if (c == 0 || q >= buf + buf_size - 1)
282             break;
283         *q++ = c;
284     }
285     *q = '\0';
286 }
287
288 /* strcat and truncate. */
289 char *pstrcat(char *buf, int buf_size, const char *s)
290 {
291     int len;
292     len = strlen(buf);
293     if (len < buf_size) 
294         pstrcpy(buf + len, buf_size - len, s);
295     return buf;
296 }
297
298 int strstart(const char *str, const char *val, const char **ptr)
299 {
300     const char *p, *q;
301     p = str;
302     q = val;
303     while (*q != '\0') {
304         if (*p != *q)
305             return 0;
306         p++;
307         q++;
308     }
309     if (ptr)
310         *ptr = p;
311     return 1;
312 }
313
314 /* return the size or -1 if error */
315 int get_image_size(const char *filename)
316 {
317     int fd, size;
318     fd = open(filename, O_RDONLY | O_BINARY);
319     if (fd < 0)
320         return -1;
321     size = lseek(fd, 0, SEEK_END);
322     close(fd);
323     return size;
324 }
325
326 /* return the size or -1 if error */
327 int load_image(const char *filename, uint8_t *addr)
328 {
329     int fd, size;
330     fd = open(filename, O_RDONLY | O_BINARY);
331     if (fd < 0)
332         return -1;
333     size = lseek(fd, 0, SEEK_END);
334     lseek(fd, 0, SEEK_SET);
335     if (read(fd, addr, size) != size) {
336         close(fd);
337         return -1;
338     }
339     close(fd);
340     return size;
341 }
342
343 void cpu_outb(CPUState *env, int addr, int val)
344 {
345 #ifdef DEBUG_IOPORT
346     if (loglevel & CPU_LOG_IOPORT)
347         fprintf(logfile, "outb: %04x %02x\n", addr, val);
348 #endif    
349     ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
350 }
351
352 void cpu_outw(CPUState *env, int addr, int val)
353 {
354 #ifdef DEBUG_IOPORT
355     if (loglevel & CPU_LOG_IOPORT)
356         fprintf(logfile, "outw: %04x %04x\n", addr, val);
357 #endif    
358     ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
359 }
360
361 void cpu_outl(CPUState *env, int addr, int val)
362 {
363 #ifdef DEBUG_IOPORT
364     if (loglevel & CPU_LOG_IOPORT)
365         fprintf(logfile, "outl: %04x %08x\n", addr, val);
366 #endif
367     ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
368 }
369
370 int cpu_inb(CPUState *env, int addr)
371 {
372     int val;
373     val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
374 #ifdef DEBUG_IOPORT
375     if (loglevel & CPU_LOG_IOPORT)
376         fprintf(logfile, "inb : %04x %02x\n", addr, val);
377 #endif
378     return val;
379 }
380
381 int cpu_inw(CPUState *env, int addr)
382 {
383     int val;
384     val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
385 #ifdef DEBUG_IOPORT
386     if (loglevel & CPU_LOG_IOPORT)
387         fprintf(logfile, "inw : %04x %04x\n", addr, val);
388 #endif
389     return val;
390 }
391
392 int cpu_inl(CPUState *env, int addr)
393 {
394     int val;
395     val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
396 #ifdef DEBUG_IOPORT
397     if (loglevel & CPU_LOG_IOPORT)
398         fprintf(logfile, "inl : %04x %08x\n", addr, val);
399 #endif
400     return val;
401 }
402
403 /***********************************************************/
404 void hw_error(const char *fmt, ...)
405 {
406     va_list ap;
407
408     va_start(ap, fmt);
409     fprintf(stderr, "qemu: hardware error: ");
410     vfprintf(stderr, fmt, ap);
411     fprintf(stderr, "\n");
412 #ifdef TARGET_I386
413     cpu_dump_state(global_env, stderr, fprintf, X86_DUMP_FPU | X86_DUMP_CCOP);
414 #else
415     cpu_dump_state(global_env, stderr, fprintf, 0);
416 #endif
417     va_end(ap);
418     abort();
419 }
420
421 /***********************************************************/
422 /* keyboard/mouse */
423
424 static QEMUPutKBDEvent *qemu_put_kbd_event;
425 static void *qemu_put_kbd_event_opaque;
426 static QEMUPutMouseEvent *qemu_put_mouse_event;
427 static void *qemu_put_mouse_event_opaque;
428
429 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
430 {
431     qemu_put_kbd_event_opaque = opaque;
432     qemu_put_kbd_event = func;
433 }
434
435 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
436 {
437     qemu_put_mouse_event_opaque = opaque;
438     qemu_put_mouse_event = func;
439 }
440
441 void kbd_put_keycode(int keycode)
442 {
443     if (qemu_put_kbd_event) {
444         qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
445     }
446 }
447
448 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
449 {
450     if (qemu_put_mouse_event) {
451         qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
452                              dx, dy, dz, buttons_state);
453     }
454 }
455
456 /***********************************************************/
457 /* timers */
458
459 #if defined(__powerpc__)
460
461 static inline uint32_t get_tbl(void) 
462 {
463     uint32_t tbl;
464     asm volatile("mftb %0" : "=r" (tbl));
465     return tbl;
466 }
467
468 static inline uint32_t get_tbu(void) 
469 {
470         uint32_t tbl;
471         asm volatile("mftbu %0" : "=r" (tbl));
472         return tbl;
473 }
474
475 int64_t cpu_get_real_ticks(void)
476 {
477     uint32_t l, h, h1;
478     /* NOTE: we test if wrapping has occurred */
479     do {
480         h = get_tbu();
481         l = get_tbl();
482         h1 = get_tbu();
483     } while (h != h1);
484     return ((int64_t)h << 32) | l;
485 }
486
487 #elif defined(__i386__)
488
489 int64_t cpu_get_real_ticks(void)
490 {
491     int64_t val;
492     asm volatile ("rdtsc" : "=A" (val));
493     return val;
494 }
495
496 #elif defined(__x86_64__)
497
498 int64_t cpu_get_real_ticks(void)
499 {
500     uint32_t low,high;
501     int64_t val;
502     asm volatile("rdtsc" : "=a" (low), "=d" (high));
503     val = high;
504     val <<= 32;
505     val |= low;
506     return val;
507 }
508
509 #else
510 #error unsupported CPU
511 #endif
512
513 static int64_t cpu_ticks_offset;
514 static int cpu_ticks_enabled;
515
516 static inline int64_t cpu_get_ticks(void)
517 {
518     if (!cpu_ticks_enabled) {
519         return cpu_ticks_offset;
520     } else {
521         return cpu_get_real_ticks() + cpu_ticks_offset;
522     }
523 }
524
525 /* enable cpu_get_ticks() */
526 void cpu_enable_ticks(void)
527 {
528     if (!cpu_ticks_enabled) {
529         cpu_ticks_offset -= cpu_get_real_ticks();
530         cpu_ticks_enabled = 1;
531     }
532 }
533
534 /* disable cpu_get_ticks() : the clock is stopped. You must not call
535    cpu_get_ticks() after that.  */
536 void cpu_disable_ticks(void)
537 {
538     if (cpu_ticks_enabled) {
539         cpu_ticks_offset = cpu_get_ticks();
540         cpu_ticks_enabled = 0;
541     }
542 }
543
544 static int64_t get_clock(void)
545 {
546 #ifdef _WIN32
547     struct _timeb tb;
548     _ftime(&tb);
549     return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
550 #else
551     struct timeval tv;
552     gettimeofday(&tv, NULL);
553     return tv.tv_sec * 1000000LL + tv.tv_usec;
554 #endif
555 }
556
557 void cpu_calibrate_ticks(void)
558 {
559     int64_t usec, ticks;
560
561     usec = get_clock();
562     ticks = cpu_get_real_ticks();
563 #ifdef _WIN32
564     Sleep(50);
565 #else
566     usleep(50 * 1000);
567 #endif
568     usec = get_clock() - usec;
569     ticks = cpu_get_real_ticks() - ticks;
570     ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
571 }
572
573 /* compute with 96 bit intermediate result: (a*b)/c */
574 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
575 {
576     union {
577         uint64_t ll;
578         struct {
579 #ifdef WORDS_BIGENDIAN
580             uint32_t high, low;
581 #else
582             uint32_t low, high;
583 #endif            
584         } l;
585     } u, res;
586     uint64_t rl, rh;
587
588     u.ll = a;
589     rl = (uint64_t)u.l.low * (uint64_t)b;
590     rh = (uint64_t)u.l.high * (uint64_t)b;
591     rh += (rl >> 32);
592     res.l.high = rh / c;
593     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
594     return res.ll;
595 }
596
597 #define QEMU_TIMER_REALTIME 0
598 #define QEMU_TIMER_VIRTUAL  1
599
600 struct QEMUClock {
601     int type;
602     /* XXX: add frequency */
603 };
604
605 struct QEMUTimer {
606     QEMUClock *clock;
607     int64_t expire_time;
608     QEMUTimerCB *cb;
609     void *opaque;
610     struct QEMUTimer *next;
611 };
612
613 QEMUClock *rt_clock;
614 QEMUClock *vm_clock;
615
616 static QEMUTimer *active_timers[2];
617 #ifdef _WIN32
618 static MMRESULT timerID;
619 #else
620 /* frequency of the times() clock tick */
621 static int timer_freq;
622 #endif
623
624 QEMUClock *qemu_new_clock(int type)
625 {
626     QEMUClock *clock;
627     clock = qemu_mallocz(sizeof(QEMUClock));
628     if (!clock)
629         return NULL;
630     clock->type = type;
631     return clock;
632 }
633
634 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
635 {
636     QEMUTimer *ts;
637
638     ts = qemu_mallocz(sizeof(QEMUTimer));
639     ts->clock = clock;
640     ts->cb = cb;
641     ts->opaque = opaque;
642     return ts;
643 }
644
645 void qemu_free_timer(QEMUTimer *ts)
646 {
647     qemu_free(ts);
648 }
649
650 /* stop a timer, but do not dealloc it */
651 void qemu_del_timer(QEMUTimer *ts)
652 {
653     QEMUTimer **pt, *t;
654
655     /* NOTE: this code must be signal safe because
656        qemu_timer_expired() can be called from a signal. */
657     pt = &active_timers[ts->clock->type];
658     for(;;) {
659         t = *pt;
660         if (!t)
661             break;
662         if (t == ts) {
663             *pt = t->next;
664             break;
665         }
666         pt = &t->next;
667     }
668 }
669
670 /* modify the current timer so that it will be fired when current_time
671    >= expire_time. The corresponding callback will be called. */
672 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
673 {
674     QEMUTimer **pt, *t;
675
676     qemu_del_timer(ts);
677
678     /* add the timer in the sorted list */
679     /* NOTE: this code must be signal safe because
680        qemu_timer_expired() can be called from a signal. */
681     pt = &active_timers[ts->clock->type];
682     for(;;) {
683         t = *pt;
684         if (!t)
685             break;
686         if (t->expire_time > expire_time) 
687             break;
688         pt = &t->next;
689     }
690     ts->expire_time = expire_time;
691     ts->next = *pt;
692     *pt = ts;
693 }
694
695 int qemu_timer_pending(QEMUTimer *ts)
696 {
697     QEMUTimer *t;
698     for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
699         if (t == ts)
700             return 1;
701     }
702     return 0;
703 }
704
705 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
706 {
707     if (!timer_head)
708         return 0;
709     return (timer_head->expire_time <= current_time);
710 }
711
712 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
713 {
714     QEMUTimer *ts;
715     
716     for(;;) {
717         ts = *ptimer_head;
718         if (!ts || ts->expire_time > current_time)
719             break;
720         /* remove timer from the list before calling the callback */
721         *ptimer_head = ts->next;
722         ts->next = NULL;
723         
724         /* run the callback (the timer list can be modified) */
725         ts->cb(ts->opaque);
726     }
727 }
728
729 int64_t qemu_get_clock(QEMUClock *clock)
730 {
731     switch(clock->type) {
732     case QEMU_TIMER_REALTIME:
733 #ifdef _WIN32
734         return GetTickCount();
735 #else
736         {
737             struct tms tp;
738
739             /* Note that using gettimeofday() is not a good solution
740                for timers because its value change when the date is
741                modified. */
742             if (timer_freq == 100) {
743                 return times(&tp) * 10;
744             } else {
745                 return ((int64_t)times(&tp) * 1000) / timer_freq;
746             }
747         }
748 #endif
749     default:
750     case QEMU_TIMER_VIRTUAL:
751         return cpu_get_ticks();
752     }
753 }
754
755 /* save a timer */
756 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
757 {
758     uint64_t expire_time;
759
760     if (qemu_timer_pending(ts)) {
761         expire_time = ts->expire_time;
762     } else {
763         expire_time = -1;
764     }
765     qemu_put_be64(f, expire_time);
766 }
767
768 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
769 {
770     uint64_t expire_time;
771
772     expire_time = qemu_get_be64(f);
773     if (expire_time != -1) {
774         qemu_mod_timer(ts, expire_time);
775     } else {
776         qemu_del_timer(ts);
777     }
778 }
779
780 static void timer_save(QEMUFile *f, void *opaque)
781 {
782     if (cpu_ticks_enabled) {
783         hw_error("cannot save state if virtual timers are running");
784     }
785     qemu_put_be64s(f, &cpu_ticks_offset);
786     qemu_put_be64s(f, &ticks_per_sec);
787 }
788
789 static int timer_load(QEMUFile *f, void *opaque, int version_id)
790 {
791     if (version_id != 1)
792         return -EINVAL;
793     if (cpu_ticks_enabled) {
794         return -EINVAL;
795     }
796     qemu_get_be64s(f, &cpu_ticks_offset);
797     qemu_get_be64s(f, &ticks_per_sec);
798     return 0;
799 }
800
801 #ifdef _WIN32
802 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
803                                  DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
804 #else
805 static void host_alarm_handler(int host_signum)
806 #endif
807 {
808 #if 0
809 #define DISP_FREQ 1000
810     {
811         static int64_t delta_min = INT64_MAX;
812         static int64_t delta_max, delta_cum, last_clock, delta, ti;
813         static int count;
814         ti = qemu_get_clock(vm_clock);
815         if (last_clock != 0) {
816             delta = ti - last_clock;
817             if (delta < delta_min)
818                 delta_min = delta;
819             if (delta > delta_max)
820                 delta_max = delta;
821             delta_cum += delta;
822             if (++count == DISP_FREQ) {
823                 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
824                        muldiv64(delta_min, 1000000, ticks_per_sec),
825                        muldiv64(delta_max, 1000000, ticks_per_sec),
826                        muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
827                        (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
828                 count = 0;
829                 delta_min = INT64_MAX;
830                 delta_max = 0;
831                 delta_cum = 0;
832             }
833         }
834         last_clock = ti;
835     }
836 #endif
837     if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
838                            qemu_get_clock(vm_clock)) ||
839         qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
840                            qemu_get_clock(rt_clock))) {
841         /* stop the cpu because a timer occured */
842         cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
843     }
844 }
845
846 #ifndef _WIN32
847
848 #if defined(__linux__)
849
850 #define RTC_FREQ 1024
851
852 static int rtc_fd;
853
854 static int start_rtc_timer(void)
855 {
856     rtc_fd = open("/dev/rtc", O_RDONLY);
857     if (rtc_fd < 0)
858         return -1;
859     if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
860         fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
861                 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
862                 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
863         goto fail;
864     }
865     if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
866     fail:
867         close(rtc_fd);
868         return -1;
869     }
870     pit_min_timer_count = PIT_FREQ / RTC_FREQ;
871     return 0;
872 }
873
874 #else
875
876 static int start_rtc_timer(void)
877 {
878     return -1;
879 }
880
881 #endif /* !defined(__linux__) */
882
883 #endif /* !defined(_WIN32) */
884
885 static void init_timers(void)
886 {
887     rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
888     vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
889
890 #ifdef _WIN32
891     {
892         int count=0;
893         timerID = timeSetEvent(10,    // interval (ms)
894                                0,     // resolution
895                                host_alarm_handler, // function
896                                (DWORD)&count,  // user parameter
897                                TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
898         if( !timerID ) {
899             perror("failed timer alarm");
900             exit(1);
901         }
902     }
903     pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
904 #else
905     {
906         struct sigaction act;
907         struct itimerval itv;
908         
909         /* get times() syscall frequency */
910         timer_freq = sysconf(_SC_CLK_TCK);
911         
912         /* timer signal */
913         sigfillset(&act.sa_mask);
914         act.sa_flags = 0;
915 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
916         act.sa_flags |= SA_ONSTACK;
917 #endif
918         act.sa_handler = host_alarm_handler;
919         sigaction(SIGALRM, &act, NULL);
920
921         itv.it_interval.tv_sec = 0;
922         itv.it_interval.tv_usec = 1000;
923         itv.it_value.tv_sec = 0;
924         itv.it_value.tv_usec = 10 * 1000;
925         setitimer(ITIMER_REAL, &itv, NULL);
926         /* we probe the tick duration of the kernel to inform the user if
927            the emulated kernel requested a too high timer frequency */
928         getitimer(ITIMER_REAL, &itv);
929
930 #if defined(__linux__)
931         if (itv.it_interval.tv_usec > 1000) {
932             /* try to use /dev/rtc to have a faster timer */
933             if (start_rtc_timer() < 0)
934                 goto use_itimer;
935             /* disable itimer */
936             itv.it_interval.tv_sec = 0;
937             itv.it_interval.tv_usec = 0;
938             itv.it_value.tv_sec = 0;
939             itv.it_value.tv_usec = 0;
940             setitimer(ITIMER_REAL, &itv, NULL);
941
942             /* use the RTC */
943             sigaction(SIGIO, &act, NULL);
944             fcntl(rtc_fd, F_SETFL, O_ASYNC);
945             fcntl(rtc_fd, F_SETOWN, getpid());
946         } else 
947 #endif /* defined(__linux__) */
948         {
949         use_itimer:
950             pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
951                                    PIT_FREQ) / 1000000;
952         }
953     }
954 #endif
955 }
956
957 void quit_timers(void)
958 {
959 #ifdef _WIN32
960     timeKillEvent(timerID);
961 #endif
962 }
963
964 /***********************************************************/
965 /* character device */
966
967 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
968 {
969     return s->chr_write(s, buf, len);
970 }
971
972 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
973 {
974     char buf[4096];
975     va_list ap;
976     va_start(ap, fmt);
977     vsnprintf(buf, sizeof(buf), fmt, ap);
978     qemu_chr_write(s, buf, strlen(buf));
979     va_end(ap);
980 }
981
982 void qemu_chr_send_event(CharDriverState *s, int event)
983 {
984     if (s->chr_send_event)
985         s->chr_send_event(s, event);
986 }
987
988 void qemu_chr_add_read_handler(CharDriverState *s, 
989                                IOCanRWHandler *fd_can_read, 
990                                IOReadHandler *fd_read, void *opaque)
991 {
992     s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
993 }
994              
995 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
996 {
997     s->chr_event = chr_event;
998 }
999
1000 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1001 {
1002     return len;
1003 }
1004
1005 static void null_chr_add_read_handler(CharDriverState *chr, 
1006                                     IOCanRWHandler *fd_can_read, 
1007                                     IOReadHandler *fd_read, void *opaque)
1008 {
1009 }
1010
1011 CharDriverState *qemu_chr_open_null(void)
1012 {
1013     CharDriverState *chr;
1014
1015     chr = qemu_mallocz(sizeof(CharDriverState));
1016     if (!chr)
1017         return NULL;
1018     chr->chr_write = null_chr_write;
1019     chr->chr_add_read_handler = null_chr_add_read_handler;
1020     return chr;
1021 }
1022
1023 #ifndef _WIN32
1024
1025 typedef struct {
1026     int fd_in, fd_out;
1027     /* for nographic stdio only */
1028     IOCanRWHandler *fd_can_read; 
1029     IOReadHandler *fd_read;
1030     void *fd_opaque;
1031 } FDCharDriver;
1032
1033 #define STDIO_MAX_CLIENTS 2
1034
1035 static int stdio_nb_clients;
1036 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1037
1038 static int unix_write(int fd, const uint8_t *buf, int len1)
1039 {
1040     int ret, len;
1041
1042     len = len1;
1043     while (len > 0) {
1044         ret = write(fd, buf, len);
1045         if (ret < 0) {
1046             if (errno != EINTR && errno != EAGAIN)
1047                 return -1;
1048         } else if (ret == 0) {
1049             break;
1050         } else {
1051             buf += ret;
1052             len -= ret;
1053         }
1054     }
1055     return len1 - len;
1056 }
1057
1058 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1059 {
1060     FDCharDriver *s = chr->opaque;
1061     return unix_write(s->fd_out, buf, len);
1062 }
1063
1064 static void fd_chr_add_read_handler(CharDriverState *chr, 
1065                                     IOCanRWHandler *fd_can_read, 
1066                                     IOReadHandler *fd_read, void *opaque)
1067 {
1068     FDCharDriver *s = chr->opaque;
1069
1070     if (nographic && s->fd_in == 0) {
1071         s->fd_can_read = fd_can_read;
1072         s->fd_read = fd_read;
1073         s->fd_opaque = opaque;
1074     } else {
1075         qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
1076     }
1077 }
1078
1079 /* open a character device to a unix fd */
1080 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1081 {
1082     CharDriverState *chr;
1083     FDCharDriver *s;
1084
1085     chr = qemu_mallocz(sizeof(CharDriverState));
1086     if (!chr)
1087         return NULL;
1088     s = qemu_mallocz(sizeof(FDCharDriver));
1089     if (!s) {
1090         free(chr);
1091         return NULL;
1092     }
1093     s->fd_in = fd_in;
1094     s->fd_out = fd_out;
1095     chr->opaque = s;
1096     chr->chr_write = fd_chr_write;
1097     chr->chr_add_read_handler = fd_chr_add_read_handler;
1098     return chr;
1099 }
1100
1101 /* for STDIO, we handle the case where several clients use it
1102    (nographic mode) */
1103
1104 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1105
1106 static int term_got_escape, client_index;
1107
1108 void term_print_help(void)
1109 {
1110     printf("\n"
1111            "C-a h    print this help\n"
1112            "C-a x    exit emulator\n"
1113            "C-a s    save disk data back to file (if -snapshot)\n"
1114            "C-a b    send break (magic sysrq)\n"
1115            "C-a c    switch between console and monitor\n"
1116            "C-a C-a  send C-a\n"
1117            );
1118 }
1119
1120 /* called when a char is received */
1121 static void stdio_received_byte(int ch)
1122 {
1123     if (term_got_escape) {
1124         term_got_escape = 0;
1125         switch(ch) {
1126         case 'h':
1127             term_print_help();
1128             break;
1129         case 'x':
1130             exit(0);
1131             break;
1132         case 's': 
1133             {
1134                 int i;
1135                 for (i = 0; i < MAX_DISKS; i++) {
1136                     if (bs_table[i])
1137                         bdrv_commit(bs_table[i]);
1138                 }
1139             }
1140             break;
1141         case 'b':
1142             if (client_index < stdio_nb_clients) {
1143                 CharDriverState *chr;
1144                 FDCharDriver *s;
1145
1146                 chr = stdio_clients[client_index];
1147                 s = chr->opaque;
1148                 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1149             }
1150             break;
1151         case 'c':
1152             client_index++;
1153             if (client_index >= stdio_nb_clients)
1154                 client_index = 0;
1155             if (client_index == 0) {
1156                 /* send a new line in the monitor to get the prompt */
1157                 ch = '\r';
1158                 goto send_char;
1159             }
1160             break;
1161         case TERM_ESCAPE:
1162             goto send_char;
1163         }
1164     } else if (ch == TERM_ESCAPE) {
1165         term_got_escape = 1;
1166     } else {
1167     send_char:
1168         if (client_index < stdio_nb_clients) {
1169             uint8_t buf[1];
1170             CharDriverState *chr;
1171             FDCharDriver *s;
1172             
1173             chr = stdio_clients[client_index];
1174             s = chr->opaque;
1175             buf[0] = ch;
1176             /* XXX: should queue the char if the device is not
1177                ready */
1178             if (s->fd_can_read(s->fd_opaque) > 0) 
1179                 s->fd_read(s->fd_opaque, buf, 1);
1180         }
1181     }
1182 }
1183
1184 static int stdio_can_read(void *opaque)
1185 {
1186     /* XXX: not strictly correct */
1187     return 1;
1188 }
1189
1190 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1191 {
1192     int i;
1193     for(i = 0; i < size; i++)
1194         stdio_received_byte(buf[i]);
1195 }
1196
1197 /* init terminal so that we can grab keys */
1198 static struct termios oldtty;
1199 static int old_fd0_flags;
1200
1201 static void term_exit(void)
1202 {
1203     tcsetattr (0, TCSANOW, &oldtty);
1204     fcntl(0, F_SETFL, old_fd0_flags);
1205 }
1206
1207 static void term_init(void)
1208 {
1209     struct termios tty;
1210
1211     tcgetattr (0, &tty);
1212     oldtty = tty;
1213     old_fd0_flags = fcntl(0, F_GETFL);
1214
1215     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1216                           |INLCR|IGNCR|ICRNL|IXON);
1217     tty.c_oflag |= OPOST;
1218     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1219     /* if graphical mode, we allow Ctrl-C handling */
1220     if (nographic)
1221         tty.c_lflag &= ~ISIG;
1222     tty.c_cflag &= ~(CSIZE|PARENB);
1223     tty.c_cflag |= CS8;
1224     tty.c_cc[VMIN] = 1;
1225     tty.c_cc[VTIME] = 0;
1226     
1227     tcsetattr (0, TCSANOW, &tty);
1228
1229     atexit(term_exit);
1230
1231     fcntl(0, F_SETFL, O_NONBLOCK);
1232 }
1233
1234 CharDriverState *qemu_chr_open_stdio(void)
1235 {
1236     CharDriverState *chr;
1237
1238     if (nographic) {
1239         if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1240             return NULL;
1241         chr = qemu_chr_open_fd(0, 1);
1242         if (stdio_nb_clients == 0)
1243             qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1244         client_index = stdio_nb_clients;
1245     } else {
1246         if (stdio_nb_clients != 0)
1247             return NULL;
1248         chr = qemu_chr_open_fd(0, 1);
1249     }
1250     stdio_clients[stdio_nb_clients++] = chr;
1251     if (stdio_nb_clients == 1) {
1252         /* set the terminal in raw mode */
1253         term_init();
1254     }
1255     return chr;
1256 }
1257
1258 #if defined(__linux__)
1259 CharDriverState *qemu_chr_open_pty(void)
1260 {
1261     char slave_name[1024];
1262     int master_fd, slave_fd;
1263     
1264     /* Not satisfying */
1265     if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1266         return NULL;
1267     }
1268     fprintf(stderr, "char device redirected to %s\n", slave_name);
1269     return qemu_chr_open_fd(master_fd, master_fd);
1270 }
1271 #else
1272 CharDriverState *qemu_chr_open_pty(void)
1273 {
1274     return NULL;
1275 }
1276 #endif
1277
1278 #endif /* !defined(_WIN32) */
1279
1280 CharDriverState *qemu_chr_open(const char *filename)
1281 {
1282     if (!strcmp(filename, "vc")) {
1283         return text_console_init(&display_state);
1284     } else if (!strcmp(filename, "null")) {
1285         return qemu_chr_open_null();
1286     } else 
1287 #ifndef _WIN32
1288     if (!strcmp(filename, "pty")) {
1289         return qemu_chr_open_pty();
1290     } else if (!strcmp(filename, "stdio")) {
1291         return qemu_chr_open_stdio();
1292     } else 
1293 #endif
1294     {
1295         return NULL;
1296     }
1297 }
1298
1299 /***********************************************************/
1300 /* Linux network device redirectors */
1301
1302 void hex_dump(FILE *f, const uint8_t *buf, int size)
1303 {
1304     int len, i, j, c;
1305
1306     for(i=0;i<size;i+=16) {
1307         len = size - i;
1308         if (len > 16)
1309             len = 16;
1310         fprintf(f, "%08x ", i);
1311         for(j=0;j<16;j++) {
1312             if (j < len)
1313                 fprintf(f, " %02x", buf[i+j]);
1314             else
1315                 fprintf(f, "   ");
1316         }
1317         fprintf(f, " ");
1318         for(j=0;j<len;j++) {
1319             c = buf[i+j];
1320             if (c < ' ' || c > '~')
1321                 c = '.';
1322             fprintf(f, "%c", c);
1323         }
1324         fprintf(f, "\n");
1325     }
1326 }
1327
1328 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1329 {
1330     nd->send_packet(nd, buf, size);
1331 }
1332
1333 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read, 
1334                           IOReadHandler *fd_read, void *opaque)
1335 {
1336     nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1337 }
1338
1339 /* dummy network adapter */
1340
1341 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1342 {
1343 }
1344
1345 static void dummy_add_read_packet(NetDriverState *nd, 
1346                                   IOCanRWHandler *fd_can_read, 
1347                                   IOReadHandler *fd_read, void *opaque)
1348 {
1349 }
1350
1351 static int net_dummy_init(NetDriverState *nd)
1352 {
1353     nd->send_packet = dummy_send_packet;
1354     nd->add_read_packet = dummy_add_read_packet;
1355     pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1356     return 0;
1357 }
1358
1359 #if defined(CONFIG_SLIRP)
1360
1361 /* slirp network adapter */
1362
1363 static void *slirp_fd_opaque;
1364 static IOCanRWHandler *slirp_fd_can_read;
1365 static IOReadHandler *slirp_fd_read;
1366 static int slirp_inited;
1367
1368 int slirp_can_output(void)
1369 {
1370     return slirp_fd_can_read(slirp_fd_opaque);
1371 }
1372
1373 void slirp_output(const uint8_t *pkt, int pkt_len)
1374 {
1375 #if 0
1376     printf("output:\n");
1377     hex_dump(stdout, pkt, pkt_len);
1378 #endif
1379     slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1380 }
1381
1382 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1383 {
1384 #if 0
1385     printf("input:\n");
1386     hex_dump(stdout, buf, size);
1387 #endif
1388     slirp_input(buf, size);
1389 }
1390
1391 static void slirp_add_read_packet(NetDriverState *nd, 
1392                                   IOCanRWHandler *fd_can_read, 
1393                                   IOReadHandler *fd_read, void *opaque)
1394 {
1395     slirp_fd_opaque = opaque;
1396     slirp_fd_can_read = fd_can_read;
1397     slirp_fd_read = fd_read;
1398 }
1399
1400 static int net_slirp_init(NetDriverState *nd)
1401 {
1402     if (!slirp_inited) {
1403         slirp_inited = 1;
1404         slirp_init();
1405     }
1406     nd->send_packet = slirp_send_packet;
1407     nd->add_read_packet = slirp_add_read_packet;
1408     pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1409     return 0;
1410 }
1411
1412 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1413 {
1414     const char *p, *p1;
1415     int len;
1416     p = *pp;
1417     p1 = strchr(p, sep);
1418     if (!p1)
1419         return -1;
1420     len = p1 - p;
1421     p1++;
1422     if (buf_size > 0) {
1423         if (len > buf_size - 1)
1424             len = buf_size - 1;
1425         memcpy(buf, p, len);
1426         buf[len] = '\0';
1427     }
1428     *pp = p1;
1429     return 0;
1430 }
1431
1432 static void net_slirp_redir(const char *redir_str)
1433 {
1434     int is_udp;
1435     char buf[256], *r;
1436     const char *p;
1437     struct in_addr guest_addr;
1438     int host_port, guest_port;
1439     
1440     if (!slirp_inited) {
1441         slirp_inited = 1;
1442         slirp_init();
1443     }
1444
1445     p = redir_str;
1446     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1447         goto fail;
1448     if (!strcmp(buf, "tcp")) {
1449         is_udp = 0;
1450     } else if (!strcmp(buf, "udp")) {
1451         is_udp = 1;
1452     } else {
1453         goto fail;
1454     }
1455
1456     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1457         goto fail;
1458     host_port = strtol(buf, &r, 0);
1459     if (r == buf)
1460         goto fail;
1461
1462     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1463         goto fail;
1464     if (buf[0] == '\0') {
1465         pstrcpy(buf, sizeof(buf), "10.0.2.15");
1466     }
1467     if (!inet_aton(buf, &guest_addr))
1468         goto fail;
1469     
1470     guest_port = strtol(p, &r, 0);
1471     if (r == p)
1472         goto fail;
1473     
1474     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1475         fprintf(stderr, "qemu: could not set up redirection\n");
1476         exit(1);
1477     }
1478     return;
1479  fail:
1480     fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1481     exit(1);
1482 }
1483     
1484 #ifndef _WIN32
1485
1486 char smb_dir[1024];
1487
1488 static void smb_exit(void)
1489 {
1490     DIR *d;
1491     struct dirent *de;
1492     char filename[1024];
1493
1494     /* erase all the files in the directory */
1495     d = opendir(smb_dir);
1496     for(;;) {
1497         de = readdir(d);
1498         if (!de)
1499             break;
1500         if (strcmp(de->d_name, ".") != 0 &&
1501             strcmp(de->d_name, "..") != 0) {
1502             snprintf(filename, sizeof(filename), "%s/%s", 
1503                      smb_dir, de->d_name);
1504             unlink(filename);
1505         }
1506     }
1507     closedir(d);
1508     rmdir(smb_dir);
1509 }
1510
1511 /* automatic user mode samba server configuration */
1512 void net_slirp_smb(const char *exported_dir)
1513 {
1514     char smb_conf[1024];
1515     char smb_cmdline[1024];
1516     FILE *f;
1517
1518     if (!slirp_inited) {
1519         slirp_inited = 1;
1520         slirp_init();
1521     }
1522
1523     /* XXX: better tmp dir construction */
1524     snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1525     if (mkdir(smb_dir, 0700) < 0) {
1526         fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1527         exit(1);
1528     }
1529     snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1530     
1531     f = fopen(smb_conf, "w");
1532     if (!f) {
1533         fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1534         exit(1);
1535     }
1536     fprintf(f, 
1537             "[global]\n"
1538             "pid directory=%s\n"
1539             "lock directory=%s\n"
1540             "log file=%s/log.smbd\n"
1541             "smb passwd file=%s/smbpasswd\n"
1542             "security = share\n"
1543             "[qemu]\n"
1544             "path=%s\n"
1545             "read only=no\n"
1546             "guest ok=yes\n",
1547             smb_dir,
1548             smb_dir,
1549             smb_dir,
1550             smb_dir,
1551             exported_dir
1552             );
1553     fclose(f);
1554     atexit(smb_exit);
1555
1556     snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1557              smb_conf);
1558     
1559     slirp_add_exec(0, smb_cmdline, 4, 139);
1560 }
1561
1562 #endif /* !defined(_WIN32) */
1563
1564 #endif /* CONFIG_SLIRP */
1565
1566 #if !defined(_WIN32)
1567 #ifdef _BSD
1568 static int tun_open(char *ifname, int ifname_size)
1569 {
1570     int fd;
1571     char *dev;
1572     struct stat s;
1573
1574     fd = open("/dev/tap", O_RDWR);
1575     if (fd < 0) {
1576         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1577         return -1;
1578     }
1579
1580     fstat(fd, &s);
1581     dev = devname(s.st_rdev, S_IFCHR);
1582     pstrcpy(ifname, ifname_size, dev);
1583
1584     fcntl(fd, F_SETFL, O_NONBLOCK);
1585     return fd;
1586 }
1587 #else
1588 static int tun_open(char *ifname, int ifname_size)
1589 {
1590     struct ifreq ifr;
1591     int fd, ret;
1592     
1593     fd = open("/dev/net/tun", O_RDWR);
1594     if (fd < 0) {
1595         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1596         return -1;
1597     }
1598     memset(&ifr, 0, sizeof(ifr));
1599     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1600     pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1601     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1602     if (ret != 0) {
1603         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1604         close(fd);
1605         return -1;
1606     }
1607     printf("Connected to host network interface: %s\n", ifr.ifr_name);
1608     pstrcpy(ifname, ifname_size, ifr.ifr_name);
1609     fcntl(fd, F_SETFL, O_NONBLOCK);
1610     return fd;
1611 }
1612 #endif
1613
1614 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1615 {
1616     write(nd->fd, buf, size);
1617 }
1618
1619 static void tun_add_read_packet(NetDriverState *nd, 
1620                                 IOCanRWHandler *fd_can_read, 
1621                                 IOReadHandler *fd_read, void *opaque)
1622 {
1623     qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1624 }
1625
1626 static int net_tun_init(NetDriverState *nd)
1627 {
1628     int pid, status;
1629     char *args[3];
1630     char **parg;
1631
1632     nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1633     if (nd->fd < 0)
1634         return -1;
1635
1636     /* try to launch network init script */
1637     pid = fork();
1638     if (pid >= 0) {
1639         if (pid == 0) {
1640             parg = args;
1641             *parg++ = network_script;
1642             *parg++ = nd->ifname;
1643             *parg++ = NULL;
1644             execv(network_script, args);
1645             exit(1);
1646         }
1647         while (waitpid(pid, &status, 0) != pid);
1648         if (!WIFEXITED(status) ||
1649             WEXITSTATUS(status) != 0) {
1650             fprintf(stderr, "%s: could not launch network script\n",
1651                     network_script);
1652         }
1653     }
1654     nd->send_packet = tun_send_packet;
1655     nd->add_read_packet = tun_add_read_packet;
1656     return 0;
1657 }
1658
1659 static int net_fd_init(NetDriverState *nd, int fd)
1660 {
1661     nd->fd = fd;
1662     nd->send_packet = tun_send_packet;
1663     nd->add_read_packet = tun_add_read_packet;
1664     pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1665     return 0;
1666 }
1667
1668 #endif /* !_WIN32 */
1669
1670 /***********************************************************/
1671 /* pid file */
1672
1673 static char *pid_filename;
1674
1675 /* Remove PID file. Called on normal exit */
1676
1677 static void remove_pidfile(void) 
1678 {
1679     unlink (pid_filename);
1680 }
1681
1682 static void create_pidfile(const char *filename)
1683 {
1684     struct stat pidstat;
1685     FILE *f;
1686
1687     /* Try to write our PID to the named file */
1688     if (stat(filename, &pidstat) < 0) {
1689         if (errno == ENOENT) {
1690             if ((f = fopen (filename, "w")) == NULL) {
1691                 perror("Opening pidfile");
1692                 exit(1);
1693             }
1694             fprintf(f, "%d\n", getpid());
1695             fclose(f);
1696             pid_filename = qemu_strdup(filename);
1697             if (!pid_filename) {
1698                 fprintf(stderr, "Could not save PID filename");
1699                 exit(1);
1700             }
1701             atexit(remove_pidfile);
1702         }
1703     } else {
1704         fprintf(stderr, "%s already exists. Remove it and try again.\n", 
1705                 filename);
1706         exit(1);
1707     }
1708 }
1709
1710 /***********************************************************/
1711 /* dumb display */
1712
1713 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1714 {
1715 }
1716
1717 static void dumb_resize(DisplayState *ds, int w, int h)
1718 {
1719 }
1720
1721 static void dumb_refresh(DisplayState *ds)
1722 {
1723     vga_update_display();
1724 }
1725
1726 void dumb_display_init(DisplayState *ds)
1727 {
1728     ds->data = NULL;
1729     ds->linesize = 0;
1730     ds->depth = 0;
1731     ds->dpy_update = dumb_update;
1732     ds->dpy_resize = dumb_resize;
1733     ds->dpy_refresh = dumb_refresh;
1734 }
1735
1736 #if !defined(CONFIG_SOFTMMU)
1737 /***********************************************************/
1738 /* cpu signal handler */
1739 static void host_segv_handler(int host_signum, siginfo_t *info, 
1740                               void *puc)
1741 {
1742     if (cpu_signal_handler(host_signum, info, puc))
1743         return;
1744     if (stdio_nb_clients > 0)
1745         term_exit();
1746     abort();
1747 }
1748 #endif
1749
1750 /***********************************************************/
1751 /* I/O handling */
1752
1753 #define MAX_IO_HANDLERS 64
1754
1755 typedef struct IOHandlerRecord {
1756     int fd;
1757     IOCanRWHandler *fd_can_read;
1758     IOReadHandler *fd_read;
1759     void *opaque;
1760     /* temporary data */
1761     struct pollfd *ufd;
1762     int max_size;
1763     struct IOHandlerRecord *next;
1764 } IOHandlerRecord;
1765
1766 static IOHandlerRecord *first_io_handler;
1767
1768 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
1769                              IOReadHandler *fd_read, void *opaque)
1770 {
1771     IOHandlerRecord *ioh;
1772
1773     ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1774     if (!ioh)
1775         return -1;
1776     ioh->fd = fd;
1777     ioh->fd_can_read = fd_can_read;
1778     ioh->fd_read = fd_read;
1779     ioh->opaque = opaque;
1780     ioh->next = first_io_handler;
1781     first_io_handler = ioh;
1782     return 0;
1783 }
1784
1785 void qemu_del_fd_read_handler(int fd)
1786 {
1787     IOHandlerRecord **pioh, *ioh;
1788
1789     pioh = &first_io_handler;
1790     for(;;) {
1791         ioh = *pioh;
1792         if (ioh == NULL)
1793             break;
1794         if (ioh->fd == fd) {
1795             *pioh = ioh->next;
1796             break;
1797         }
1798         pioh = &ioh->next;
1799     }
1800 }
1801
1802 /***********************************************************/
1803 /* savevm/loadvm support */
1804
1805 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1806 {
1807     fwrite(buf, 1, size, f);
1808 }
1809
1810 void qemu_put_byte(QEMUFile *f, int v)
1811 {
1812     fputc(v, f);
1813 }
1814
1815 void qemu_put_be16(QEMUFile *f, unsigned int v)
1816 {
1817     qemu_put_byte(f, v >> 8);
1818     qemu_put_byte(f, v);
1819 }
1820
1821 void qemu_put_be32(QEMUFile *f, unsigned int v)
1822 {
1823     qemu_put_byte(f, v >> 24);
1824     qemu_put_byte(f, v >> 16);
1825     qemu_put_byte(f, v >> 8);
1826     qemu_put_byte(f, v);
1827 }
1828
1829 void qemu_put_be64(QEMUFile *f, uint64_t v)
1830 {
1831     qemu_put_be32(f, v >> 32);
1832     qemu_put_be32(f, v);
1833 }
1834
1835 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1836 {
1837     return fread(buf, 1, size, f);
1838 }
1839
1840 int qemu_get_byte(QEMUFile *f)
1841 {
1842     int v;
1843     v = fgetc(f);
1844     if (v == EOF)
1845         return 0;
1846     else
1847         return v;
1848 }
1849
1850 unsigned int qemu_get_be16(QEMUFile *f)
1851 {
1852     unsigned int v;
1853     v = qemu_get_byte(f) << 8;
1854     v |= qemu_get_byte(f);
1855     return v;
1856 }
1857
1858 unsigned int qemu_get_be32(QEMUFile *f)
1859 {
1860     unsigned int v;
1861     v = qemu_get_byte(f) << 24;
1862     v |= qemu_get_byte(f) << 16;
1863     v |= qemu_get_byte(f) << 8;
1864     v |= qemu_get_byte(f);
1865     return v;
1866 }
1867
1868 uint64_t qemu_get_be64(QEMUFile *f)
1869 {
1870     uint64_t v;
1871     v = (uint64_t)qemu_get_be32(f) << 32;
1872     v |= qemu_get_be32(f);
1873     return v;
1874 }
1875
1876 int64_t qemu_ftell(QEMUFile *f)
1877 {
1878     return ftell(f);
1879 }
1880
1881 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1882 {
1883     if (fseek(f, pos, whence) < 0)
1884         return -1;
1885     return ftell(f);
1886 }
1887
1888 typedef struct SaveStateEntry {
1889     char idstr[256];
1890     int instance_id;
1891     int version_id;
1892     SaveStateHandler *save_state;
1893     LoadStateHandler *load_state;
1894     void *opaque;
1895     struct SaveStateEntry *next;
1896 } SaveStateEntry;
1897
1898 static SaveStateEntry *first_se;
1899
1900 int register_savevm(const char *idstr, 
1901                     int instance_id, 
1902                     int version_id,
1903                     SaveStateHandler *save_state,
1904                     LoadStateHandler *load_state,
1905                     void *opaque)
1906 {
1907     SaveStateEntry *se, **pse;
1908
1909     se = qemu_malloc(sizeof(SaveStateEntry));
1910     if (!se)
1911         return -1;
1912     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1913     se->instance_id = instance_id;
1914     se->version_id = version_id;
1915     se->save_state = save_state;
1916     se->load_state = load_state;
1917     se->opaque = opaque;
1918     se->next = NULL;
1919
1920     /* add at the end of list */
1921     pse = &first_se;
1922     while (*pse != NULL)
1923         pse = &(*pse)->next;
1924     *pse = se;
1925     return 0;
1926 }
1927
1928 #define QEMU_VM_FILE_MAGIC   0x5145564d
1929 #define QEMU_VM_FILE_VERSION 0x00000001
1930
1931 int qemu_savevm(const char *filename)
1932 {
1933     SaveStateEntry *se;
1934     QEMUFile *f;
1935     int len, len_pos, cur_pos, saved_vm_running, ret;
1936
1937     saved_vm_running = vm_running;
1938     vm_stop(0);
1939
1940     f = fopen(filename, "wb");
1941     if (!f) {
1942         ret = -1;
1943         goto the_end;
1944     }
1945
1946     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1947     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1948
1949     for(se = first_se; se != NULL; se = se->next) {
1950         /* ID string */
1951         len = strlen(se->idstr);
1952         qemu_put_byte(f, len);
1953         qemu_put_buffer(f, se->idstr, len);
1954
1955         qemu_put_be32(f, se->instance_id);
1956         qemu_put_be32(f, se->version_id);
1957
1958         /* record size: filled later */
1959         len_pos = ftell(f);
1960         qemu_put_be32(f, 0);
1961         
1962         se->save_state(f, se->opaque);
1963
1964         /* fill record size */
1965         cur_pos = ftell(f);
1966         len = ftell(f) - len_pos - 4;
1967         fseek(f, len_pos, SEEK_SET);
1968         qemu_put_be32(f, len);
1969         fseek(f, cur_pos, SEEK_SET);
1970     }
1971
1972     fclose(f);
1973     ret = 0;
1974  the_end:
1975     if (saved_vm_running)
1976         vm_start();
1977     return ret;
1978 }
1979
1980 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1981 {
1982     SaveStateEntry *se;
1983
1984     for(se = first_se; se != NULL; se = se->next) {
1985         if (!strcmp(se->idstr, idstr) && 
1986             instance_id == se->instance_id)
1987             return se;
1988     }
1989     return NULL;
1990 }
1991
1992 int qemu_loadvm(const char *filename)
1993 {
1994     SaveStateEntry *se;
1995     QEMUFile *f;
1996     int len, cur_pos, ret, instance_id, record_len, version_id;
1997     int saved_vm_running;
1998     unsigned int v;
1999     char idstr[256];
2000     
2001     saved_vm_running = vm_running;
2002     vm_stop(0);
2003
2004     f = fopen(filename, "rb");
2005     if (!f) {
2006         ret = -1;
2007         goto the_end;
2008     }
2009
2010     v = qemu_get_be32(f);
2011     if (v != QEMU_VM_FILE_MAGIC)
2012         goto fail;
2013     v = qemu_get_be32(f);
2014     if (v != QEMU_VM_FILE_VERSION) {
2015     fail:
2016         fclose(f);
2017         ret = -1;
2018         goto the_end;
2019     }
2020     for(;;) {
2021 #if defined (DO_TB_FLUSH)
2022         tb_flush(global_env);
2023 #endif
2024         len = qemu_get_byte(f);
2025         if (feof(f))
2026             break;
2027         qemu_get_buffer(f, idstr, len);
2028         idstr[len] = '\0';
2029         instance_id = qemu_get_be32(f);
2030         version_id = qemu_get_be32(f);
2031         record_len = qemu_get_be32(f);
2032 #if 0
2033         printf("idstr=%s instance=0x%x version=%d len=%d\n", 
2034                idstr, instance_id, version_id, record_len);
2035 #endif
2036         cur_pos = ftell(f);
2037         se = find_se(idstr, instance_id);
2038         if (!se) {
2039             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
2040                     instance_id, idstr);
2041         } else {
2042             ret = se->load_state(f, se->opaque, version_id);
2043             if (ret < 0) {
2044                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
2045                         instance_id, idstr);
2046             }
2047         }
2048         /* always seek to exact end of record */
2049         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
2050     }
2051     fclose(f);
2052     ret = 0;
2053  the_end:
2054     if (saved_vm_running)
2055         vm_start();
2056     return ret;
2057 }
2058
2059 /***********************************************************/
2060 /* cpu save/restore */
2061
2062 #if defined(TARGET_I386)
2063
2064 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
2065 {
2066     qemu_put_be32(f, dt->selector);
2067     qemu_put_be32(f, (uint32_t)dt->base);
2068     qemu_put_be32(f, dt->limit);
2069     qemu_put_be32(f, dt->flags);
2070 }
2071
2072 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
2073 {
2074     dt->selector = qemu_get_be32(f);
2075     dt->base = (uint8_t *)qemu_get_be32(f);
2076     dt->limit = qemu_get_be32(f);
2077     dt->flags = qemu_get_be32(f);
2078 }
2079
2080 void cpu_save(QEMUFile *f, void *opaque)
2081 {
2082     CPUState *env = opaque;
2083     uint16_t fptag, fpus, fpuc;
2084     uint32_t hflags;
2085     int i;
2086
2087     for(i = 0; i < 8; i++)
2088         qemu_put_be32s(f, &env->regs[i]);
2089     qemu_put_be32s(f, &env->eip);
2090     qemu_put_be32s(f, &env->eflags);
2091     qemu_put_be32s(f, &env->eflags);
2092     hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
2093     qemu_put_be32s(f, &hflags);
2094     
2095     /* FPU */
2096     fpuc = env->fpuc;
2097     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
2098     fptag = 0;
2099     for (i=7; i>=0; i--) {
2100         fptag <<= 2;
2101         if (env->fptags[i]) {
2102             fptag |= 3;
2103         }
2104     }
2105     
2106     qemu_put_be16s(f, &fpuc);
2107     qemu_put_be16s(f, &fpus);
2108     qemu_put_be16s(f, &fptag);
2109
2110     for(i = 0; i < 8; i++) {
2111         uint64_t mant;
2112         uint16_t exp;
2113         cpu_get_fp80(&mant, &exp, env->fpregs[i]);
2114         qemu_put_be64(f, mant);
2115         qemu_put_be16(f, exp);
2116     }
2117
2118     for(i = 0; i < 6; i++)
2119         cpu_put_seg(f, &env->segs[i]);
2120     cpu_put_seg(f, &env->ldt);
2121     cpu_put_seg(f, &env->tr);
2122     cpu_put_seg(f, &env->gdt);
2123     cpu_put_seg(f, &env->idt);
2124     
2125     qemu_put_be32s(f, &env->sysenter_cs);
2126     qemu_put_be32s(f, &env->sysenter_esp);
2127     qemu_put_be32s(f, &env->sysenter_eip);
2128     
2129     qemu_put_be32s(f, &env->cr[0]);
2130     qemu_put_be32s(f, &env->cr[2]);
2131     qemu_put_be32s(f, &env->cr[3]);
2132     qemu_put_be32s(f, &env->cr[4]);
2133     
2134     for(i = 0; i < 8; i++)
2135         qemu_put_be32s(f, &env->dr[i]);
2136
2137     /* MMU */
2138     qemu_put_be32s(f, &env->a20_mask);
2139 }
2140
2141 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2142 {
2143     CPUState *env = opaque;
2144     int i;
2145     uint32_t hflags;
2146     uint16_t fpus, fpuc, fptag;
2147
2148     if (version_id != 2)
2149         return -EINVAL;
2150     for(i = 0; i < 8; i++)
2151         qemu_get_be32s(f, &env->regs[i]);
2152     qemu_get_be32s(f, &env->eip);
2153     qemu_get_be32s(f, &env->eflags);
2154     qemu_get_be32s(f, &env->eflags);
2155     qemu_get_be32s(f, &hflags);
2156
2157     qemu_get_be16s(f, &fpuc);
2158     qemu_get_be16s(f, &fpus);
2159     qemu_get_be16s(f, &fptag);
2160
2161     for(i = 0; i < 8; i++) {
2162         uint64_t mant;
2163         uint16_t exp;
2164         mant = qemu_get_be64(f);
2165         exp = qemu_get_be16(f);
2166         env->fpregs[i] = cpu_set_fp80(mant, exp);
2167     }
2168
2169     env->fpuc = fpuc;
2170     env->fpstt = (fpus >> 11) & 7;
2171     env->fpus = fpus & ~0x3800;
2172     for(i = 0; i < 8; i++) {
2173         env->fptags[i] = ((fptag & 3) == 3);
2174         fptag >>= 2;
2175     }
2176     
2177     for(i = 0; i < 6; i++)
2178         cpu_get_seg(f, &env->segs[i]);
2179     cpu_get_seg(f, &env->ldt);
2180     cpu_get_seg(f, &env->tr);
2181     cpu_get_seg(f, &env->gdt);
2182     cpu_get_seg(f, &env->idt);
2183     
2184     qemu_get_be32s(f, &env->sysenter_cs);
2185     qemu_get_be32s(f, &env->sysenter_esp);
2186     qemu_get_be32s(f, &env->sysenter_eip);
2187     
2188     qemu_get_be32s(f, &env->cr[0]);
2189     qemu_get_be32s(f, &env->cr[2]);
2190     qemu_get_be32s(f, &env->cr[3]);
2191     qemu_get_be32s(f, &env->cr[4]);
2192     
2193     for(i = 0; i < 8; i++)
2194         qemu_get_be32s(f, &env->dr[i]);
2195
2196     /* MMU */
2197     qemu_get_be32s(f, &env->a20_mask);
2198
2199     /* XXX: compute hflags from scratch, except for CPL and IIF */
2200     env->hflags = hflags;
2201     tlb_flush(env, 1);
2202     return 0;
2203 }
2204
2205 #elif defined(TARGET_PPC)
2206 void cpu_save(QEMUFile *f, void *opaque)
2207 {
2208 }
2209
2210 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2211 {
2212     return 0;
2213 }
2214 #elif defined(TARGET_SPARC)
2215 void cpu_save(QEMUFile *f, void *opaque)
2216 {
2217 }
2218
2219 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2220 {
2221     return 0;
2222 }
2223 #else
2224
2225 #warning No CPU save/restore functions
2226
2227 #endif
2228
2229 /***********************************************************/
2230 /* ram save/restore */
2231
2232 /* we just avoid storing empty pages */
2233 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
2234 {
2235     int i, v;
2236
2237     v = buf[0];
2238     for(i = 1; i < len; i++) {
2239         if (buf[i] != v)
2240             goto normal_save;
2241     }
2242     qemu_put_byte(f, 1);
2243     qemu_put_byte(f, v);
2244     return;
2245  normal_save:
2246     qemu_put_byte(f, 0); 
2247     qemu_put_buffer(f, buf, len);
2248 }
2249
2250 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2251 {
2252     int v;
2253
2254     v = qemu_get_byte(f);
2255     switch(v) {
2256     case 0:
2257         if (qemu_get_buffer(f, buf, len) != len)
2258             return -EIO;
2259         break;
2260     case 1:
2261         v = qemu_get_byte(f);
2262         memset(buf, v, len);
2263         break;
2264     default:
2265         return -EINVAL;
2266     }
2267     return 0;
2268 }
2269
2270 static void ram_save(QEMUFile *f, void *opaque)
2271 {
2272     int i;
2273     qemu_put_be32(f, phys_ram_size);
2274     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2275         ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2276     }
2277 }
2278
2279 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2280 {
2281     int i, ret;
2282
2283     if (version_id != 1)
2284         return -EINVAL;
2285     if (qemu_get_be32(f) != phys_ram_size)
2286         return -EINVAL;
2287     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2288         ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2289         if (ret)
2290             return ret;
2291     }
2292     return 0;
2293 }
2294
2295 /***********************************************************/
2296 /* main execution loop */
2297
2298 void gui_update(void *opaque)
2299 {
2300     display_state.dpy_refresh(&display_state);
2301     qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2302 }
2303
2304 /* XXX: support several handlers */
2305 VMStopHandler *vm_stop_cb;
2306 VMStopHandler *vm_stop_opaque;
2307
2308 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2309 {
2310     vm_stop_cb = cb;
2311     vm_stop_opaque = opaque;
2312     return 0;
2313 }
2314
2315 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2316 {
2317     vm_stop_cb = NULL;
2318 }
2319
2320 void vm_start(void)
2321 {
2322     if (!vm_running) {
2323         cpu_enable_ticks();
2324         vm_running = 1;
2325     }
2326 }
2327
2328 void vm_stop(int reason) 
2329 {
2330     if (vm_running) {
2331         cpu_disable_ticks();
2332         vm_running = 0;
2333         if (reason != 0) {
2334             if (vm_stop_cb) {
2335                 vm_stop_cb(vm_stop_opaque, reason);
2336             }
2337         }
2338     }
2339 }
2340
2341 /* reset/shutdown handler */
2342
2343 typedef struct QEMUResetEntry {
2344     QEMUResetHandler *func;
2345     void *opaque;
2346     struct QEMUResetEntry *next;
2347 } QEMUResetEntry;
2348
2349 static QEMUResetEntry *first_reset_entry;
2350 static int reset_requested;
2351 static int shutdown_requested;
2352
2353 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2354 {
2355     QEMUResetEntry **pre, *re;
2356
2357     pre = &first_reset_entry;
2358     while (*pre != NULL)
2359         pre = &(*pre)->next;
2360     re = qemu_mallocz(sizeof(QEMUResetEntry));
2361     re->func = func;
2362     re->opaque = opaque;
2363     re->next = NULL;
2364     *pre = re;
2365 }
2366
2367 void qemu_system_reset(void)
2368 {
2369     QEMUResetEntry *re;
2370
2371     /* reset all devices */
2372     for(re = first_reset_entry; re != NULL; re = re->next) {
2373         re->func(re->opaque);
2374     }
2375 }
2376
2377 void qemu_system_reset_request(void)
2378 {
2379     reset_requested = 1;
2380     cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2381 }
2382
2383 void qemu_system_shutdown_request(void)
2384 {
2385     shutdown_requested = 1;
2386     cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2387 }
2388
2389 static void main_cpu_reset(void *opaque)
2390 {
2391 #ifdef TARGET_I386
2392     CPUState *env = opaque;
2393     cpu_reset(env);
2394 #endif
2395 }
2396
2397 void main_loop_wait(int timeout)
2398 {
2399 #ifndef _WIN32
2400     struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2401     IOHandlerRecord *ioh, *ioh_next;
2402     uint8_t buf[4096];
2403     int n, max_size;
2404 #endif
2405     int ret;
2406
2407 #ifdef _WIN32
2408         if (timeout > 0)
2409             Sleep(timeout);
2410 #else
2411         /* poll any events */
2412         /* XXX: separate device handlers from system ones */
2413         pf = ufds;
2414         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2415             if (!ioh->fd_can_read) {
2416                 max_size = 0;
2417                 pf->fd = ioh->fd;
2418                 pf->events = POLLIN;
2419                 ioh->ufd = pf;
2420                 pf++;
2421             } else {
2422                 max_size = ioh->fd_can_read(ioh->opaque);
2423                 if (max_size > 0) {
2424                     if (max_size > sizeof(buf))
2425                         max_size = sizeof(buf);
2426                     pf->fd = ioh->fd;
2427                     pf->events = POLLIN;
2428                     ioh->ufd = pf;
2429                     pf++;
2430                 } else {
2431                     ioh->ufd = NULL;
2432                 }
2433             }
2434             ioh->max_size = max_size;
2435         }
2436         
2437         ret = poll(ufds, pf - ufds, timeout);
2438         if (ret > 0) {
2439             /* XXX: better handling of removal */
2440             for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2441                 ioh_next = ioh->next;
2442                 pf = ioh->ufd;
2443                 if (pf) {
2444                     if (pf->revents & POLLIN) {
2445                         if (ioh->max_size == 0) {
2446                             /* just a read event */
2447                             ioh->fd_read(ioh->opaque, NULL, 0);
2448                         } else {
2449                             n = read(ioh->fd, buf, ioh->max_size);
2450                             if (n >= 0) {
2451                                 ioh->fd_read(ioh->opaque, buf, n);
2452                             } else if (errno != EAGAIN) {
2453                                 ioh->fd_read(ioh->opaque, NULL, -errno);
2454                             }
2455                         }
2456                     }
2457                 }
2458             }
2459         }
2460 #endif /* !defined(_WIN32) */
2461 #if defined(CONFIG_SLIRP)
2462         /* XXX: merge with poll() */
2463         if (slirp_inited) {
2464             fd_set rfds, wfds, xfds;
2465             int nfds;
2466             struct timeval tv;
2467
2468             nfds = -1;
2469             FD_ZERO(&rfds);
2470             FD_ZERO(&wfds);
2471             FD_ZERO(&xfds);
2472             slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2473             tv.tv_sec = 0;
2474             tv.tv_usec = 0;
2475             ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2476             if (ret >= 0) {
2477                 slirp_select_poll(&rfds, &wfds, &xfds);
2478             }
2479         }
2480 #endif
2481
2482         if (vm_running) {
2483             qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
2484                             qemu_get_clock(vm_clock));
2485             /* run dma transfers, if any */
2486             DMA_run();
2487         }
2488
2489         /* real time timers */
2490         qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
2491                         qemu_get_clock(rt_clock));
2492 }
2493
2494 int main_loop(void)
2495 {
2496     int ret, timeout;
2497     CPUState *env = global_env;
2498
2499     for(;;) {
2500         if (vm_running) {
2501             ret = cpu_exec(env);
2502             if (shutdown_requested) {
2503                 ret = EXCP_INTERRUPT; 
2504                 break;
2505             }
2506             if (reset_requested) {
2507                 reset_requested = 0;
2508                 qemu_system_reset();
2509                 ret = EXCP_INTERRUPT; 
2510             }
2511             if (ret == EXCP_DEBUG) {
2512                 vm_stop(EXCP_DEBUG);
2513             }
2514             /* if hlt instruction, we wait until the next IRQ */
2515             /* XXX: use timeout computed from timers */
2516             if (ret == EXCP_HLT) 
2517                 timeout = 10;
2518             else
2519                 timeout = 0;
2520         } else {
2521             timeout = 10;
2522         }
2523         main_loop_wait(timeout);
2524     }
2525     cpu_disable_ticks();
2526     return ret;
2527 }
2528
2529 void help(void)
2530 {
2531     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2532            "usage: %s [options] [disk_image]\n"
2533            "\n"
2534            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2535            "\n"
2536            "Standard options:\n"
2537            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
2538            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
2539            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
2540            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2541            "-boot [a|c|d]   boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2542            "-snapshot       write to temporary files instead of disk image files\n"
2543            "-m megs         set virtual RAM size to megs MB [default=%d]\n"
2544            "-nographic      disable graphical output and redirect serial I/Os to console\n"
2545 #ifndef _WIN32
2546            "-k language     use keyboard layout (for example \"fr\" for French)\n"
2547 #endif
2548            "-enable-audio   enable audio support\n"
2549            "-localtime      set the real time clock to local time [default=utc]\n"
2550            "-full-screen    start in full screen\n"
2551 #ifdef TARGET_PPC
2552            "-prep           Simulate a PREP system (default is PowerMAC)\n"
2553            "-g WxH[xDEPTH]  Set the initial VGA graphic mode\n"
2554 #endif
2555            "\n"
2556            "Network options:\n"
2557            "-nics n         simulate 'n' network cards [default=1]\n"
2558            "-macaddr addr   set the mac address of the first interface\n"
2559            "-n script       set tap/tun network init script [default=%s]\n"
2560            "-tun-fd fd      use this fd as already opened tap/tun interface\n"
2561 #ifdef CONFIG_SLIRP
2562            "-user-net       use user mode network stack [default if no tap/tun script]\n"
2563            "-tftp prefix    allow tftp access to files starting with prefix [-user-net]\n"
2564 #ifndef _WIN32
2565            "-smb dir        allow SMB access to files in 'dir' [-user-net]\n"
2566 #endif
2567            "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2568            "                redirect TCP or UDP connections from host to guest [-user-net]\n"
2569 #endif
2570            "-dummy-net      use dummy network stack\n"
2571            "\n"
2572            "Linux boot specific:\n"
2573            "-kernel bzImage use 'bzImage' as kernel image\n"
2574            "-append cmdline use 'cmdline' as kernel command line\n"
2575            "-initrd file    use 'file' as initial ram disk\n"
2576            "\n"
2577            "Debug/Expert options:\n"
2578            "-monitor dev    redirect the monitor to char device 'dev'\n"
2579            "-serial dev     redirect the serial port to char device 'dev'\n"
2580            "-pidfile file   Write PID to 'file'\n"
2581            "-S              freeze CPU at startup (use 'c' to start execution)\n"
2582            "-s              wait gdb connection to port %d\n"
2583            "-p port         change gdb connection port\n"
2584            "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
2585            "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
2586            "                translation (t=none or lba) (usually qemu can guess them)\n"
2587            "-L path         set the directory for the BIOS and VGA BIOS\n"
2588 #ifdef USE_CODE_COPY
2589            "-no-code-copy   disable code copy acceleration\n"
2590 #endif
2591 #ifdef TARGET_I386
2592            "-isa            simulate an ISA-only system (default is PCI system)\n"
2593            "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
2594            "                (default is CL-GD5446 PCI VGA)\n"
2595 #endif
2596            "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
2597            "\n"
2598            "During emulation, the following keys are useful:\n"
2599            "ctrl-alt-f      toggle full screen\n"
2600            "ctrl-alt-n      switch to virtual console 'n'\n"
2601            "ctrl-alt        toggle mouse and keyboard grab\n"
2602            "\n"
2603            "When using -nographic, press 'ctrl-a h' to get some help.\n"
2604            ,
2605 #ifdef CONFIG_SOFTMMU
2606            "qemu",
2607 #else
2608            "qemu-fast",
2609 #endif
2610            DEFAULT_RAM_SIZE,
2611            DEFAULT_NETWORK_SCRIPT,
2612            DEFAULT_GDBSTUB_PORT,
2613            "/tmp/qemu.log");
2614 #ifndef CONFIG_SOFTMMU
2615     printf("\n"
2616            "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2617            "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2618            "PC emulation.\n");
2619 #endif
2620     exit(1);
2621 }
2622
2623 #define HAS_ARG 0x0001
2624
2625 enum {
2626     QEMU_OPTION_h,
2627
2628     QEMU_OPTION_fda,
2629     QEMU_OPTION_fdb,
2630     QEMU_OPTION_hda,
2631     QEMU_OPTION_hdb,
2632     QEMU_OPTION_hdc,
2633     QEMU_OPTION_hdd,
2634     QEMU_OPTION_cdrom,
2635     QEMU_OPTION_boot,
2636     QEMU_OPTION_snapshot,
2637     QEMU_OPTION_m,
2638     QEMU_OPTION_nographic,
2639     QEMU_OPTION_enable_audio,
2640
2641     QEMU_OPTION_nics,
2642     QEMU_OPTION_macaddr,
2643     QEMU_OPTION_n,
2644     QEMU_OPTION_tun_fd,
2645     QEMU_OPTION_user_net,
2646     QEMU_OPTION_tftp,
2647     QEMU_OPTION_smb,
2648     QEMU_OPTION_redir,
2649     QEMU_OPTION_dummy_net,
2650
2651     QEMU_OPTION_kernel,
2652     QEMU_OPTION_append,
2653     QEMU_OPTION_initrd,
2654
2655     QEMU_OPTION_S,
2656     QEMU_OPTION_s,
2657     QEMU_OPTION_p,
2658     QEMU_OPTION_d,
2659     QEMU_OPTION_hdachs,
2660     QEMU_OPTION_L,
2661     QEMU_OPTION_no_code_copy,
2662     QEMU_OPTION_pci,
2663     QEMU_OPTION_isa,
2664     QEMU_OPTION_prep,
2665     QEMU_OPTION_k,
2666     QEMU_OPTION_localtime,
2667     QEMU_OPTION_cirrusvga,
2668     QEMU_OPTION_g,
2669     QEMU_OPTION_std_vga,
2670     QEMU_OPTION_monitor,
2671     QEMU_OPTION_serial,
2672     QEMU_OPTION_loadvm,
2673     QEMU_OPTION_full_screen,
2674     QEMU_OPTION_pidfile,
2675 };
2676
2677 typedef struct QEMUOption {
2678     const char *name;
2679     int flags;
2680     int index;
2681 } QEMUOption;
2682
2683 const QEMUOption qemu_options[] = {
2684     { "h", 0, QEMU_OPTION_h },
2685
2686     { "fda", HAS_ARG, QEMU_OPTION_fda },
2687     { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2688     { "hda", HAS_ARG, QEMU_OPTION_hda },
2689     { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2690     { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2691     { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2692     { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2693     { "boot", HAS_ARG, QEMU_OPTION_boot },
2694     { "snapshot", 0, QEMU_OPTION_snapshot },
2695     { "m", HAS_ARG, QEMU_OPTION_m },
2696     { "nographic", 0, QEMU_OPTION_nographic },
2697     { "k", HAS_ARG, QEMU_OPTION_k },
2698     { "enable-audio", 0, QEMU_OPTION_enable_audio },
2699
2700     { "nics", HAS_ARG, QEMU_OPTION_nics},
2701     { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2702     { "n", HAS_ARG, QEMU_OPTION_n },
2703     { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2704 #ifdef CONFIG_SLIRP
2705     { "user-net", 0, QEMU_OPTION_user_net },
2706     { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2707 #ifndef _WIN32
2708     { "smb", HAS_ARG, QEMU_OPTION_smb },
2709 #endif
2710     { "redir", HAS_ARG, QEMU_OPTION_redir },
2711 #endif
2712     { "dummy-net", 0, QEMU_OPTION_dummy_net },
2713
2714     { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2715     { "append", HAS_ARG, QEMU_OPTION_append },
2716     { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2717
2718     { "S", 0, QEMU_OPTION_S },
2719     { "s", 0, QEMU_OPTION_s },
2720     { "p", HAS_ARG, QEMU_OPTION_p },
2721     { "d", HAS_ARG, QEMU_OPTION_d },
2722     { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2723     { "L", HAS_ARG, QEMU_OPTION_L },
2724     { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2725 #ifdef TARGET_PPC
2726     { "prep", 0, QEMU_OPTION_prep },
2727     { "g", 1, QEMU_OPTION_g },
2728 #endif
2729     { "localtime", 0, QEMU_OPTION_localtime },
2730     { "isa", 0, QEMU_OPTION_isa },
2731     { "std-vga", 0, QEMU_OPTION_std_vga },
2732     { "monitor", 1, QEMU_OPTION_monitor },
2733     { "serial", 1, QEMU_OPTION_serial },
2734     { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
2735     { "full-screen", 0, QEMU_OPTION_full_screen },
2736     { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
2737
2738     /* temporary options */
2739     { "pci", 0, QEMU_OPTION_pci },
2740     { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2741     { NULL },
2742 };
2743
2744 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2745
2746 /* this stack is only used during signal handling */
2747 #define SIGNAL_STACK_SIZE 32768
2748
2749 static uint8_t *signal_stack;
2750
2751 #endif
2752
2753 /* password input */
2754
2755 static BlockDriverState *get_bdrv(int index)
2756 {
2757     BlockDriverState *bs;
2758
2759     if (index < 4) {
2760         bs = bs_table[index];
2761     } else if (index < 6) {
2762         bs = fd_table[index - 4];
2763     } else {
2764         bs = NULL;
2765     }
2766     return bs;
2767 }
2768
2769 static void read_passwords(void)
2770 {
2771     BlockDriverState *bs;
2772     int i, j;
2773     char password[256];
2774
2775     for(i = 0; i < 6; i++) {
2776         bs = get_bdrv(i);
2777         if (bs && bdrv_is_encrypted(bs)) {
2778             term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
2779             for(j = 0; j < 3; j++) {
2780                 monitor_readline("Password: ", 
2781                                  1, password, sizeof(password));
2782                 if (bdrv_set_key(bs, password) == 0)
2783                     break;
2784                 term_printf("invalid password\n");
2785             }
2786         }
2787     }
2788 }
2789
2790 #define NET_IF_TUN   0
2791 #define NET_IF_USER  1
2792 #define NET_IF_DUMMY 2
2793
2794 int main(int argc, char **argv)
2795 {
2796 #ifdef CONFIG_GDBSTUB
2797     int use_gdbstub, gdbstub_port;
2798 #endif
2799     int i, has_cdrom;
2800     int snapshot, linux_boot;
2801     CPUState *env;
2802     const char *initrd_filename;
2803     const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2804     const char *kernel_filename, *kernel_cmdline;
2805     DisplayState *ds = &display_state;
2806     int cyls, heads, secs, translation;
2807     int start_emulation = 1;
2808     uint8_t macaddr[6];
2809     int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2810     int optind;
2811     const char *r, *optarg;
2812     CharDriverState *monitor_hd;
2813     char monitor_device[128];
2814     char serial_devices[MAX_SERIAL_PORTS][128];
2815     int serial_device_index;
2816     const char *loadvm = NULL;
2817     
2818 #if !defined(CONFIG_SOFTMMU)
2819     /* we never want that malloc() uses mmap() */
2820     mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2821 #endif
2822     initrd_filename = NULL;
2823     for(i = 0; i < MAX_FD; i++)
2824         fd_filename[i] = NULL;
2825     for(i = 0; i < MAX_DISKS; i++)
2826         hd_filename[i] = NULL;
2827     ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2828     vga_ram_size = VGA_RAM_SIZE;
2829     bios_size = BIOS_SIZE;
2830     pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2831 #ifdef CONFIG_GDBSTUB
2832     use_gdbstub = 0;
2833     gdbstub_port = DEFAULT_GDBSTUB_PORT;
2834 #endif
2835     snapshot = 0;
2836     nographic = 0;
2837     kernel_filename = NULL;
2838     kernel_cmdline = "";
2839     has_cdrom = 1;
2840     cyls = heads = secs = 0;
2841     translation = BIOS_ATA_TRANSLATION_AUTO;
2842     pstrcpy(monitor_device, sizeof(monitor_device), "vc");
2843
2844     pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
2845     for(i = 1; i < MAX_SERIAL_PORTS; i++)
2846         serial_devices[i][0] = '\0';
2847     serial_device_index = 0;
2848     
2849     nb_tun_fds = 0;
2850     net_if_type = -1;
2851     nb_nics = 1;
2852     /* default mac address of the first network interface */
2853     macaddr[0] = 0x52;
2854     macaddr[1] = 0x54;
2855     macaddr[2] = 0x00;
2856     macaddr[3] = 0x12;
2857     macaddr[4] = 0x34;
2858     macaddr[5] = 0x56;
2859     
2860     optind = 1;
2861     for(;;) {
2862         if (optind >= argc)
2863             break;
2864         r = argv[optind];
2865         if (r[0] != '-') {
2866             hd_filename[0] = argv[optind++];
2867         } else {
2868             const QEMUOption *popt;
2869
2870             optind++;
2871             popt = qemu_options;
2872             for(;;) {
2873                 if (!popt->name) {
2874                     fprintf(stderr, "%s: invalid option -- '%s'\n", 
2875                             argv[0], r);
2876                     exit(1);
2877                 }
2878                 if (!strcmp(popt->name, r + 1))
2879                     break;
2880                 popt++;
2881             }
2882             if (popt->flags & HAS_ARG) {
2883                 if (optind >= argc) {
2884                     fprintf(stderr, "%s: option '%s' requires an argument\n",
2885                             argv[0], r);
2886                     exit(1);
2887                 }
2888                 optarg = argv[optind++];
2889             } else {
2890                 optarg = NULL;
2891             }
2892
2893             switch(popt->index) {
2894             case QEMU_OPTION_initrd:
2895                 initrd_filename = optarg;
2896                 break;
2897             case QEMU_OPTION_hda:
2898                 hd_filename[0] = optarg;
2899                 break;
2900             case QEMU_OPTION_hdb:
2901                 hd_filename[1] = optarg;
2902                 break;
2903             case QEMU_OPTION_snapshot:
2904                 snapshot = 1;
2905                 break;
2906             case QEMU_OPTION_hdachs:
2907                 {
2908                     const char *p;
2909                     p = optarg;
2910                     cyls = strtol(p, (char **)&p, 0);
2911                     if (cyls < 1 || cyls > 16383)
2912                         goto chs_fail;
2913                     if (*p != ',')
2914                         goto chs_fail;
2915                     p++;
2916                     heads = strtol(p, (char **)&p, 0);
2917                     if (heads < 1 || heads > 16)
2918                         goto chs_fail;
2919                     if (*p != ',')
2920                         goto chs_fail;
2921                     p++;
2922                     secs = strtol(p, (char **)&p, 0);
2923                     if (secs < 1 || secs > 63)
2924                         goto chs_fail;
2925                     if (*p == ',') {
2926                         p++;
2927                         if (!strcmp(p, "none"))
2928                             translation = BIOS_ATA_TRANSLATION_NONE;
2929                         else if (!strcmp(p, "lba"))
2930                             translation = BIOS_ATA_TRANSLATION_LBA;
2931                         else if (!strcmp(p, "auto"))
2932                             translation = BIOS_ATA_TRANSLATION_AUTO;
2933                         else
2934                             goto chs_fail;
2935                     } else if (*p != '\0') {
2936                     chs_fail:
2937                         fprintf(stderr, "qemu: invalid physical CHS format\n");
2938                         exit(1);
2939                     }
2940                 }
2941                 break;
2942             case QEMU_OPTION_nographic:
2943                 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
2944                 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
2945                 nographic = 1;
2946                 break;
2947             case QEMU_OPTION_kernel:
2948                 kernel_filename = optarg;
2949                 break;
2950             case QEMU_OPTION_append:
2951                 kernel_cmdline = optarg;
2952                 break;
2953             case QEMU_OPTION_tun_fd:
2954                 {
2955                     const char *p;
2956                     int fd;
2957                     net_if_type = NET_IF_TUN;
2958                     if (nb_tun_fds < MAX_NICS) {
2959                         fd = strtol(optarg, (char **)&p, 0);
2960                         if (*p != '\0') {
2961                             fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2962                             exit(1);
2963                         }
2964                         tun_fds[nb_tun_fds++] = fd;
2965                     }
2966                 }
2967                 break;
2968             case QEMU_OPTION_hdc:
2969                 hd_filename[2] = optarg;
2970                 has_cdrom = 0;
2971                 break;
2972             case QEMU_OPTION_hdd:
2973                 hd_filename[3] = optarg;
2974                 break;
2975             case QEMU_OPTION_cdrom:
2976                 hd_filename[2] = optarg;
2977                 has_cdrom = 1;
2978                 break;
2979             case QEMU_OPTION_boot:
2980                 boot_device = optarg[0];
2981                 if (boot_device != 'a' && 
2982                     boot_device != 'c' && boot_device != 'd') {
2983                     fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2984                     exit(1);
2985                 }
2986                 break;
2987             case QEMU_OPTION_fda:
2988                 fd_filename[0] = optarg;
2989                 break;
2990             case QEMU_OPTION_fdb:
2991                 fd_filename[1] = optarg;
2992                 break;
2993             case QEMU_OPTION_no_code_copy:
2994                 code_copy_enabled = 0;
2995                 break;
2996             case QEMU_OPTION_nics:
2997                 nb_nics = atoi(optarg);
2998                 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2999                     fprintf(stderr, "qemu: invalid number of network interfaces\n");
3000                     exit(1);
3001                 }
3002                 break;
3003             case QEMU_OPTION_macaddr:
3004                 {
3005                     const char *p;
3006                     int i;
3007                     p = optarg;
3008                     for(i = 0; i < 6; i++) {
3009                         macaddr[i] = strtol(p, (char **)&p, 16);
3010                         if (i == 5) {
3011                             if (*p != '\0') 
3012                                 goto macaddr_error;
3013                         } else {
3014                             if (*p != ':') {
3015                             macaddr_error:
3016                                 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
3017                                 exit(1);
3018                             }
3019                             p++;
3020                         }
3021                     }
3022                 }
3023                 break;
3024 #ifdef CONFIG_SLIRP
3025             case QEMU_OPTION_tftp:
3026                 tftp_prefix = optarg;
3027                 break;
3028 #ifndef _WIN32
3029             case QEMU_OPTION_smb:
3030                 net_slirp_smb(optarg);
3031                 break;
3032 #endif
3033             case QEMU_OPTION_user_net:
3034                 net_if_type = NET_IF_USER;
3035                 break;
3036             case QEMU_OPTION_redir:
3037                 net_slirp_redir(optarg);                
3038                 break;
3039 #endif
3040             case QEMU_OPTION_dummy_net:
3041                 net_if_type = NET_IF_DUMMY;
3042                 break;
3043             case QEMU_OPTION_enable_audio:
3044                 audio_enabled = 1;
3045                 break;
3046             case QEMU_OPTION_h:
3047                 help();
3048                 break;
3049             case QEMU_OPTION_m:
3050                 ram_size = atoi(optarg) * 1024 * 1024;
3051                 if (ram_size <= 0)
3052                     help();
3053                 if (ram_size > PHYS_RAM_MAX_SIZE) {
3054                     fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
3055                             PHYS_RAM_MAX_SIZE / (1024 * 1024));
3056                     exit(1);
3057                 }
3058                 break;
3059             case QEMU_OPTION_d:
3060                 {
3061                     int mask;
3062                     CPULogItem *item;
3063                     
3064                     mask = cpu_str_to_log_mask(optarg);
3065                     if (!mask) {
3066                         printf("Log items (comma separated):\n");
3067                     for(item = cpu_log_items; item->mask != 0; item++) {
3068                         printf("%-10s %s\n", item->name, item->help);
3069                     }
3070                     exit(1);
3071                     }
3072                     cpu_set_log(mask);
3073                 }
3074                 break;
3075             case QEMU_OPTION_n:
3076                 pstrcpy(network_script, sizeof(network_script), optarg);
3077                 break;
3078 #ifdef CONFIG_GDBSTUB
3079             case QEMU_OPTION_s:
3080                 use_gdbstub = 1;
3081                 break;
3082             case QEMU_OPTION_p:
3083                 gdbstub_port = atoi(optarg);
3084                 break;
3085 #endif
3086             case QEMU_OPTION_L:
3087                 bios_dir = optarg;
3088                 break;
3089             case QEMU_OPTION_S:
3090                 start_emulation = 0;
3091                 break;
3092             case QEMU_OPTION_pci:
3093                 pci_enabled = 1;
3094                 break;
3095             case QEMU_OPTION_isa:
3096                 pci_enabled = 0;
3097                 break;
3098             case QEMU_OPTION_prep:
3099                 prep_enabled = 1;
3100                 break;
3101             case QEMU_OPTION_k:
3102                 keyboard_layout = optarg;
3103                 break;
3104             case QEMU_OPTION_localtime:
3105                 rtc_utc = 0;
3106                 break;
3107             case QEMU_OPTION_cirrusvga:
3108                 cirrus_vga_enabled = 1;
3109                 break;
3110             case QEMU_OPTION_std_vga:
3111                 cirrus_vga_enabled = 0;
3112                 break;
3113             case QEMU_OPTION_g:
3114                 {
3115                     const char *p;
3116                     int w, h, depth;
3117                     p = optarg;
3118                     w = strtol(p, (char **)&p, 10);
3119                     if (w <= 0) {
3120                     graphic_error:
3121                         fprintf(stderr, "qemu: invalid resolution or depth\n");
3122                         exit(1);
3123                     }
3124                     if (*p != 'x')
3125                         goto graphic_error;
3126                     p++;
3127                     h = strtol(p, (char **)&p, 10);
3128                     if (h <= 0)
3129                         goto graphic_error;
3130                     if (*p == 'x') {
3131                         p++;
3132                         depth = strtol(p, (char **)&p, 10);
3133                         if (depth != 8 && depth != 15 && depth != 16 && 
3134                             depth != 24 && depth != 32)
3135                             goto graphic_error;
3136                     } else if (*p == '\0') {
3137                         depth = graphic_depth;
3138                     } else {
3139                         goto graphic_error;
3140                     }
3141                     
3142                     graphic_width = w;
3143                     graphic_height = h;
3144                     graphic_depth = depth;
3145                 }
3146                 break;
3147             case QEMU_OPTION_monitor:
3148                 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
3149                 break;
3150             case QEMU_OPTION_serial:
3151                 if (serial_device_index >= MAX_SERIAL_PORTS) {
3152                     fprintf(stderr, "qemu: too many serial ports\n");
3153                     exit(1);
3154                 }
3155                 pstrcpy(serial_devices[serial_device_index], 
3156                         sizeof(serial_devices[0]), optarg);
3157                 serial_device_index++;
3158                 break;
3159             case QEMU_OPTION_loadvm:
3160                 loadvm = optarg;
3161                 break;
3162             case QEMU_OPTION_full_screen:
3163                 full_screen = 1;
3164                 break;
3165             case QEMU_OPTION_pidfile:
3166                 create_pidfile(optarg);
3167                 break;
3168             }
3169         }
3170     }
3171
3172     linux_boot = (kernel_filename != NULL);
3173         
3174     if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
3175         fd_filename[0] == '\0')
3176         help();
3177     
3178     /* boot to cd by default if no hard disk */
3179     if (hd_filename[0] == '\0' && boot_device == 'c') {
3180         if (fd_filename[0] != '\0')
3181             boot_device = 'a';
3182         else
3183             boot_device = 'd';
3184     }
3185
3186 #if !defined(CONFIG_SOFTMMU)
3187     /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3188     {
3189         static uint8_t stdout_buf[4096];
3190         setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3191     }
3192 #else
3193     setvbuf(stdout, NULL, _IOLBF, 0);
3194 #endif
3195
3196     /* init host network redirectors */
3197     if (net_if_type == -1) {
3198         net_if_type = NET_IF_TUN;
3199 #if defined(CONFIG_SLIRP)
3200         if (access(network_script, R_OK) < 0) {
3201             net_if_type = NET_IF_USER;
3202         }
3203 #endif
3204     }
3205
3206     for(i = 0; i < nb_nics; i++) {
3207         NetDriverState *nd = &nd_table[i];
3208         nd->index = i;
3209         /* init virtual mac address */
3210         nd->macaddr[0] = macaddr[0];
3211         nd->macaddr[1] = macaddr[1];
3212         nd->macaddr[2] = macaddr[2];
3213         nd->macaddr[3] = macaddr[3];
3214         nd->macaddr[4] = macaddr[4];
3215         nd->macaddr[5] = macaddr[5] + i;
3216         switch(net_if_type) {
3217 #if defined(CONFIG_SLIRP)
3218         case NET_IF_USER:
3219             net_slirp_init(nd);
3220             break;
3221 #endif
3222 #if !defined(_WIN32)
3223         case NET_IF_TUN:
3224             if (i < nb_tun_fds) {
3225                 net_fd_init(nd, tun_fds[i]);
3226             } else {
3227                 if (net_tun_init(nd) < 0)
3228                     net_dummy_init(nd);
3229             }
3230             break;
3231 #endif
3232         case NET_IF_DUMMY:
3233         default:
3234             net_dummy_init(nd);
3235             break;
3236         }
3237     }
3238
3239     /* init the memory */
3240     phys_ram_size = ram_size + vga_ram_size + bios_size;
3241
3242 #ifdef CONFIG_SOFTMMU
3243 #ifdef _BSD
3244     /* mallocs are always aligned on BSD. valloc is better for correctness */
3245     phys_ram_base = valloc(phys_ram_size);
3246 #else
3247     phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
3248 #endif
3249     if (!phys_ram_base) {
3250         fprintf(stderr, "Could not allocate physical memory\n");
3251         exit(1);
3252     }
3253 #else
3254     /* as we must map the same page at several addresses, we must use
3255        a fd */
3256     {
3257         const char *tmpdir;
3258
3259         tmpdir = getenv("QEMU_TMPDIR");
3260         if (!tmpdir)
3261             tmpdir = "/tmp";
3262         snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
3263         if (mkstemp(phys_ram_file) < 0) {
3264             fprintf(stderr, "Could not create temporary memory file '%s'\n", 
3265                     phys_ram_file);
3266             exit(1);
3267         }
3268         phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
3269         if (phys_ram_fd < 0) {
3270             fprintf(stderr, "Could not open temporary memory file '%s'\n", 
3271                     phys_ram_file);
3272             exit(1);
3273         }
3274         ftruncate(phys_ram_fd, phys_ram_size);
3275         unlink(phys_ram_file);
3276         phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
3277                              phys_ram_size, 
3278                              PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
3279                              phys_ram_fd, 0);
3280         if (phys_ram_base == MAP_FAILED) {
3281             fprintf(stderr, "Could not map physical memory\n");
3282             exit(1);
3283         }
3284     }
3285 #endif
3286
3287     /* we always create the cdrom drive, even if no disk is there */
3288     bdrv_init();
3289     if (has_cdrom) {
3290         bs_table[2] = bdrv_new("cdrom");
3291         bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
3292     }
3293
3294     /* open the virtual block devices */
3295     for(i = 0; i < MAX_DISKS; i++) {
3296         if (hd_filename[i]) {
3297             if (!bs_table[i]) {
3298                 char buf[64];
3299                 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3300                 bs_table[i] = bdrv_new(buf);
3301             }
3302             if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3303                 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3304                         hd_filename[i]);
3305                 exit(1);
3306             }
3307             if (i == 0 && cyls != 0) {
3308                 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3309                 bdrv_set_translation_hint(bs_table[i], translation);
3310             }
3311         }
3312     }
3313
3314     /* we always create at least one floppy disk */
3315     fd_table[0] = bdrv_new("fda");
3316     bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3317
3318     for(i = 0; i < MAX_FD; i++) {
3319         if (fd_filename[i]) {
3320             if (!fd_table[i]) {
3321                 char buf[64];
3322                 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3323                 fd_table[i] = bdrv_new(buf);
3324                 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3325             }
3326             if (fd_filename[i] != '\0') {
3327                 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3328                     fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3329                             fd_filename[i]);
3330                     exit(1);
3331                 }
3332             }
3333         }
3334     }
3335
3336     /* init CPU state */
3337     env = cpu_init();
3338     global_env = env;
3339     cpu_single_env = env;
3340
3341     register_savevm("timer", 0, 1, timer_save, timer_load, env);
3342     register_savevm("cpu", 0, 2, cpu_save, cpu_load, env);
3343     register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
3344     qemu_register_reset(main_cpu_reset, global_env);
3345
3346     init_ioports();
3347     cpu_calibrate_ticks();
3348
3349     /* terminal init */
3350     if (nographic) {
3351         dumb_display_init(ds);
3352     } else {
3353 #ifdef CONFIG_SDL
3354         sdl_display_init(ds, full_screen);
3355 #else
3356         dumb_display_init(ds);
3357 #endif
3358     }
3359
3360     vga_console = graphic_console_init(ds);
3361     
3362     monitor_hd = qemu_chr_open(monitor_device);
3363     if (!monitor_hd) {
3364         fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3365         exit(1);
3366     }
3367     monitor_init(monitor_hd, !nographic);
3368
3369     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3370         if (serial_devices[i][0] != '\0') {
3371             serial_hds[i] = qemu_chr_open(serial_devices[i]);
3372             if (!serial_hds[i]) {
3373                 fprintf(stderr, "qemu: could not open serial device '%s'\n", 
3374                         serial_devices[i]);
3375                 exit(1);
3376             }
3377             if (!strcmp(serial_devices[i], "vc"))
3378                 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3379         }
3380     }
3381
3382     /* setup cpu signal handlers for MMU / self modifying code handling */
3383 #if !defined(CONFIG_SOFTMMU)
3384     
3385 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3386     {
3387         stack_t stk;
3388         signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3389         stk.ss_sp = signal_stack;
3390         stk.ss_size = SIGNAL_STACK_SIZE;
3391         stk.ss_flags = 0;
3392
3393         if (sigaltstack(&stk, NULL) < 0) {
3394             perror("sigaltstack");
3395             exit(1);
3396         }
3397     }
3398 #endif
3399     {
3400         struct sigaction act;
3401         
3402         sigfillset(&act.sa_mask);
3403         act.sa_flags = SA_SIGINFO;
3404 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3405         act.sa_flags |= SA_ONSTACK;
3406 #endif
3407         act.sa_sigaction = host_segv_handler;
3408         sigaction(SIGSEGV, &act, NULL);
3409         sigaction(SIGBUS, &act, NULL);
3410 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3411         sigaction(SIGFPE, &act, NULL);
3412 #endif
3413     }
3414 #endif
3415
3416 #ifndef _WIN32
3417     {
3418         struct sigaction act;
3419         sigfillset(&act.sa_mask);
3420         act.sa_flags = 0;
3421         act.sa_handler = SIG_IGN;
3422         sigaction(SIGPIPE, &act, NULL);
3423     }
3424 #endif
3425     init_timers();
3426
3427 #if defined(TARGET_I386)
3428     pc_init(ram_size, vga_ram_size, boot_device,
3429             ds, fd_filename, snapshot,
3430             kernel_filename, kernel_cmdline, initrd_filename);
3431 #elif defined(TARGET_PPC)
3432     ppc_init(ram_size, vga_ram_size, boot_device,
3433              ds, fd_filename, snapshot,
3434              kernel_filename, kernel_cmdline, initrd_filename);
3435 #elif defined(TARGET_SPARC)
3436     sun4m_init(ram_size, vga_ram_size, boot_device,
3437             ds, fd_filename, snapshot,
3438             kernel_filename, kernel_cmdline, initrd_filename);
3439 #endif
3440
3441     gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3442     qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3443
3444 #ifdef CONFIG_GDBSTUB
3445     if (use_gdbstub) {
3446         if (gdbserver_start(gdbstub_port) < 0) {
3447             fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
3448                     gdbstub_port);
3449             exit(1);
3450         } else {
3451             printf("Waiting gdb connection on port %d\n", gdbstub_port);
3452         }
3453     } else 
3454 #endif
3455     if (loadvm)
3456         qemu_loadvm(loadvm);
3457
3458     {
3459         /* XXX: simplify init */
3460         read_passwords();
3461         if (start_emulation) {
3462             vm_start();
3463         }
3464     }
3465     main_loop();
3466     quit_timers();
3467     return 0;
3468 }