update
[qemu] / vl.c
1 /*
2  * QEMU System Emulator
3  * 
4  * Copyright (c) 2003-2005 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 #include <netdb.h>
44 #ifdef _BSD
45 #include <sys/stat.h>
46 #ifndef __APPLE__
47 #include <libutil.h>
48 #endif
49 #else
50 #include <linux/if.h>
51 #include <linux/if_tun.h>
52 #include <pty.h>
53 #include <malloc.h>
54 #include <linux/rtc.h>
55 #include <linux/ppdev.h>
56 #endif
57 #endif
58
59 #if defined(CONFIG_SLIRP)
60 #include "libslirp.h"
61 #endif
62
63 #ifdef _WIN32
64 #include <malloc.h>
65 #include <sys/timeb.h>
66 #include <windows.h>
67 #define getopt_long_only getopt_long
68 #define memalign(align, size) malloc(size)
69 #endif
70
71 #ifdef CONFIG_SDL
72 #ifdef __APPLE__
73 #include <SDL/SDL.h>
74 #endif
75 #endif /* CONFIG_SDL */
76
77 #ifdef CONFIG_COCOA
78 #undef main
79 #define main qemu_main
80 #endif /* CONFIG_COCOA */
81
82 #include "disas.h"
83
84 #include "exec-all.h"
85
86 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
87
88 //#define DEBUG_UNUSED_IOPORT
89 //#define DEBUG_IOPORT
90
91 #if !defined(CONFIG_SOFTMMU)
92 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
93 #else
94 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
95 #endif
96
97 #ifdef TARGET_PPC
98 #define DEFAULT_RAM_SIZE 144
99 #else
100 #define DEFAULT_RAM_SIZE 128
101 #endif
102 /* in ms */
103 #define GUI_REFRESH_INTERVAL 30
104
105 /* XXX: use a two level table to limit memory usage */
106 #define MAX_IOPORTS 65536
107
108 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
109 char phys_ram_file[1024];
110 void *ioport_opaque[MAX_IOPORTS];
111 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
112 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
113 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
114 int vga_ram_size;
115 int bios_size;
116 static DisplayState display_state;
117 int nographic;
118 const char* keyboard_layout = NULL;
119 int64_t ticks_per_sec;
120 int boot_device = 'c';
121 int ram_size;
122 int pit_min_timer_count = 0;
123 int nb_nics;
124 NICInfo nd_table[MAX_NICS];
125 QEMUTimer *gui_timer;
126 int vm_running;
127 int rtc_utc = 1;
128 int cirrus_vga_enabled = 1;
129 #ifdef TARGET_SPARC
130 int graphic_width = 1024;
131 int graphic_height = 768;
132 #else
133 int graphic_width = 800;
134 int graphic_height = 600;
135 #endif
136 int graphic_depth = 15;
137 int full_screen = 0;
138 TextConsole *vga_console;
139 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
140 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
141 #ifdef TARGET_I386
142 int win2k_install_hack = 0;
143 #endif
144 int usb_enabled = 0;
145 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
146 USBDevice *vm_usb_hub;
147 static VLANState *first_vlan;
148 int smp_cpus = 1;
149 #if defined(TARGET_SPARC)
150 #define MAX_CPUS 16
151 #elif defined(TARGET_I386)
152 #define MAX_CPUS 255
153 #else
154 #define MAX_CPUS 1
155 #endif
156
157 /***********************************************************/
158 /* x86 ISA bus support */
159
160 target_phys_addr_t isa_mem_base = 0;
161 PicState2 *isa_pic;
162
163 uint32_t default_ioport_readb(void *opaque, uint32_t address)
164 {
165 #ifdef DEBUG_UNUSED_IOPORT
166     fprintf(stderr, "inb: port=0x%04x\n", address);
167 #endif
168     return 0xff;
169 }
170
171 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
172 {
173 #ifdef DEBUG_UNUSED_IOPORT
174     fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
175 #endif
176 }
177
178 /* default is to make two byte accesses */
179 uint32_t default_ioport_readw(void *opaque, uint32_t address)
180 {
181     uint32_t data;
182     data = ioport_read_table[0][address](ioport_opaque[address], address);
183     address = (address + 1) & (MAX_IOPORTS - 1);
184     data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
185     return data;
186 }
187
188 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
189 {
190     ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
191     address = (address + 1) & (MAX_IOPORTS - 1);
192     ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
193 }
194
195 uint32_t default_ioport_readl(void *opaque, uint32_t address)
196 {
197 #ifdef DEBUG_UNUSED_IOPORT
198     fprintf(stderr, "inl: port=0x%04x\n", address);
199 #endif
200     return 0xffffffff;
201 }
202
203 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
204 {
205 #ifdef DEBUG_UNUSED_IOPORT
206     fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
207 #endif
208 }
209
210 void init_ioports(void)
211 {
212     int i;
213
214     for(i = 0; i < MAX_IOPORTS; i++) {
215         ioport_read_table[0][i] = default_ioport_readb;
216         ioport_write_table[0][i] = default_ioport_writeb;
217         ioport_read_table[1][i] = default_ioport_readw;
218         ioport_write_table[1][i] = default_ioport_writew;
219         ioport_read_table[2][i] = default_ioport_readl;
220         ioport_write_table[2][i] = default_ioport_writel;
221     }
222 }
223
224 /* size is the word size in byte */
225 int register_ioport_read(int start, int length, int size, 
226                          IOPortReadFunc *func, void *opaque)
227 {
228     int i, bsize;
229
230     if (size == 1) {
231         bsize = 0;
232     } else if (size == 2) {
233         bsize = 1;
234     } else if (size == 4) {
235         bsize = 2;
236     } else {
237         hw_error("register_ioport_read: invalid size");
238         return -1;
239     }
240     for(i = start; i < start + length; i += size) {
241         ioport_read_table[bsize][i] = func;
242         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
243             hw_error("register_ioport_read: invalid opaque");
244         ioport_opaque[i] = opaque;
245     }
246     return 0;
247 }
248
249 /* size is the word size in byte */
250 int register_ioport_write(int start, int length, int size, 
251                           IOPortWriteFunc *func, void *opaque)
252 {
253     int i, bsize;
254
255     if (size == 1) {
256         bsize = 0;
257     } else if (size == 2) {
258         bsize = 1;
259     } else if (size == 4) {
260         bsize = 2;
261     } else {
262         hw_error("register_ioport_write: invalid size");
263         return -1;
264     }
265     for(i = start; i < start + length; i += size) {
266         ioport_write_table[bsize][i] = func;
267         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
268             hw_error("register_ioport_read: invalid opaque");
269         ioport_opaque[i] = opaque;
270     }
271     return 0;
272 }
273
274 void isa_unassign_ioport(int start, int length)
275 {
276     int i;
277
278     for(i = start; i < start + length; i++) {
279         ioport_read_table[0][i] = default_ioport_readb;
280         ioport_read_table[1][i] = default_ioport_readw;
281         ioport_read_table[2][i] = default_ioport_readl;
282
283         ioport_write_table[0][i] = default_ioport_writeb;
284         ioport_write_table[1][i] = default_ioport_writew;
285         ioport_write_table[2][i] = default_ioport_writel;
286     }
287 }
288
289 /***********************************************************/
290
291 void pstrcpy(char *buf, int buf_size, const char *str)
292 {
293     int c;
294     char *q = buf;
295
296     if (buf_size <= 0)
297         return;
298
299     for(;;) {
300         c = *str++;
301         if (c == 0 || q >= buf + buf_size - 1)
302             break;
303         *q++ = c;
304     }
305     *q = '\0';
306 }
307
308 /* strcat and truncate. */
309 char *pstrcat(char *buf, int buf_size, const char *s)
310 {
311     int len;
312     len = strlen(buf);
313     if (len < buf_size) 
314         pstrcpy(buf + len, buf_size - len, s);
315     return buf;
316 }
317
318 int strstart(const char *str, const char *val, const char **ptr)
319 {
320     const char *p, *q;
321     p = str;
322     q = val;
323     while (*q != '\0') {
324         if (*p != *q)
325             return 0;
326         p++;
327         q++;
328     }
329     if (ptr)
330         *ptr = p;
331     return 1;
332 }
333
334 /* return the size or -1 if error */
335 int get_image_size(const char *filename)
336 {
337     int fd, size;
338     fd = open(filename, O_RDONLY | O_BINARY);
339     if (fd < 0)
340         return -1;
341     size = lseek(fd, 0, SEEK_END);
342     close(fd);
343     return size;
344 }
345
346 /* return the size or -1 if error */
347 int load_image(const char *filename, uint8_t *addr)
348 {
349     int fd, size;
350     fd = open(filename, O_RDONLY | O_BINARY);
351     if (fd < 0)
352         return -1;
353     size = lseek(fd, 0, SEEK_END);
354     lseek(fd, 0, SEEK_SET);
355     if (read(fd, addr, size) != size) {
356         close(fd);
357         return -1;
358     }
359     close(fd);
360     return size;
361 }
362
363 void cpu_outb(CPUState *env, int addr, int val)
364 {
365 #ifdef DEBUG_IOPORT
366     if (loglevel & CPU_LOG_IOPORT)
367         fprintf(logfile, "outb: %04x %02x\n", addr, val);
368 #endif    
369     ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
370 }
371
372 void cpu_outw(CPUState *env, int addr, int val)
373 {
374 #ifdef DEBUG_IOPORT
375     if (loglevel & CPU_LOG_IOPORT)
376         fprintf(logfile, "outw: %04x %04x\n", addr, val);
377 #endif    
378     ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
379 }
380
381 void cpu_outl(CPUState *env, int addr, int val)
382 {
383 #ifdef DEBUG_IOPORT
384     if (loglevel & CPU_LOG_IOPORT)
385         fprintf(logfile, "outl: %04x %08x\n", addr, val);
386 #endif
387     ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
388 }
389
390 int cpu_inb(CPUState *env, int addr)
391 {
392     int val;
393     val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
394 #ifdef DEBUG_IOPORT
395     if (loglevel & CPU_LOG_IOPORT)
396         fprintf(logfile, "inb : %04x %02x\n", addr, val);
397 #endif
398     return val;
399 }
400
401 int cpu_inw(CPUState *env, int addr)
402 {
403     int val;
404     val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
405 #ifdef DEBUG_IOPORT
406     if (loglevel & CPU_LOG_IOPORT)
407         fprintf(logfile, "inw : %04x %04x\n", addr, val);
408 #endif
409     return val;
410 }
411
412 int cpu_inl(CPUState *env, int addr)
413 {
414     int val;
415     val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
416 #ifdef DEBUG_IOPORT
417     if (loglevel & CPU_LOG_IOPORT)
418         fprintf(logfile, "inl : %04x %08x\n", addr, val);
419 #endif
420     return val;
421 }
422
423 /***********************************************************/
424 void hw_error(const char *fmt, ...)
425 {
426     va_list ap;
427     CPUState *env;
428
429     va_start(ap, fmt);
430     fprintf(stderr, "qemu: hardware error: ");
431     vfprintf(stderr, fmt, ap);
432     fprintf(stderr, "\n");
433     for(env = first_cpu; env != NULL; env = env->next_cpu) {
434         fprintf(stderr, "CPU #%d:\n", env->cpu_index);
435 #ifdef TARGET_I386
436         cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
437 #else
438         cpu_dump_state(env, stderr, fprintf, 0);
439 #endif
440     }
441     va_end(ap);
442     abort();
443 }
444
445 /***********************************************************/
446 /* keyboard/mouse */
447
448 static QEMUPutKBDEvent *qemu_put_kbd_event;
449 static void *qemu_put_kbd_event_opaque;
450 static QEMUPutMouseEvent *qemu_put_mouse_event;
451 static void *qemu_put_mouse_event_opaque;
452
453 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
454 {
455     qemu_put_kbd_event_opaque = opaque;
456     qemu_put_kbd_event = func;
457 }
458
459 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
460 {
461     qemu_put_mouse_event_opaque = opaque;
462     qemu_put_mouse_event = func;
463 }
464
465 void kbd_put_keycode(int keycode)
466 {
467     if (qemu_put_kbd_event) {
468         qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
469     }
470 }
471
472 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
473 {
474     if (qemu_put_mouse_event) {
475         qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
476                              dx, dy, dz, buttons_state);
477     }
478 }
479
480 /***********************************************************/
481 /* timers */
482
483 #if defined(__powerpc__)
484
485 static inline uint32_t get_tbl(void) 
486 {
487     uint32_t tbl;
488     asm volatile("mftb %0" : "=r" (tbl));
489     return tbl;
490 }
491
492 static inline uint32_t get_tbu(void) 
493 {
494         uint32_t tbl;
495         asm volatile("mftbu %0" : "=r" (tbl));
496         return tbl;
497 }
498
499 int64_t cpu_get_real_ticks(void)
500 {
501     uint32_t l, h, h1;
502     /* NOTE: we test if wrapping has occurred */
503     do {
504         h = get_tbu();
505         l = get_tbl();
506         h1 = get_tbu();
507     } while (h != h1);
508     return ((int64_t)h << 32) | l;
509 }
510
511 #elif defined(__i386__)
512
513 int64_t cpu_get_real_ticks(void)
514 {
515     int64_t val;
516     asm volatile ("rdtsc" : "=A" (val));
517     return val;
518 }
519
520 #elif defined(__x86_64__)
521
522 int64_t cpu_get_real_ticks(void)
523 {
524     uint32_t low,high;
525     int64_t val;
526     asm volatile("rdtsc" : "=a" (low), "=d" (high));
527     val = high;
528     val <<= 32;
529     val |= low;
530     return val;
531 }
532
533 #elif defined(__ia64)
534
535 int64_t cpu_get_real_ticks(void)
536 {
537         int64_t val;
538         asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
539         return val;
540 }
541
542 #elif defined(__s390__)
543
544 int64_t cpu_get_real_ticks(void)
545 {
546     int64_t val;
547     asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
548     return val;
549 }
550
551 #else
552 #error unsupported CPU
553 #endif
554
555 static int64_t cpu_ticks_offset;
556 static int cpu_ticks_enabled;
557
558 static inline int64_t cpu_get_ticks(void)
559 {
560     if (!cpu_ticks_enabled) {
561         return cpu_ticks_offset;
562     } else {
563         return cpu_get_real_ticks() + cpu_ticks_offset;
564     }
565 }
566
567 /* enable cpu_get_ticks() */
568 void cpu_enable_ticks(void)
569 {
570     if (!cpu_ticks_enabled) {
571         cpu_ticks_offset -= cpu_get_real_ticks();
572         cpu_ticks_enabled = 1;
573     }
574 }
575
576 /* disable cpu_get_ticks() : the clock is stopped. You must not call
577    cpu_get_ticks() after that.  */
578 void cpu_disable_ticks(void)
579 {
580     if (cpu_ticks_enabled) {
581         cpu_ticks_offset = cpu_get_ticks();
582         cpu_ticks_enabled = 0;
583     }
584 }
585
586 static int64_t get_clock(void)
587 {
588 #ifdef _WIN32
589     struct _timeb tb;
590     _ftime(&tb);
591     return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
592 #else
593     struct timeval tv;
594     gettimeofday(&tv, NULL);
595     return tv.tv_sec * 1000000LL + tv.tv_usec;
596 #endif
597 }
598
599 void cpu_calibrate_ticks(void)
600 {
601     int64_t usec, ticks;
602
603     usec = get_clock();
604     ticks = cpu_get_real_ticks();
605 #ifdef _WIN32
606     Sleep(50);
607 #else
608     usleep(50 * 1000);
609 #endif
610     usec = get_clock() - usec;
611     ticks = cpu_get_real_ticks() - ticks;
612     ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
613 }
614
615 /* compute with 96 bit intermediate result: (a*b)/c */
616 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
617 {
618     union {
619         uint64_t ll;
620         struct {
621 #ifdef WORDS_BIGENDIAN
622             uint32_t high, low;
623 #else
624             uint32_t low, high;
625 #endif            
626         } l;
627     } u, res;
628     uint64_t rl, rh;
629
630     u.ll = a;
631     rl = (uint64_t)u.l.low * (uint64_t)b;
632     rh = (uint64_t)u.l.high * (uint64_t)b;
633     rh += (rl >> 32);
634     res.l.high = rh / c;
635     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
636     return res.ll;
637 }
638
639 #define QEMU_TIMER_REALTIME 0
640 #define QEMU_TIMER_VIRTUAL  1
641
642 struct QEMUClock {
643     int type;
644     /* XXX: add frequency */
645 };
646
647 struct QEMUTimer {
648     QEMUClock *clock;
649     int64_t expire_time;
650     QEMUTimerCB *cb;
651     void *opaque;
652     struct QEMUTimer *next;
653 };
654
655 QEMUClock *rt_clock;
656 QEMUClock *vm_clock;
657
658 static QEMUTimer *active_timers[2];
659 #ifdef _WIN32
660 static MMRESULT timerID;
661 #else
662 /* frequency of the times() clock tick */
663 static int timer_freq;
664 #endif
665
666 QEMUClock *qemu_new_clock(int type)
667 {
668     QEMUClock *clock;
669     clock = qemu_mallocz(sizeof(QEMUClock));
670     if (!clock)
671         return NULL;
672     clock->type = type;
673     return clock;
674 }
675
676 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
677 {
678     QEMUTimer *ts;
679
680     ts = qemu_mallocz(sizeof(QEMUTimer));
681     ts->clock = clock;
682     ts->cb = cb;
683     ts->opaque = opaque;
684     return ts;
685 }
686
687 void qemu_free_timer(QEMUTimer *ts)
688 {
689     qemu_free(ts);
690 }
691
692 /* stop a timer, but do not dealloc it */
693 void qemu_del_timer(QEMUTimer *ts)
694 {
695     QEMUTimer **pt, *t;
696
697     /* NOTE: this code must be signal safe because
698        qemu_timer_expired() can be called from a signal. */
699     pt = &active_timers[ts->clock->type];
700     for(;;) {
701         t = *pt;
702         if (!t)
703             break;
704         if (t == ts) {
705             *pt = t->next;
706             break;
707         }
708         pt = &t->next;
709     }
710 }
711
712 /* modify the current timer so that it will be fired when current_time
713    >= expire_time. The corresponding callback will be called. */
714 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
715 {
716     QEMUTimer **pt, *t;
717
718     qemu_del_timer(ts);
719
720     /* add the timer in the sorted list */
721     /* NOTE: this code must be signal safe because
722        qemu_timer_expired() can be called from a signal. */
723     pt = &active_timers[ts->clock->type];
724     for(;;) {
725         t = *pt;
726         if (!t)
727             break;
728         if (t->expire_time > expire_time) 
729             break;
730         pt = &t->next;
731     }
732     ts->expire_time = expire_time;
733     ts->next = *pt;
734     *pt = ts;
735 }
736
737 int qemu_timer_pending(QEMUTimer *ts)
738 {
739     QEMUTimer *t;
740     for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
741         if (t == ts)
742             return 1;
743     }
744     return 0;
745 }
746
747 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
748 {
749     if (!timer_head)
750         return 0;
751     return (timer_head->expire_time <= current_time);
752 }
753
754 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
755 {
756     QEMUTimer *ts;
757     
758     for(;;) {
759         ts = *ptimer_head;
760         if (!ts || ts->expire_time > current_time)
761             break;
762         /* remove timer from the list before calling the callback */
763         *ptimer_head = ts->next;
764         ts->next = NULL;
765         
766         /* run the callback (the timer list can be modified) */
767         ts->cb(ts->opaque);
768     }
769 }
770
771 int64_t qemu_get_clock(QEMUClock *clock)
772 {
773     switch(clock->type) {
774     case QEMU_TIMER_REALTIME:
775 #ifdef _WIN32
776         return GetTickCount();
777 #else
778         {
779             struct tms tp;
780
781             /* Note that using gettimeofday() is not a good solution
782                for timers because its value change when the date is
783                modified. */
784             if (timer_freq == 100) {
785                 return times(&tp) * 10;
786             } else {
787                 return ((int64_t)times(&tp) * 1000) / timer_freq;
788             }
789         }
790 #endif
791     default:
792     case QEMU_TIMER_VIRTUAL:
793         return cpu_get_ticks();
794     }
795 }
796
797 /* save a timer */
798 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
799 {
800     uint64_t expire_time;
801
802     if (qemu_timer_pending(ts)) {
803         expire_time = ts->expire_time;
804     } else {
805         expire_time = -1;
806     }
807     qemu_put_be64(f, expire_time);
808 }
809
810 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
811 {
812     uint64_t expire_time;
813
814     expire_time = qemu_get_be64(f);
815     if (expire_time != -1) {
816         qemu_mod_timer(ts, expire_time);
817     } else {
818         qemu_del_timer(ts);
819     }
820 }
821
822 static void timer_save(QEMUFile *f, void *opaque)
823 {
824     if (cpu_ticks_enabled) {
825         hw_error("cannot save state if virtual timers are running");
826     }
827     qemu_put_be64s(f, &cpu_ticks_offset);
828     qemu_put_be64s(f, &ticks_per_sec);
829 }
830
831 static int timer_load(QEMUFile *f, void *opaque, int version_id)
832 {
833     if (version_id != 1)
834         return -EINVAL;
835     if (cpu_ticks_enabled) {
836         return -EINVAL;
837     }
838     qemu_get_be64s(f, &cpu_ticks_offset);
839     qemu_get_be64s(f, &ticks_per_sec);
840     return 0;
841 }
842
843 #ifdef _WIN32
844 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
845                                  DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
846 #else
847 static void host_alarm_handler(int host_signum)
848 #endif
849 {
850 #if 0
851 #define DISP_FREQ 1000
852     {
853         static int64_t delta_min = INT64_MAX;
854         static int64_t delta_max, delta_cum, last_clock, delta, ti;
855         static int count;
856         ti = qemu_get_clock(vm_clock);
857         if (last_clock != 0) {
858             delta = ti - last_clock;
859             if (delta < delta_min)
860                 delta_min = delta;
861             if (delta > delta_max)
862                 delta_max = delta;
863             delta_cum += delta;
864             if (++count == DISP_FREQ) {
865                 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
866                        muldiv64(delta_min, 1000000, ticks_per_sec),
867                        muldiv64(delta_max, 1000000, ticks_per_sec),
868                        muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
869                        (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
870                 count = 0;
871                 delta_min = INT64_MAX;
872                 delta_max = 0;
873                 delta_cum = 0;
874             }
875         }
876         last_clock = ti;
877     }
878 #endif
879     if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
880                            qemu_get_clock(vm_clock)) ||
881         qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
882                            qemu_get_clock(rt_clock))) {
883         CPUState *env = cpu_single_env;
884         if (env) {
885             /* stop the currently executing cpu because a timer occured */
886             cpu_interrupt(env, CPU_INTERRUPT_EXIT);
887 #ifdef USE_KQEMU
888             if (env->kqemu_enabled) {
889                 kqemu_cpu_interrupt(env);
890             }
891 #endif
892         }
893     }
894 }
895
896 #ifndef _WIN32
897
898 #if defined(__linux__)
899
900 #define RTC_FREQ 1024
901
902 static int rtc_fd;
903
904 static int start_rtc_timer(void)
905 {
906     rtc_fd = open("/dev/rtc", O_RDONLY);
907     if (rtc_fd < 0)
908         return -1;
909     if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
910         fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
911                 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
912                 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
913         goto fail;
914     }
915     if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
916     fail:
917         close(rtc_fd);
918         return -1;
919     }
920     pit_min_timer_count = PIT_FREQ / RTC_FREQ;
921     return 0;
922 }
923
924 #else
925
926 static int start_rtc_timer(void)
927 {
928     return -1;
929 }
930
931 #endif /* !defined(__linux__) */
932
933 #endif /* !defined(_WIN32) */
934
935 static void init_timers(void)
936 {
937     rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
938     vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
939
940 #ifdef _WIN32
941     {
942         int count=0;
943         timerID = timeSetEvent(1,     // interval (ms)
944                                0,     // resolution
945                                host_alarm_handler, // function
946                                (DWORD)&count,  // user parameter
947                                TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
948         if( !timerID ) {
949             perror("failed timer alarm");
950             exit(1);
951         }
952     }
953     pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
954 #else
955     {
956         struct sigaction act;
957         struct itimerval itv;
958         
959         /* get times() syscall frequency */
960         timer_freq = sysconf(_SC_CLK_TCK);
961         
962         /* timer signal */
963         sigfillset(&act.sa_mask);
964        act.sa_flags = 0;
965 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
966         act.sa_flags |= SA_ONSTACK;
967 #endif
968         act.sa_handler = host_alarm_handler;
969         sigaction(SIGALRM, &act, NULL);
970
971         itv.it_interval.tv_sec = 0;
972         itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
973         itv.it_value.tv_sec = 0;
974         itv.it_value.tv_usec = 10 * 1000;
975         setitimer(ITIMER_REAL, &itv, NULL);
976         /* we probe the tick duration of the kernel to inform the user if
977            the emulated kernel requested a too high timer frequency */
978         getitimer(ITIMER_REAL, &itv);
979
980 #if defined(__linux__)
981         if (itv.it_interval.tv_usec > 1000) {
982             /* try to use /dev/rtc to have a faster timer */
983             if (start_rtc_timer() < 0)
984                 goto use_itimer;
985             /* disable itimer */
986             itv.it_interval.tv_sec = 0;
987             itv.it_interval.tv_usec = 0;
988             itv.it_value.tv_sec = 0;
989             itv.it_value.tv_usec = 0;
990             setitimer(ITIMER_REAL, &itv, NULL);
991
992             /* use the RTC */
993             sigaction(SIGIO, &act, NULL);
994             fcntl(rtc_fd, F_SETFL, O_ASYNC);
995             fcntl(rtc_fd, F_SETOWN, getpid());
996         } else 
997 #endif /* defined(__linux__) */
998         {
999         use_itimer:
1000             pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1001                                    PIT_FREQ) / 1000000;
1002         }
1003     }
1004 #endif
1005 }
1006
1007 void quit_timers(void)
1008 {
1009 #ifdef _WIN32
1010     timeKillEvent(timerID);
1011 #endif
1012 }
1013
1014 /***********************************************************/
1015 /* character device */
1016
1017 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1018 {
1019     return s->chr_write(s, buf, len);
1020 }
1021
1022 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1023 {
1024     if (!s->chr_ioctl)
1025         return -ENOTSUP;
1026     return s->chr_ioctl(s, cmd, arg);
1027 }
1028
1029 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1030 {
1031     char buf[4096];
1032     va_list ap;
1033     va_start(ap, fmt);
1034     vsnprintf(buf, sizeof(buf), fmt, ap);
1035     qemu_chr_write(s, buf, strlen(buf));
1036     va_end(ap);
1037 }
1038
1039 void qemu_chr_send_event(CharDriverState *s, int event)
1040 {
1041     if (s->chr_send_event)
1042         s->chr_send_event(s, event);
1043 }
1044
1045 void qemu_chr_add_read_handler(CharDriverState *s, 
1046                                IOCanRWHandler *fd_can_read, 
1047                                IOReadHandler *fd_read, void *opaque)
1048 {
1049     s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1050 }
1051              
1052 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1053 {
1054     s->chr_event = chr_event;
1055 }
1056
1057 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1058 {
1059     return len;
1060 }
1061
1062 static void null_chr_add_read_handler(CharDriverState *chr, 
1063                                     IOCanRWHandler *fd_can_read, 
1064                                     IOReadHandler *fd_read, void *opaque)
1065 {
1066 }
1067
1068 CharDriverState *qemu_chr_open_null(void)
1069 {
1070     CharDriverState *chr;
1071
1072     chr = qemu_mallocz(sizeof(CharDriverState));
1073     if (!chr)
1074         return NULL;
1075     chr->chr_write = null_chr_write;
1076     chr->chr_add_read_handler = null_chr_add_read_handler;
1077     return chr;
1078 }
1079
1080 #ifndef _WIN32
1081
1082 typedef struct {
1083     int fd_in, fd_out;
1084     IOCanRWHandler *fd_can_read; 
1085     IOReadHandler *fd_read;
1086     void *fd_opaque;
1087     int max_size;
1088 } FDCharDriver;
1089
1090 #define STDIO_MAX_CLIENTS 2
1091
1092 static int stdio_nb_clients;
1093 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1094
1095 static int unix_write(int fd, const uint8_t *buf, int len1)
1096 {
1097     int ret, len;
1098
1099     len = len1;
1100     while (len > 0) {
1101         ret = write(fd, buf, len);
1102         if (ret < 0) {
1103             if (errno != EINTR && errno != EAGAIN)
1104                 return -1;
1105         } else if (ret == 0) {
1106             break;
1107         } else {
1108             buf += ret;
1109             len -= ret;
1110         }
1111     }
1112     return len1 - len;
1113 }
1114
1115 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1116 {
1117     FDCharDriver *s = chr->opaque;
1118     return unix_write(s->fd_out, buf, len);
1119 }
1120
1121 static int fd_chr_read_poll(void *opaque)
1122 {
1123     CharDriverState *chr = opaque;
1124     FDCharDriver *s = chr->opaque;
1125
1126     s->max_size = s->fd_can_read(s->fd_opaque);
1127     return s->max_size;
1128 }
1129
1130 static void fd_chr_read(void *opaque)
1131 {
1132     CharDriverState *chr = opaque;
1133     FDCharDriver *s = chr->opaque;
1134     int size, len;
1135     uint8_t buf[1024];
1136     
1137     len = sizeof(buf);
1138     if (len > s->max_size)
1139         len = s->max_size;
1140     if (len == 0)
1141         return;
1142     size = read(s->fd_in, buf, len);
1143     if (size > 0) {
1144         s->fd_read(s->fd_opaque, buf, size);
1145     }
1146 }
1147
1148 static void fd_chr_add_read_handler(CharDriverState *chr, 
1149                                     IOCanRWHandler *fd_can_read, 
1150                                     IOReadHandler *fd_read, void *opaque)
1151 {
1152     FDCharDriver *s = chr->opaque;
1153
1154     if (s->fd_in >= 0) {
1155         s->fd_can_read = fd_can_read;
1156         s->fd_read = fd_read;
1157         s->fd_opaque = opaque;
1158         if (nographic && s->fd_in == 0) {
1159         } else {
1160             qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1161                                  fd_chr_read, NULL, chr);
1162         }
1163     }
1164 }
1165
1166 /* open a character device to a unix fd */
1167 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1168 {
1169     CharDriverState *chr;
1170     FDCharDriver *s;
1171
1172     chr = qemu_mallocz(sizeof(CharDriverState));
1173     if (!chr)
1174         return NULL;
1175     s = qemu_mallocz(sizeof(FDCharDriver));
1176     if (!s) {
1177         free(chr);
1178         return NULL;
1179     }
1180     s->fd_in = fd_in;
1181     s->fd_out = fd_out;
1182     chr->opaque = s;
1183     chr->chr_write = fd_chr_write;
1184     chr->chr_add_read_handler = fd_chr_add_read_handler;
1185     return chr;
1186 }
1187
1188 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1189 {
1190     int fd_out;
1191
1192     fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY);
1193     if (fd_out < 0)
1194         return NULL;
1195     return qemu_chr_open_fd(-1, fd_out);
1196 }
1197
1198 CharDriverState *qemu_chr_open_pipe(const char *filename)
1199 {
1200     int fd;
1201
1202     fd = open(filename, O_RDWR | O_BINARY);
1203     if (fd < 0)
1204         return NULL;
1205     return qemu_chr_open_fd(fd, fd);
1206 }
1207
1208
1209 /* for STDIO, we handle the case where several clients use it
1210    (nographic mode) */
1211
1212 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1213
1214 #define TERM_FIFO_MAX_SIZE 1
1215
1216 static int term_got_escape, client_index;
1217 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1218 int term_fifo_size;
1219
1220 void term_print_help(void)
1221 {
1222     printf("\n"
1223            "C-a h    print this help\n"
1224            "C-a x    exit emulator\n"
1225            "C-a s    save disk data back to file (if -snapshot)\n"
1226            "C-a b    send break (magic sysrq)\n"
1227            "C-a c    switch between console and monitor\n"
1228            "C-a C-a  send C-a\n"
1229            );
1230 }
1231
1232 /* called when a char is received */
1233 static void stdio_received_byte(int ch)
1234 {
1235     if (term_got_escape) {
1236         term_got_escape = 0;
1237         switch(ch) {
1238         case 'h':
1239             term_print_help();
1240             break;
1241         case 'x':
1242             exit(0);
1243             break;
1244         case 's': 
1245             {
1246                 int i;
1247                 for (i = 0; i < MAX_DISKS; i++) {
1248                     if (bs_table[i])
1249                         bdrv_commit(bs_table[i]);
1250                 }
1251             }
1252             break;
1253         case 'b':
1254             if (client_index < stdio_nb_clients) {
1255                 CharDriverState *chr;
1256                 FDCharDriver *s;
1257
1258                 chr = stdio_clients[client_index];
1259                 s = chr->opaque;
1260                 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1261             }
1262             break;
1263         case 'c':
1264             client_index++;
1265             if (client_index >= stdio_nb_clients)
1266                 client_index = 0;
1267             if (client_index == 0) {
1268                 /* send a new line in the monitor to get the prompt */
1269                 ch = '\r';
1270                 goto send_char;
1271             }
1272             break;
1273         case TERM_ESCAPE:
1274             goto send_char;
1275         }
1276     } else if (ch == TERM_ESCAPE) {
1277         term_got_escape = 1;
1278     } else {
1279     send_char:
1280         if (client_index < stdio_nb_clients) {
1281             uint8_t buf[1];
1282             CharDriverState *chr;
1283             FDCharDriver *s;
1284             
1285             chr = stdio_clients[client_index];
1286             s = chr->opaque;
1287             if (s->fd_can_read(s->fd_opaque) > 0) {
1288                 buf[0] = ch;
1289                 s->fd_read(s->fd_opaque, buf, 1);
1290             } else if (term_fifo_size == 0) {
1291                 term_fifo[term_fifo_size++] = ch;
1292             }
1293         }
1294     }
1295 }
1296
1297 static int stdio_read_poll(void *opaque)
1298 {
1299     CharDriverState *chr;
1300     FDCharDriver *s;
1301
1302     if (client_index < stdio_nb_clients) {
1303         chr = stdio_clients[client_index];
1304         s = chr->opaque;
1305         /* try to flush the queue if needed */
1306         if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1307             s->fd_read(s->fd_opaque, term_fifo, 1);
1308             term_fifo_size = 0;
1309         }
1310         /* see if we can absorb more chars */
1311         if (term_fifo_size == 0)
1312             return 1;
1313         else
1314             return 0;
1315     } else {
1316         return 1;
1317     }
1318 }
1319
1320 static void stdio_read(void *opaque)
1321 {
1322     int size;
1323     uint8_t buf[1];
1324     
1325     size = read(0, buf, 1);
1326     if (size > 0)
1327         stdio_received_byte(buf[0]);
1328 }
1329
1330 /* init terminal so that we can grab keys */
1331 static struct termios oldtty;
1332 static int old_fd0_flags;
1333
1334 static void term_exit(void)
1335 {
1336     tcsetattr (0, TCSANOW, &oldtty);
1337     fcntl(0, F_SETFL, old_fd0_flags);
1338 }
1339
1340 static void term_init(void)
1341 {
1342     struct termios tty;
1343
1344     tcgetattr (0, &tty);
1345     oldtty = tty;
1346     old_fd0_flags = fcntl(0, F_GETFL);
1347
1348     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1349                           |INLCR|IGNCR|ICRNL|IXON);
1350     tty.c_oflag |= OPOST;
1351     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1352     /* if graphical mode, we allow Ctrl-C handling */
1353     if (nographic)
1354         tty.c_lflag &= ~ISIG;
1355     tty.c_cflag &= ~(CSIZE|PARENB);
1356     tty.c_cflag |= CS8;
1357     tty.c_cc[VMIN] = 1;
1358     tty.c_cc[VTIME] = 0;
1359     
1360     tcsetattr (0, TCSANOW, &tty);
1361
1362     atexit(term_exit);
1363
1364     fcntl(0, F_SETFL, O_NONBLOCK);
1365 }
1366
1367 CharDriverState *qemu_chr_open_stdio(void)
1368 {
1369     CharDriverState *chr;
1370
1371     if (nographic) {
1372         if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1373             return NULL;
1374         chr = qemu_chr_open_fd(0, 1);
1375         if (stdio_nb_clients == 0)
1376             qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1377         client_index = stdio_nb_clients;
1378     } else {
1379         if (stdio_nb_clients != 0)
1380             return NULL;
1381         chr = qemu_chr_open_fd(0, 1);
1382     }
1383     stdio_clients[stdio_nb_clients++] = chr;
1384     if (stdio_nb_clients == 1) {
1385         /* set the terminal in raw mode */
1386         term_init();
1387     }
1388     return chr;
1389 }
1390
1391 #if defined(__linux__)
1392 CharDriverState *qemu_chr_open_pty(void)
1393 {
1394     struct termios tty;
1395     char slave_name[1024];
1396     int master_fd, slave_fd;
1397     
1398     /* Not satisfying */
1399     if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1400         return NULL;
1401     }
1402     
1403     /* Disabling local echo and line-buffered output */
1404     tcgetattr (master_fd, &tty);
1405     tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1406     tty.c_cc[VMIN] = 1;
1407     tty.c_cc[VTIME] = 0;
1408     tcsetattr (master_fd, TCSAFLUSH, &tty);
1409
1410     fprintf(stderr, "char device redirected to %s\n", slave_name);
1411     return qemu_chr_open_fd(master_fd, master_fd);
1412 }
1413
1414 static void tty_serial_init(int fd, int speed, 
1415                             int parity, int data_bits, int stop_bits)
1416 {
1417     struct termios tty;
1418     speed_t spd;
1419
1420 #if 0
1421     printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1422            speed, parity, data_bits, stop_bits);
1423 #endif
1424     tcgetattr (fd, &tty);
1425
1426     switch(speed) {
1427     case 50:
1428         spd = B50;
1429         break;
1430     case 75:
1431         spd = B75;
1432         break;
1433     case 300:
1434         spd = B300;
1435         break;
1436     case 600:
1437         spd = B600;
1438         break;
1439     case 1200:
1440         spd = B1200;
1441         break;
1442     case 2400:
1443         spd = B2400;
1444         break;
1445     case 4800:
1446         spd = B4800;
1447         break;
1448     case 9600:
1449         spd = B9600;
1450         break;
1451     case 19200:
1452         spd = B19200;
1453         break;
1454     case 38400:
1455         spd = B38400;
1456         break;
1457     case 57600:
1458         spd = B57600;
1459         break;
1460     default:
1461     case 115200:
1462         spd = B115200;
1463         break;
1464     }
1465
1466     cfsetispeed(&tty, spd);
1467     cfsetospeed(&tty, spd);
1468
1469     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1470                           |INLCR|IGNCR|ICRNL|IXON);
1471     tty.c_oflag |= OPOST;
1472     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1473     tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1474     switch(data_bits) {
1475     default:
1476     case 8:
1477         tty.c_cflag |= CS8;
1478         break;
1479     case 7:
1480         tty.c_cflag |= CS7;
1481         break;
1482     case 6:
1483         tty.c_cflag |= CS6;
1484         break;
1485     case 5:
1486         tty.c_cflag |= CS5;
1487         break;
1488     }
1489     switch(parity) {
1490     default:
1491     case 'N':
1492         break;
1493     case 'E':
1494         tty.c_cflag |= PARENB;
1495         break;
1496     case 'O':
1497         tty.c_cflag |= PARENB | PARODD;
1498         break;
1499     }
1500     
1501     tcsetattr (fd, TCSANOW, &tty);
1502 }
1503
1504 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1505 {
1506     FDCharDriver *s = chr->opaque;
1507     
1508     switch(cmd) {
1509     case CHR_IOCTL_SERIAL_SET_PARAMS:
1510         {
1511             QEMUSerialSetParams *ssp = arg;
1512             tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1513                             ssp->data_bits, ssp->stop_bits);
1514         }
1515         break;
1516     case CHR_IOCTL_SERIAL_SET_BREAK:
1517         {
1518             int enable = *(int *)arg;
1519             if (enable)
1520                 tcsendbreak(s->fd_in, 1);
1521         }
1522         break;
1523     default:
1524         return -ENOTSUP;
1525     }
1526     return 0;
1527 }
1528
1529 CharDriverState *qemu_chr_open_tty(const char *filename)
1530 {
1531     CharDriverState *chr;
1532     int fd;
1533
1534     fd = open(filename, O_RDWR | O_NONBLOCK);
1535     if (fd < 0)
1536         return NULL;
1537     fcntl(fd, F_SETFL, O_NONBLOCK);
1538     tty_serial_init(fd, 115200, 'N', 8, 1);
1539     chr = qemu_chr_open_fd(fd, fd);
1540     if (!chr)
1541         return NULL;
1542     chr->chr_ioctl = tty_serial_ioctl;
1543     return chr;
1544 }
1545
1546 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1547 {
1548     int fd = (int)chr->opaque;
1549     uint8_t b;
1550
1551     switch(cmd) {
1552     case CHR_IOCTL_PP_READ_DATA:
1553         if (ioctl(fd, PPRDATA, &b) < 0)
1554             return -ENOTSUP;
1555         *(uint8_t *)arg = b;
1556         break;
1557     case CHR_IOCTL_PP_WRITE_DATA:
1558         b = *(uint8_t *)arg;
1559         if (ioctl(fd, PPWDATA, &b) < 0)
1560             return -ENOTSUP;
1561         break;
1562     case CHR_IOCTL_PP_READ_CONTROL:
1563         if (ioctl(fd, PPRCONTROL, &b) < 0)
1564             return -ENOTSUP;
1565         *(uint8_t *)arg = b;
1566         break;
1567     case CHR_IOCTL_PP_WRITE_CONTROL:
1568         b = *(uint8_t *)arg;
1569         if (ioctl(fd, PPWCONTROL, &b) < 0)
1570             return -ENOTSUP;
1571         break;
1572     case CHR_IOCTL_PP_READ_STATUS:
1573         if (ioctl(fd, PPRSTATUS, &b) < 0)
1574             return -ENOTSUP;
1575         *(uint8_t *)arg = b;
1576         break;
1577     default:
1578         return -ENOTSUP;
1579     }
1580     return 0;
1581 }
1582
1583 CharDriverState *qemu_chr_open_pp(const char *filename)
1584 {
1585     CharDriverState *chr;
1586     int fd;
1587
1588     fd = open(filename, O_RDWR);
1589     if (fd < 0)
1590         return NULL;
1591
1592     if (ioctl(fd, PPCLAIM) < 0) {
1593         close(fd);
1594         return NULL;
1595     }
1596
1597     chr = qemu_mallocz(sizeof(CharDriverState));
1598     if (!chr) {
1599         close(fd);
1600         return NULL;
1601     }
1602     chr->opaque = (void *)fd;
1603     chr->chr_write = null_chr_write;
1604     chr->chr_add_read_handler = null_chr_add_read_handler;
1605     chr->chr_ioctl = pp_ioctl;
1606     return chr;
1607 }
1608
1609 #else
1610 CharDriverState *qemu_chr_open_pty(void)
1611 {
1612     return NULL;
1613 }
1614 #endif
1615
1616 #endif /* !defined(_WIN32) */
1617
1618 CharDriverState *qemu_chr_open(const char *filename)
1619 {
1620     const char *p;
1621     if (!strcmp(filename, "vc")) {
1622         return text_console_init(&display_state);
1623     } else if (!strcmp(filename, "null")) {
1624         return qemu_chr_open_null();
1625     } else 
1626 #ifndef _WIN32
1627     if (strstart(filename, "file:", &p)) {
1628         return qemu_chr_open_file_out(p);
1629     } else if (strstart(filename, "pipe:", &p)) {
1630         return qemu_chr_open_pipe(p);
1631     } else if (!strcmp(filename, "pty")) {
1632         return qemu_chr_open_pty();
1633     } else if (!strcmp(filename, "stdio")) {
1634         return qemu_chr_open_stdio();
1635     } else 
1636 #endif
1637 #if defined(__linux__)
1638     if (strstart(filename, "/dev/parport", NULL)) {
1639         return qemu_chr_open_pp(filename);
1640     } else 
1641     if (strstart(filename, "/dev/", NULL)) {
1642         return qemu_chr_open_tty(filename);
1643     } else 
1644 #endif
1645     {
1646         return NULL;
1647     }
1648 }
1649
1650 /***********************************************************/
1651 /* network device redirectors */
1652
1653 void hex_dump(FILE *f, const uint8_t *buf, int size)
1654 {
1655     int len, i, j, c;
1656
1657     for(i=0;i<size;i+=16) {
1658         len = size - i;
1659         if (len > 16)
1660             len = 16;
1661         fprintf(f, "%08x ", i);
1662         for(j=0;j<16;j++) {
1663             if (j < len)
1664                 fprintf(f, " %02x", buf[i+j]);
1665             else
1666                 fprintf(f, "   ");
1667         }
1668         fprintf(f, " ");
1669         for(j=0;j<len;j++) {
1670             c = buf[i+j];
1671             if (c < ' ' || c > '~')
1672                 c = '.';
1673             fprintf(f, "%c", c);
1674         }
1675         fprintf(f, "\n");
1676     }
1677 }
1678
1679 static int parse_macaddr(uint8_t *macaddr, const char *p)
1680 {
1681     int i;
1682     for(i = 0; i < 6; i++) {
1683         macaddr[i] = strtol(p, (char **)&p, 16);
1684         if (i == 5) {
1685             if (*p != '\0') 
1686                 return -1;
1687         } else {
1688             if (*p != ':') 
1689                 return -1;
1690             p++;
1691         }
1692     }
1693     return 0;
1694 }
1695
1696 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1697 {
1698     const char *p, *p1;
1699     int len;
1700     p = *pp;
1701     p1 = strchr(p, sep);
1702     if (!p1)
1703         return -1;
1704     len = p1 - p;
1705     p1++;
1706     if (buf_size > 0) {
1707         if (len > buf_size - 1)
1708             len = buf_size - 1;
1709         memcpy(buf, p, len);
1710         buf[len] = '\0';
1711     }
1712     *pp = p1;
1713     return 0;
1714 }
1715
1716 int parse_host_port(struct sockaddr_in *saddr, const char *str)
1717 {
1718     char buf[512];
1719     struct hostent *he;
1720     const char *p, *r;
1721     int port;
1722
1723     p = str;
1724     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1725         return -1;
1726     saddr->sin_family = AF_INET;
1727     if (buf[0] == '\0') {
1728         saddr->sin_addr.s_addr = 0;
1729     } else {
1730         if (isdigit(buf[0])) {
1731             if (!inet_aton(buf, &saddr->sin_addr))
1732                 return -1;
1733         } else {
1734 #ifdef _WIN32
1735             return -1;
1736 #else
1737             if ((he = gethostbyname(buf)) == NULL)
1738                 return - 1;
1739             saddr->sin_addr = *(struct in_addr *)he->h_addr;
1740 #endif
1741         }
1742     }
1743     port = strtol(p, (char **)&r, 0);
1744     if (r == p)
1745         return -1;
1746     saddr->sin_port = htons(port);
1747     return 0;
1748 }
1749
1750 /* find or alloc a new VLAN */
1751 VLANState *qemu_find_vlan(int id)
1752 {
1753     VLANState **pvlan, *vlan;
1754     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1755         if (vlan->id == id)
1756             return vlan;
1757     }
1758     vlan = qemu_mallocz(sizeof(VLANState));
1759     if (!vlan)
1760         return NULL;
1761     vlan->id = id;
1762     vlan->next = NULL;
1763     pvlan = &first_vlan;
1764     while (*pvlan != NULL)
1765         pvlan = &(*pvlan)->next;
1766     *pvlan = vlan;
1767     return vlan;
1768 }
1769
1770 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
1771                                       IOReadHandler *fd_read, void *opaque)
1772 {
1773     VLANClientState *vc, **pvc;
1774     vc = qemu_mallocz(sizeof(VLANClientState));
1775     if (!vc)
1776         return NULL;
1777     vc->fd_read = fd_read;
1778     vc->opaque = opaque;
1779     vc->vlan = vlan;
1780
1781     vc->next = NULL;
1782     pvc = &vlan->first_client;
1783     while (*pvc != NULL)
1784         pvc = &(*pvc)->next;
1785     *pvc = vc;
1786     return vc;
1787 }
1788
1789 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
1790 {
1791     VLANState *vlan = vc1->vlan;
1792     VLANClientState *vc;
1793
1794 #if 0
1795     printf("vlan %d send:\n", vlan->id);
1796     hex_dump(stdout, buf, size);
1797 #endif
1798     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1799         if (vc != vc1) {
1800             vc->fd_read(vc->opaque, buf, size);
1801         }
1802     }
1803 }
1804
1805 #if defined(CONFIG_SLIRP)
1806
1807 /* slirp network adapter */
1808
1809 static int slirp_inited;
1810 static VLANClientState *slirp_vc;
1811
1812 int slirp_can_output(void)
1813 {
1814     return 1;
1815 }
1816
1817 void slirp_output(const uint8_t *pkt, int pkt_len)
1818 {
1819 #if 0
1820     printf("slirp output:\n");
1821     hex_dump(stdout, pkt, pkt_len);
1822 #endif
1823     qemu_send_packet(slirp_vc, pkt, pkt_len);
1824 }
1825
1826 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
1827 {
1828 #if 0
1829     printf("slirp input:\n");
1830     hex_dump(stdout, buf, size);
1831 #endif
1832     slirp_input(buf, size);
1833 }
1834
1835 static int net_slirp_init(VLANState *vlan)
1836 {
1837     if (!slirp_inited) {
1838         slirp_inited = 1;
1839         slirp_init();
1840     }
1841     slirp_vc = qemu_new_vlan_client(vlan, 
1842                                     slirp_receive, NULL);
1843     snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
1844     return 0;
1845 }
1846
1847 static void net_slirp_redir(const char *redir_str)
1848 {
1849     int is_udp;
1850     char buf[256], *r;
1851     const char *p;
1852     struct in_addr guest_addr;
1853     int host_port, guest_port;
1854     
1855     if (!slirp_inited) {
1856         slirp_inited = 1;
1857         slirp_init();
1858     }
1859
1860     p = redir_str;
1861     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1862         goto fail;
1863     if (!strcmp(buf, "tcp")) {
1864         is_udp = 0;
1865     } else if (!strcmp(buf, "udp")) {
1866         is_udp = 1;
1867     } else {
1868         goto fail;
1869     }
1870
1871     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1872         goto fail;
1873     host_port = strtol(buf, &r, 0);
1874     if (r == buf)
1875         goto fail;
1876
1877     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1878         goto fail;
1879     if (buf[0] == '\0') {
1880         pstrcpy(buf, sizeof(buf), "10.0.2.15");
1881     }
1882     if (!inet_aton(buf, &guest_addr))
1883         goto fail;
1884     
1885     guest_port = strtol(p, &r, 0);
1886     if (r == p)
1887         goto fail;
1888     
1889     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1890         fprintf(stderr, "qemu: could not set up redirection\n");
1891         exit(1);
1892     }
1893     return;
1894  fail:
1895     fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1896     exit(1);
1897 }
1898     
1899 #ifndef _WIN32
1900
1901 char smb_dir[1024];
1902
1903 static void smb_exit(void)
1904 {
1905     DIR *d;
1906     struct dirent *de;
1907     char filename[1024];
1908
1909     /* erase all the files in the directory */
1910     d = opendir(smb_dir);
1911     for(;;) {
1912         de = readdir(d);
1913         if (!de)
1914             break;
1915         if (strcmp(de->d_name, ".") != 0 &&
1916             strcmp(de->d_name, "..") != 0) {
1917             snprintf(filename, sizeof(filename), "%s/%s", 
1918                      smb_dir, de->d_name);
1919             unlink(filename);
1920         }
1921     }
1922     closedir(d);
1923     rmdir(smb_dir);
1924 }
1925
1926 /* automatic user mode samba server configuration */
1927 void net_slirp_smb(const char *exported_dir)
1928 {
1929     char smb_conf[1024];
1930     char smb_cmdline[1024];
1931     FILE *f;
1932
1933     if (!slirp_inited) {
1934         slirp_inited = 1;
1935         slirp_init();
1936     }
1937
1938     /* XXX: better tmp dir construction */
1939     snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1940     if (mkdir(smb_dir, 0700) < 0) {
1941         fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1942         exit(1);
1943     }
1944     snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1945     
1946     f = fopen(smb_conf, "w");
1947     if (!f) {
1948         fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1949         exit(1);
1950     }
1951     fprintf(f, 
1952             "[global]\n"
1953             "private dir=%s\n"
1954             "smb ports=0\n"
1955             "socket address=127.0.0.1\n"
1956             "pid directory=%s\n"
1957             "lock directory=%s\n"
1958             "log file=%s/log.smbd\n"
1959             "smb passwd file=%s/smbpasswd\n"
1960             "security = share\n"
1961             "[qemu]\n"
1962             "path=%s\n"
1963             "read only=no\n"
1964             "guest ok=yes\n",
1965             smb_dir,
1966             smb_dir,
1967             smb_dir,
1968             smb_dir,
1969             smb_dir,
1970             exported_dir
1971             );
1972     fclose(f);
1973     atexit(smb_exit);
1974
1975     snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1976              smb_conf);
1977     
1978     slirp_add_exec(0, smb_cmdline, 4, 139);
1979 }
1980
1981 #endif /* !defined(_WIN32) */
1982
1983 #endif /* CONFIG_SLIRP */
1984
1985 #if !defined(_WIN32)
1986
1987 typedef struct TAPState {
1988     VLANClientState *vc;
1989     int fd;
1990 } TAPState;
1991
1992 static void tap_receive(void *opaque, const uint8_t *buf, int size)
1993 {
1994     TAPState *s = opaque;
1995     int ret;
1996     for(;;) {
1997         ret = write(s->fd, buf, size);
1998         if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
1999         } else {
2000             break;
2001         }
2002     }
2003 }
2004
2005 static void tap_send(void *opaque)
2006 {
2007     TAPState *s = opaque;
2008     uint8_t buf[4096];
2009     int size;
2010
2011     size = read(s->fd, buf, sizeof(buf));
2012     if (size > 0) {
2013         qemu_send_packet(s->vc, buf, size);
2014     }
2015 }
2016
2017 /* fd support */
2018
2019 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2020 {
2021     TAPState *s;
2022
2023     s = qemu_mallocz(sizeof(TAPState));
2024     if (!s)
2025         return NULL;
2026     s->fd = fd;
2027     s->vc = qemu_new_vlan_client(vlan, tap_receive, s);
2028     qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2029     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2030     return s;
2031 }
2032
2033 #ifdef _BSD
2034 static int tap_open(char *ifname, int ifname_size)
2035 {
2036     int fd;
2037     char *dev;
2038     struct stat s;
2039
2040     fd = open("/dev/tap", O_RDWR);
2041     if (fd < 0) {
2042         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2043         return -1;
2044     }
2045
2046     fstat(fd, &s);
2047     dev = devname(s.st_rdev, S_IFCHR);
2048     pstrcpy(ifname, ifname_size, dev);
2049
2050     fcntl(fd, F_SETFL, O_NONBLOCK);
2051     return fd;
2052 }
2053 #else
2054 static int tap_open(char *ifname, int ifname_size)
2055 {
2056     struct ifreq ifr;
2057     int fd, ret;
2058     
2059     fd = open("/dev/net/tun", O_RDWR);
2060     if (fd < 0) {
2061         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2062         return -1;
2063     }
2064     memset(&ifr, 0, sizeof(ifr));
2065     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2066     if (ifname[0] != '\0')
2067         pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2068     else
2069         pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2070     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2071     if (ret != 0) {
2072         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2073         close(fd);
2074         return -1;
2075     }
2076     pstrcpy(ifname, ifname_size, ifr.ifr_name);
2077     fcntl(fd, F_SETFL, O_NONBLOCK);
2078     return fd;
2079 }
2080 #endif
2081
2082 static int net_tap_init(VLANState *vlan, const char *ifname1,
2083                         const char *setup_script)
2084 {
2085     TAPState *s;
2086     int pid, status, fd;
2087     char *args[3];
2088     char **parg;
2089     char ifname[128];
2090
2091     if (ifname1 != NULL)
2092         pstrcpy(ifname, sizeof(ifname), ifname1);
2093     else
2094         ifname[0] = '\0';
2095     fd = tap_open(ifname, sizeof(ifname));
2096     if (fd < 0)
2097         return -1;
2098
2099     if (!setup_script)
2100         setup_script = "";
2101     if (setup_script[0] != '\0') {
2102         /* try to launch network init script */
2103         pid = fork();
2104         if (pid >= 0) {
2105             if (pid == 0) {
2106                 parg = args;
2107                 *parg++ = (char *)setup_script;
2108                 *parg++ = ifname;
2109                 *parg++ = NULL;
2110                 execv(setup_script, args);
2111                 _exit(1);
2112             }
2113             while (waitpid(pid, &status, 0) != pid);
2114             if (!WIFEXITED(status) ||
2115                 WEXITSTATUS(status) != 0) {
2116                 fprintf(stderr, "%s: could not launch network script\n",
2117                         setup_script);
2118                 return -1;
2119             }
2120         }
2121     }
2122     s = net_tap_fd_init(vlan, fd);
2123     if (!s)
2124         return -1;
2125     snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
2126              "tap: ifname=%s setup_script=%s", ifname, setup_script);
2127     return 0;
2128 }
2129
2130 /* network connection */
2131 typedef struct NetSocketState {
2132     VLANClientState *vc;
2133     int fd;
2134     int state; /* 0 = getting length, 1 = getting data */
2135     int index;
2136     int packet_len;
2137     uint8_t buf[4096];
2138     struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2139 } NetSocketState;
2140
2141 typedef struct NetSocketListenState {
2142     VLANState *vlan;
2143     int fd;
2144 } NetSocketListenState;
2145
2146 /* XXX: we consider we can send the whole packet without blocking */
2147 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2148 {
2149     NetSocketState *s = opaque;
2150     uint32_t len;
2151     len = htonl(size);
2152
2153     unix_write(s->fd, (const uint8_t *)&len, sizeof(len));
2154     unix_write(s->fd, buf, size);
2155 }
2156
2157 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2158 {
2159     NetSocketState *s = opaque;
2160     sendto(s->fd, buf, size, 0, 
2161            (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2162 }
2163
2164 static void net_socket_send(void *opaque)
2165 {
2166     NetSocketState *s = opaque;
2167     int l, size;
2168     uint8_t buf1[4096];
2169     const uint8_t *buf;
2170
2171     size = read(s->fd, buf1, sizeof(buf1));
2172     if (size < 0) 
2173         return;
2174     if (size == 0) {
2175         /* end of connection */
2176         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2177         return;
2178     }
2179     buf = buf1;
2180     while (size > 0) {
2181         /* reassemble a packet from the network */
2182         switch(s->state) {
2183         case 0:
2184             l = 4 - s->index;
2185             if (l > size)
2186                 l = size;
2187             memcpy(s->buf + s->index, buf, l);
2188             buf += l;
2189             size -= l;
2190             s->index += l;
2191             if (s->index == 4) {
2192                 /* got length */
2193                 s->packet_len = ntohl(*(uint32_t *)s->buf);
2194                 s->index = 0;
2195                 s->state = 1;
2196             }
2197             break;
2198         case 1:
2199             l = s->packet_len - s->index;
2200             if (l > size)
2201                 l = size;
2202             memcpy(s->buf + s->index, buf, l);
2203             s->index += l;
2204             buf += l;
2205             size -= l;
2206             if (s->index >= s->packet_len) {
2207                 qemu_send_packet(s->vc, s->buf, s->packet_len);
2208                 s->index = 0;
2209                 s->state = 0;
2210             }
2211             break;
2212         }
2213     }
2214 }
2215
2216 static void net_socket_send_dgram(void *opaque)
2217 {
2218     NetSocketState *s = opaque;
2219     int size;
2220
2221     size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2222     if (size < 0) 
2223         return;
2224     if (size == 0) {
2225         /* end of connection */
2226         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2227         return;
2228     }
2229     qemu_send_packet(s->vc, s->buf, size);
2230 }
2231
2232 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2233 {
2234     struct ip_mreq imr;
2235     int fd;
2236     int val, ret;
2237     if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2238         fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2239                 inet_ntoa(mcastaddr->sin_addr), ntohl(mcastaddr->sin_addr.s_addr));
2240         return -1;
2241
2242     }
2243     fd = socket(PF_INET, SOCK_DGRAM, 0);
2244     if (fd < 0) {
2245         perror("socket(PF_INET, SOCK_DGRAM)");
2246         return -1;
2247     }
2248
2249     /* Add host to multicast group */
2250     imr.imr_multiaddr = mcastaddr->sin_addr;
2251     imr.imr_interface.s_addr = htonl(INADDR_ANY);
2252
2253     ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *) &imr, sizeof(struct ip_mreq));
2254     if (ret < 0) {
2255         perror("setsockopt(IP_ADD_MEMBERSHIP)");
2256         goto fail;
2257     }
2258
2259     /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2260     val = 1;
2261     ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &val, sizeof(val));
2262     if (ret < 0) {
2263         perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2264         goto fail;
2265     }
2266
2267     ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
2268     if (ret < 0) {
2269         perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2270         goto fail;
2271     }
2272     
2273     ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2274     if (ret < 0) {
2275         perror("bind");
2276         goto fail;
2277     }
2278     
2279     fcntl(fd, F_SETFL, O_NONBLOCK);
2280     return fd;
2281 fail:
2282     if (fd>=0) close(fd);
2283     return -1;
2284 }
2285
2286 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
2287                                           int is_connected)
2288 {
2289     struct sockaddr_in saddr;
2290     int newfd;
2291     socklen_t saddr_len;
2292     NetSocketState *s;
2293
2294     /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2295      * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
2296      * by ONLY ONE process: we must "clone" this dgram socket --jjo
2297      */
2298
2299     if (is_connected) {
2300         if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2301             /* must be bound */
2302             if (saddr.sin_addr.s_addr==0) {
2303                 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2304                         fd);
2305                 return NULL;
2306             }
2307             /* clone dgram socket */
2308             newfd = net_socket_mcast_create(&saddr);
2309             if (newfd < 0) {
2310                 /* error already reported by net_socket_mcast_create() */
2311                 close(fd);
2312                 return NULL;
2313             }
2314             /* clone newfd to fd, close newfd */
2315             dup2(newfd, fd);
2316             close(newfd);
2317         
2318         } else {
2319             fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2320                     fd, strerror(errno));
2321             return NULL;
2322         }
2323     }
2324
2325     s = qemu_mallocz(sizeof(NetSocketState));
2326     if (!s)
2327         return NULL;
2328     s->fd = fd;
2329
2330     s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, s);
2331     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2332
2333     /* mcast: save bound address as dst */
2334     if (is_connected) s->dgram_dst=saddr;
2335
2336     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2337             "socket: fd=%d (%s mcast=%s:%d)", 
2338             fd, is_connected? "cloned" : "",
2339             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2340     return s;
2341 }
2342
2343 static void net_socket_connect(void *opaque)
2344 {
2345     NetSocketState *s = opaque;
2346     qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2347 }
2348
2349 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
2350                                           int is_connected)
2351 {
2352     NetSocketState *s;
2353     s = qemu_mallocz(sizeof(NetSocketState));
2354     if (!s)
2355         return NULL;
2356     s->fd = fd;
2357     s->vc = qemu_new_vlan_client(vlan, 
2358                                  net_socket_receive, s);
2359     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2360              "socket: fd=%d", fd);
2361     if (is_connected) {
2362         net_socket_connect(s);
2363     } else {
2364         qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2365     }
2366     return s;
2367 }
2368
2369 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
2370                                           int is_connected)
2371 {
2372     int so_type=-1, optlen=sizeof(so_type);
2373
2374     if(getsockopt(fd, SOL_SOCKET,SO_TYPE, &so_type, &optlen)< 0) {
2375         fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2376         return NULL;
2377     }
2378     switch(so_type) {
2379     case SOCK_DGRAM:
2380         return net_socket_fd_init_dgram(vlan, fd, is_connected);
2381     case SOCK_STREAM:
2382         return net_socket_fd_init_stream(vlan, fd, is_connected);
2383     default:
2384         /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2385         fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2386         return net_socket_fd_init_stream(vlan, fd, is_connected);
2387     }
2388     return NULL;
2389 }
2390
2391 static void net_socket_accept(void *opaque)
2392 {
2393     NetSocketListenState *s = opaque;    
2394     NetSocketState *s1;
2395     struct sockaddr_in saddr;
2396     socklen_t len;
2397     int fd;
2398
2399     for(;;) {
2400         len = sizeof(saddr);
2401         fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2402         if (fd < 0 && errno != EINTR) {
2403             return;
2404         } else if (fd >= 0) {
2405             break;
2406         }
2407     }
2408     s1 = net_socket_fd_init(s->vlan, fd, 1); 
2409     if (!s1) {
2410         close(fd);
2411     } else {
2412         snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2413                  "socket: connection from %s:%d", 
2414                  inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2415     }
2416 }
2417
2418 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2419 {
2420     NetSocketListenState *s;
2421     int fd, val, ret;
2422     struct sockaddr_in saddr;
2423
2424     if (parse_host_port(&saddr, host_str) < 0)
2425         return -1;
2426     
2427     s = qemu_mallocz(sizeof(NetSocketListenState));
2428     if (!s)
2429         return -1;
2430
2431     fd = socket(PF_INET, SOCK_STREAM, 0);
2432     if (fd < 0) {
2433         perror("socket");
2434         return -1;
2435     }
2436     fcntl(fd, F_SETFL, O_NONBLOCK);
2437
2438     /* allow fast reuse */
2439     val = 1;
2440     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
2441     
2442     ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2443     if (ret < 0) {
2444         perror("bind");
2445         return -1;
2446     }
2447     ret = listen(fd, 0);
2448     if (ret < 0) {
2449         perror("listen");
2450         return -1;
2451     }
2452     s->vlan = vlan;
2453     s->fd = fd;
2454     qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2455     return 0;
2456 }
2457
2458 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2459 {
2460     NetSocketState *s;
2461     int fd, connected, ret;
2462     struct sockaddr_in saddr;
2463
2464     if (parse_host_port(&saddr, host_str) < 0)
2465         return -1;
2466
2467     fd = socket(PF_INET, SOCK_STREAM, 0);
2468     if (fd < 0) {
2469         perror("socket");
2470         return -1;
2471     }
2472     fcntl(fd, F_SETFL, O_NONBLOCK);
2473
2474     connected = 0;
2475     for(;;) {
2476         ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2477         if (ret < 0) {
2478             if (errno == EINTR || errno == EAGAIN) {
2479             } else if (errno == EINPROGRESS) {
2480                 break;
2481             } else {
2482                 perror("connect");
2483                 close(fd);
2484                 return -1;
2485             }
2486         } else {
2487             connected = 1;
2488             break;
2489         }
2490     }
2491     s = net_socket_fd_init(vlan, fd, connected);
2492     if (!s)
2493         return -1;
2494     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2495              "socket: connect to %s:%d", 
2496              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2497     return 0;
2498 }
2499
2500 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
2501 {
2502     NetSocketState *s;
2503     int fd;
2504     struct sockaddr_in saddr;
2505
2506     if (parse_host_port(&saddr, host_str) < 0)
2507         return -1;
2508
2509
2510     fd = net_socket_mcast_create(&saddr);
2511     if (fd < 0)
2512         return -1;
2513
2514     s = net_socket_fd_init(vlan, fd, 0);
2515     if (!s)
2516         return -1;
2517
2518     s->dgram_dst = saddr;
2519     
2520     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2521              "socket: mcast=%s:%d", 
2522              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2523     return 0;
2524
2525 }
2526
2527 #endif /* !_WIN32 */
2528
2529 static int get_param_value(char *buf, int buf_size,
2530                            const char *tag, const char *str)
2531 {
2532     const char *p;
2533     char *q;
2534     char option[128];
2535
2536     p = str;
2537     for(;;) {
2538         q = option;
2539         while (*p != '\0' && *p != '=') {
2540             if ((q - option) < sizeof(option) - 1)
2541                 *q++ = *p;
2542             p++;
2543         }
2544         *q = '\0';
2545         if (*p != '=')
2546             break;
2547         p++;
2548         if (!strcmp(tag, option)) {
2549             q = buf;
2550             while (*p != '\0' && *p != ',') {
2551                 if ((q - buf) < buf_size - 1)
2552                     *q++ = *p;
2553                 p++;
2554             }
2555             *q = '\0';
2556             return q - buf;
2557         } else {
2558             while (*p != '\0' && *p != ',') {
2559                 p++;
2560             }
2561         }
2562         if (*p != ',')
2563             break;
2564         p++;
2565     }
2566     return 0;
2567 }
2568
2569 int net_client_init(const char *str)
2570 {
2571     const char *p;
2572     char *q;
2573     char device[64];
2574     char buf[1024];
2575     int vlan_id, ret;
2576     VLANState *vlan;
2577
2578     p = str;
2579     q = device;
2580     while (*p != '\0' && *p != ',') {
2581         if ((q - device) < sizeof(device) - 1)
2582             *q++ = *p;
2583         p++;
2584     }
2585     *q = '\0';
2586     if (*p == ',')
2587         p++;
2588     vlan_id = 0;
2589     if (get_param_value(buf, sizeof(buf), "vlan", p)) {
2590         vlan_id = strtol(buf, NULL, 0);
2591     }
2592     vlan = qemu_find_vlan(vlan_id);
2593     if (!vlan) {
2594         fprintf(stderr, "Could not create vlan %d\n", vlan_id);
2595         return -1;
2596     }
2597     if (!strcmp(device, "nic")) {
2598         NICInfo *nd;
2599         uint8_t *macaddr;
2600
2601         if (nb_nics >= MAX_NICS) {
2602             fprintf(stderr, "Too Many NICs\n");
2603             return -1;
2604         }
2605         nd = &nd_table[nb_nics];
2606         macaddr = nd->macaddr;
2607         macaddr[0] = 0x52;
2608         macaddr[1] = 0x54;
2609         macaddr[2] = 0x00;
2610         macaddr[3] = 0x12;
2611         macaddr[4] = 0x34;
2612         macaddr[5] = 0x56 + nb_nics;
2613
2614         if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2615             if (parse_macaddr(macaddr, buf) < 0) {
2616                 fprintf(stderr, "invalid syntax for ethernet address\n");
2617                 return -1;
2618             }
2619         }
2620         nd->vlan = vlan;
2621         nb_nics++;
2622         ret = 0;
2623     } else
2624     if (!strcmp(device, "none")) {
2625         /* does nothing. It is needed to signal that no network cards
2626            are wanted */
2627         ret = 0;
2628     } else
2629 #ifdef CONFIG_SLIRP
2630     if (!strcmp(device, "user")) {
2631         ret = net_slirp_init(vlan);
2632     } else
2633 #endif
2634 #ifndef _WIN32
2635     if (!strcmp(device, "tap")) {
2636         char ifname[64];
2637         char setup_script[1024];
2638         int fd;
2639         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2640             fd = strtol(buf, NULL, 0);
2641             ret = -1;
2642             if (net_tap_fd_init(vlan, fd))
2643                 ret = 0;
2644         } else {
2645             get_param_value(ifname, sizeof(ifname), "ifname", p);
2646             if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2647                 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2648             }
2649             ret = net_tap_init(vlan, ifname, setup_script);
2650         }
2651     } else
2652     if (!strcmp(device, "socket")) {
2653         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2654             int fd;
2655             fd = strtol(buf, NULL, 0);
2656             ret = -1;
2657             if (net_socket_fd_init(vlan, fd, 1))
2658                 ret = 0;
2659         } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2660             ret = net_socket_listen_init(vlan, buf);
2661         } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2662             ret = net_socket_connect_init(vlan, buf);
2663         } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
2664             ret = net_socket_mcast_init(vlan, buf);
2665         } else {
2666             fprintf(stderr, "Unknown socket options: %s\n", p);
2667             return -1;
2668         }
2669     } else
2670 #endif
2671     {
2672         fprintf(stderr, "Unknown network device: %s\n", device);
2673         return -1;
2674     }
2675     if (ret < 0) {
2676         fprintf(stderr, "Could not initialize device '%s'\n", device);
2677     }
2678     
2679     return ret;
2680 }
2681
2682 void do_info_network(void)
2683 {
2684     VLANState *vlan;
2685     VLANClientState *vc;
2686
2687     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2688         term_printf("VLAN %d devices:\n", vlan->id);
2689         for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2690             term_printf("  %s\n", vc->info_str);
2691     }
2692 }
2693  
2694 /***********************************************************/
2695 /* USB devices */
2696
2697 static int usb_device_add(const char *devname)
2698 {
2699     const char *p;
2700     USBDevice *dev;
2701     int i;
2702
2703     if (!vm_usb_hub)
2704         return -1;
2705     for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2706         if (!vm_usb_ports[i]->dev)
2707             break;
2708     }
2709     if (i == MAX_VM_USB_PORTS)
2710         return -1;
2711
2712     if (strstart(devname, "host:", &p)) {
2713         dev = usb_host_device_open(p);
2714         if (!dev)
2715             return -1;
2716     } else if (!strcmp(devname, "mouse")) {
2717         dev = usb_mouse_init();
2718         if (!dev)
2719             return -1;
2720     } else {
2721         return -1;
2722     }
2723     usb_attach(vm_usb_ports[i], dev);
2724     return 0;
2725 }
2726
2727 static int usb_device_del(const char *devname)
2728 {
2729     USBDevice *dev;
2730     int bus_num, addr, i;
2731     const char *p;
2732
2733     if (!vm_usb_hub)
2734         return -1;
2735
2736     p = strchr(devname, '.');
2737     if (!p) 
2738         return -1;
2739     bus_num = strtoul(devname, NULL, 0);
2740     addr = strtoul(p + 1, NULL, 0);
2741     if (bus_num != 0)
2742         return -1;
2743     for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2744         dev = vm_usb_ports[i]->dev;
2745         if (dev && dev->addr == addr)
2746             break;
2747     }
2748     if (i == MAX_VM_USB_PORTS)
2749         return -1;
2750     usb_attach(vm_usb_ports[i], NULL);
2751     return 0;
2752 }
2753
2754 void do_usb_add(const char *devname)
2755 {
2756     int ret;
2757     ret = usb_device_add(devname);
2758     if (ret < 0) 
2759         term_printf("Could not add USB device '%s'\n", devname);
2760 }
2761
2762 void do_usb_del(const char *devname)
2763 {
2764     int ret;
2765     ret = usb_device_del(devname);
2766     if (ret < 0) 
2767         term_printf("Could not remove USB device '%s'\n", devname);
2768 }
2769
2770 void usb_info(void)
2771 {
2772     USBDevice *dev;
2773     int i;
2774     const char *speed_str;
2775
2776     if (!vm_usb_hub) {
2777         term_printf("USB support not enabled\n");
2778         return;
2779     }
2780
2781     for(i = 0; i < MAX_VM_USB_PORTS; i++) {
2782         dev = vm_usb_ports[i]->dev;
2783         if (dev) {
2784             term_printf("Hub port %d:\n", i);
2785             switch(dev->speed) {
2786             case USB_SPEED_LOW: 
2787                 speed_str = "1.5"; 
2788                 break;
2789             case USB_SPEED_FULL: 
2790                 speed_str = "12"; 
2791                 break;
2792             case USB_SPEED_HIGH: 
2793                 speed_str = "480"; 
2794                 break;
2795             default:
2796                 speed_str = "?"; 
2797                 break;
2798             }
2799             term_printf("  Device %d.%d, speed %s Mb/s\n", 
2800                         0, dev->addr, speed_str);
2801         }
2802     }
2803 }
2804
2805 /***********************************************************/
2806 /* pid file */
2807
2808 static char *pid_filename;
2809
2810 /* Remove PID file. Called on normal exit */
2811
2812 static void remove_pidfile(void) 
2813 {
2814     unlink (pid_filename);
2815 }
2816
2817 static void create_pidfile(const char *filename)
2818 {
2819     struct stat pidstat;
2820     FILE *f;
2821
2822     /* Try to write our PID to the named file */
2823     if (stat(filename, &pidstat) < 0) {
2824         if (errno == ENOENT) {
2825             if ((f = fopen (filename, "w")) == NULL) {
2826                 perror("Opening pidfile");
2827                 exit(1);
2828             }
2829             fprintf(f, "%d\n", getpid());
2830             fclose(f);
2831             pid_filename = qemu_strdup(filename);
2832             if (!pid_filename) {
2833                 fprintf(stderr, "Could not save PID filename");
2834                 exit(1);
2835             }
2836             atexit(remove_pidfile);
2837         }
2838     } else {
2839         fprintf(stderr, "%s already exists. Remove it and try again.\n", 
2840                 filename);
2841         exit(1);
2842     }
2843 }
2844
2845 /***********************************************************/
2846 /* dumb display */
2847
2848 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2849 {
2850 }
2851
2852 static void dumb_resize(DisplayState *ds, int w, int h)
2853 {
2854 }
2855
2856 static void dumb_refresh(DisplayState *ds)
2857 {
2858     vga_update_display();
2859 }
2860
2861 void dumb_display_init(DisplayState *ds)
2862 {
2863     ds->data = NULL;
2864     ds->linesize = 0;
2865     ds->depth = 0;
2866     ds->dpy_update = dumb_update;
2867     ds->dpy_resize = dumb_resize;
2868     ds->dpy_refresh = dumb_refresh;
2869 }
2870
2871 #if !defined(CONFIG_SOFTMMU)
2872 /***********************************************************/
2873 /* cpu signal handler */
2874 static void host_segv_handler(int host_signum, siginfo_t *info, 
2875                               void *puc)
2876 {
2877     if (cpu_signal_handler(host_signum, info, puc))
2878         return;
2879     if (stdio_nb_clients > 0)
2880         term_exit();
2881     abort();
2882 }
2883 #endif
2884
2885 /***********************************************************/
2886 /* I/O handling */
2887
2888 #define MAX_IO_HANDLERS 64
2889
2890 typedef struct IOHandlerRecord {
2891     int fd;
2892     IOCanRWHandler *fd_read_poll;
2893     IOHandler *fd_read;
2894     IOHandler *fd_write;
2895     void *opaque;
2896     /* temporary data */
2897     struct pollfd *ufd;
2898     struct IOHandlerRecord *next;
2899 } IOHandlerRecord;
2900
2901 static IOHandlerRecord *first_io_handler;
2902
2903 /* XXX: fd_read_poll should be suppressed, but an API change is
2904    necessary in the character devices to suppress fd_can_read(). */
2905 int qemu_set_fd_handler2(int fd, 
2906                          IOCanRWHandler *fd_read_poll, 
2907                          IOHandler *fd_read, 
2908                          IOHandler *fd_write, 
2909                          void *opaque)
2910 {
2911     IOHandlerRecord **pioh, *ioh;
2912
2913     if (!fd_read && !fd_write) {
2914         pioh = &first_io_handler;
2915         for(;;) {
2916             ioh = *pioh;
2917             if (ioh == NULL)
2918                 break;
2919             if (ioh->fd == fd) {
2920                 *pioh = ioh->next;
2921                 break;
2922             }
2923             pioh = &ioh->next;
2924         }
2925     } else {
2926         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2927             if (ioh->fd == fd)
2928                 goto found;
2929         }
2930         ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2931         if (!ioh)
2932             return -1;
2933         ioh->next = first_io_handler;
2934         first_io_handler = ioh;
2935     found:
2936         ioh->fd = fd;
2937         ioh->fd_read_poll = fd_read_poll;
2938         ioh->fd_read = fd_read;
2939         ioh->fd_write = fd_write;
2940         ioh->opaque = opaque;
2941     }
2942     return 0;
2943 }
2944
2945 int qemu_set_fd_handler(int fd, 
2946                         IOHandler *fd_read, 
2947                         IOHandler *fd_write, 
2948                         void *opaque)
2949 {
2950     return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2951 }
2952
2953 /***********************************************************/
2954 /* savevm/loadvm support */
2955
2956 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
2957 {
2958     fwrite(buf, 1, size, f);
2959 }
2960
2961 void qemu_put_byte(QEMUFile *f, int v)
2962 {
2963     fputc(v, f);
2964 }
2965
2966 void qemu_put_be16(QEMUFile *f, unsigned int v)
2967 {
2968     qemu_put_byte(f, v >> 8);
2969     qemu_put_byte(f, v);
2970 }
2971
2972 void qemu_put_be32(QEMUFile *f, unsigned int v)
2973 {
2974     qemu_put_byte(f, v >> 24);
2975     qemu_put_byte(f, v >> 16);
2976     qemu_put_byte(f, v >> 8);
2977     qemu_put_byte(f, v);
2978 }
2979
2980 void qemu_put_be64(QEMUFile *f, uint64_t v)
2981 {
2982     qemu_put_be32(f, v >> 32);
2983     qemu_put_be32(f, v);
2984 }
2985
2986 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
2987 {
2988     return fread(buf, 1, size, f);
2989 }
2990
2991 int qemu_get_byte(QEMUFile *f)
2992 {
2993     int v;
2994     v = fgetc(f);
2995     if (v == EOF)
2996         return 0;
2997     else
2998         return v;
2999 }
3000
3001 unsigned int qemu_get_be16(QEMUFile *f)
3002 {
3003     unsigned int v;
3004     v = qemu_get_byte(f) << 8;
3005     v |= qemu_get_byte(f);
3006     return v;
3007 }
3008
3009 unsigned int qemu_get_be32(QEMUFile *f)
3010 {
3011     unsigned int v;
3012     v = qemu_get_byte(f) << 24;
3013     v |= qemu_get_byte(f) << 16;
3014     v |= qemu_get_byte(f) << 8;
3015     v |= qemu_get_byte(f);
3016     return v;
3017 }
3018
3019 uint64_t qemu_get_be64(QEMUFile *f)
3020 {
3021     uint64_t v;
3022     v = (uint64_t)qemu_get_be32(f) << 32;
3023     v |= qemu_get_be32(f);
3024     return v;
3025 }
3026
3027 int64_t qemu_ftell(QEMUFile *f)
3028 {
3029     return ftell(f);
3030 }
3031
3032 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3033 {
3034     if (fseek(f, pos, whence) < 0)
3035         return -1;
3036     return ftell(f);
3037 }
3038
3039 typedef struct SaveStateEntry {
3040     char idstr[256];
3041     int instance_id;
3042     int version_id;
3043     SaveStateHandler *save_state;
3044     LoadStateHandler *load_state;
3045     void *opaque;
3046     struct SaveStateEntry *next;
3047 } SaveStateEntry;
3048
3049 static SaveStateEntry *first_se;
3050
3051 int register_savevm(const char *idstr, 
3052                     int instance_id, 
3053                     int version_id,
3054                     SaveStateHandler *save_state,
3055                     LoadStateHandler *load_state,
3056                     void *opaque)
3057 {
3058     SaveStateEntry *se, **pse;
3059
3060     se = qemu_malloc(sizeof(SaveStateEntry));
3061     if (!se)
3062         return -1;
3063     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3064     se->instance_id = instance_id;
3065     se->version_id = version_id;
3066     se->save_state = save_state;
3067     se->load_state = load_state;
3068     se->opaque = opaque;
3069     se->next = NULL;
3070
3071     /* add at the end of list */
3072     pse = &first_se;
3073     while (*pse != NULL)
3074         pse = &(*pse)->next;
3075     *pse = se;
3076     return 0;
3077 }
3078
3079 #define QEMU_VM_FILE_MAGIC   0x5145564d
3080 #define QEMU_VM_FILE_VERSION 0x00000001
3081
3082 int qemu_savevm(const char *filename)
3083 {
3084     SaveStateEntry *se;
3085     QEMUFile *f;
3086     int len, len_pos, cur_pos, saved_vm_running, ret;
3087
3088     saved_vm_running = vm_running;
3089     vm_stop(0);
3090
3091     f = fopen(filename, "wb");
3092     if (!f) {
3093         ret = -1;
3094         goto the_end;
3095     }
3096
3097     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3098     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3099
3100     for(se = first_se; se != NULL; se = se->next) {
3101         /* ID string */
3102         len = strlen(se->idstr);
3103         qemu_put_byte(f, len);
3104         qemu_put_buffer(f, se->idstr, len);
3105
3106         qemu_put_be32(f, se->instance_id);
3107         qemu_put_be32(f, se->version_id);
3108
3109         /* record size: filled later */
3110         len_pos = ftell(f);
3111         qemu_put_be32(f, 0);
3112         
3113         se->save_state(f, se->opaque);
3114
3115         /* fill record size */
3116         cur_pos = ftell(f);
3117         len = ftell(f) - len_pos - 4;
3118         fseek(f, len_pos, SEEK_SET);
3119         qemu_put_be32(f, len);
3120         fseek(f, cur_pos, SEEK_SET);
3121     }
3122
3123     fclose(f);
3124     ret = 0;
3125  the_end:
3126     if (saved_vm_running)
3127         vm_start();
3128     return ret;
3129 }
3130
3131 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3132 {
3133     SaveStateEntry *se;
3134
3135     for(se = first_se; se != NULL; se = se->next) {
3136         if (!strcmp(se->idstr, idstr) && 
3137             instance_id == se->instance_id)
3138             return se;
3139     }
3140     return NULL;
3141 }
3142
3143 int qemu_loadvm(const char *filename)
3144 {
3145     SaveStateEntry *se;
3146     QEMUFile *f;
3147     int len, cur_pos, ret, instance_id, record_len, version_id;
3148     int saved_vm_running;
3149     unsigned int v;
3150     char idstr[256];
3151     
3152     saved_vm_running = vm_running;
3153     vm_stop(0);
3154
3155     f = fopen(filename, "rb");
3156     if (!f) {
3157         ret = -1;
3158         goto the_end;
3159     }
3160
3161     v = qemu_get_be32(f);
3162     if (v != QEMU_VM_FILE_MAGIC)
3163         goto fail;
3164     v = qemu_get_be32(f);
3165     if (v != QEMU_VM_FILE_VERSION) {
3166     fail:
3167         fclose(f);
3168         ret = -1;
3169         goto the_end;
3170     }
3171     for(;;) {
3172         len = qemu_get_byte(f);
3173         if (feof(f))
3174             break;
3175         qemu_get_buffer(f, idstr, len);
3176         idstr[len] = '\0';
3177         instance_id = qemu_get_be32(f);
3178         version_id = qemu_get_be32(f);
3179         record_len = qemu_get_be32(f);
3180 #if 0
3181         printf("idstr=%s instance=0x%x version=%d len=%d\n", 
3182                idstr, instance_id, version_id, record_len);
3183 #endif
3184         cur_pos = ftell(f);
3185         se = find_se(idstr, instance_id);
3186         if (!se) {
3187             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
3188                     instance_id, idstr);
3189         } else {
3190             ret = se->load_state(f, se->opaque, version_id);
3191             if (ret < 0) {
3192                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
3193                         instance_id, idstr);
3194             }
3195         }
3196         /* always seek to exact end of record */
3197         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3198     }
3199     fclose(f);
3200     ret = 0;
3201  the_end:
3202     if (saved_vm_running)
3203         vm_start();
3204     return ret;
3205 }
3206
3207 /***********************************************************/
3208 /* cpu save/restore */
3209
3210 #if defined(TARGET_I386)
3211
3212 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3213 {
3214     qemu_put_be32(f, dt->selector);
3215     qemu_put_betl(f, dt->base);
3216     qemu_put_be32(f, dt->limit);
3217     qemu_put_be32(f, dt->flags);
3218 }
3219
3220 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3221 {
3222     dt->selector = qemu_get_be32(f);
3223     dt->base = qemu_get_betl(f);
3224     dt->limit = qemu_get_be32(f);
3225     dt->flags = qemu_get_be32(f);
3226 }
3227
3228 void cpu_save(QEMUFile *f, void *opaque)
3229 {
3230     CPUState *env = opaque;
3231     uint16_t fptag, fpus, fpuc, fpregs_format;
3232     uint32_t hflags;
3233     int i;
3234     
3235     for(i = 0; i < CPU_NB_REGS; i++)
3236         qemu_put_betls(f, &env->regs[i]);
3237     qemu_put_betls(f, &env->eip);
3238     qemu_put_betls(f, &env->eflags);
3239     hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3240     qemu_put_be32s(f, &hflags);
3241     
3242     /* FPU */
3243     fpuc = env->fpuc;
3244     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3245     fptag = 0;
3246     for(i = 0; i < 8; i++) {
3247         fptag |= ((!env->fptags[i]) << i);
3248     }
3249     
3250     qemu_put_be16s(f, &fpuc);
3251     qemu_put_be16s(f, &fpus);
3252     qemu_put_be16s(f, &fptag);
3253
3254 #ifdef USE_X86LDOUBLE
3255     fpregs_format = 0;
3256 #else
3257     fpregs_format = 1;
3258 #endif
3259     qemu_put_be16s(f, &fpregs_format);
3260     
3261     for(i = 0; i < 8; i++) {
3262 #ifdef USE_X86LDOUBLE
3263         {
3264             uint64_t mant;
3265             uint16_t exp;
3266             /* we save the real CPU data (in case of MMX usage only 'mant'
3267                contains the MMX register */
3268             cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3269             qemu_put_be64(f, mant);
3270             qemu_put_be16(f, exp);
3271         }
3272 #else
3273         /* if we use doubles for float emulation, we save the doubles to
3274            avoid losing information in case of MMX usage. It can give
3275            problems if the image is restored on a CPU where long
3276            doubles are used instead. */
3277         qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3278 #endif
3279     }
3280
3281     for(i = 0; i < 6; i++)
3282         cpu_put_seg(f, &env->segs[i]);
3283     cpu_put_seg(f, &env->ldt);
3284     cpu_put_seg(f, &env->tr);
3285     cpu_put_seg(f, &env->gdt);
3286     cpu_put_seg(f, &env->idt);
3287     
3288     qemu_put_be32s(f, &env->sysenter_cs);
3289     qemu_put_be32s(f, &env->sysenter_esp);
3290     qemu_put_be32s(f, &env->sysenter_eip);
3291     
3292     qemu_put_betls(f, &env->cr[0]);
3293     qemu_put_betls(f, &env->cr[2]);
3294     qemu_put_betls(f, &env->cr[3]);
3295     qemu_put_betls(f, &env->cr[4]);
3296     
3297     for(i = 0; i < 8; i++)
3298         qemu_put_betls(f, &env->dr[i]);
3299
3300     /* MMU */
3301     qemu_put_be32s(f, &env->a20_mask);
3302
3303     /* XMM */
3304     qemu_put_be32s(f, &env->mxcsr);
3305     for(i = 0; i < CPU_NB_REGS; i++) {
3306         qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3307         qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3308     }
3309
3310 #ifdef TARGET_X86_64
3311     qemu_put_be64s(f, &env->efer);
3312     qemu_put_be64s(f, &env->star);
3313     qemu_put_be64s(f, &env->lstar);
3314     qemu_put_be64s(f, &env->cstar);
3315     qemu_put_be64s(f, &env->fmask);
3316     qemu_put_be64s(f, &env->kernelgsbase);
3317 #endif
3318 }
3319
3320 #ifdef USE_X86LDOUBLE
3321 /* XXX: add that in a FPU generic layer */
3322 union x86_longdouble {
3323     uint64_t mant;
3324     uint16_t exp;
3325 };
3326
3327 #define MANTD1(fp)      (fp & ((1LL << 52) - 1))
3328 #define EXPBIAS1 1023
3329 #define EXPD1(fp)       ((fp >> 52) & 0x7FF)
3330 #define SIGND1(fp)      ((fp >> 32) & 0x80000000)
3331
3332 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3333 {
3334     int e;
3335     /* mantissa */
3336     p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3337     /* exponent + sign */
3338     e = EXPD1(temp) - EXPBIAS1 + 16383;
3339     e |= SIGND1(temp) >> 16;
3340     p->exp = e;
3341 }
3342 #endif
3343
3344 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3345 {
3346     CPUState *env = opaque;
3347     int i, guess_mmx;
3348     uint32_t hflags;
3349     uint16_t fpus, fpuc, fptag, fpregs_format;
3350
3351     if (version_id != 3)
3352         return -EINVAL;
3353     for(i = 0; i < CPU_NB_REGS; i++)
3354         qemu_get_betls(f, &env->regs[i]);
3355     qemu_get_betls(f, &env->eip);
3356     qemu_get_betls(f, &env->eflags);
3357     qemu_get_be32s(f, &hflags);
3358
3359     qemu_get_be16s(f, &fpuc);
3360     qemu_get_be16s(f, &fpus);
3361     qemu_get_be16s(f, &fptag);
3362     qemu_get_be16s(f, &fpregs_format);
3363     
3364     /* NOTE: we cannot always restore the FPU state if the image come
3365        from a host with a different 'USE_X86LDOUBLE' define. We guess
3366        if we are in an MMX state to restore correctly in that case. */
3367     guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3368     for(i = 0; i < 8; i++) {
3369         uint64_t mant;
3370         uint16_t exp;
3371         
3372         switch(fpregs_format) {
3373         case 0:
3374             mant = qemu_get_be64(f);
3375             exp = qemu_get_be16(f);
3376 #ifdef USE_X86LDOUBLE
3377             env->fpregs[i].d = cpu_set_fp80(mant, exp);
3378 #else
3379             /* difficult case */
3380             if (guess_mmx)
3381                 env->fpregs[i].mmx.MMX_Q(0) = mant;
3382             else
3383                 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3384 #endif
3385             break;
3386         case 1:
3387             mant = qemu_get_be64(f);
3388 #ifdef USE_X86LDOUBLE
3389             {
3390                 union x86_longdouble *p;
3391                 /* difficult case */
3392                 p = (void *)&env->fpregs[i];
3393                 if (guess_mmx) {
3394                     p->mant = mant;
3395                     p->exp = 0xffff;
3396                 } else {
3397                     fp64_to_fp80(p, mant);
3398                 }
3399             }
3400 #else
3401             env->fpregs[i].mmx.MMX_Q(0) = mant;
3402 #endif            
3403             break;
3404         default:
3405             return -EINVAL;
3406         }
3407     }
3408
3409     env->fpuc = fpuc;
3410     /* XXX: restore FPU round state */
3411     env->fpstt = (fpus >> 11) & 7;
3412     env->fpus = fpus & ~0x3800;
3413     fptag ^= 0xff;
3414     for(i = 0; i < 8; i++) {
3415         env->fptags[i] = (fptag >> i) & 1;
3416     }
3417     
3418     for(i = 0; i < 6; i++)
3419         cpu_get_seg(f, &env->segs[i]);
3420     cpu_get_seg(f, &env->ldt);
3421     cpu_get_seg(f, &env->tr);
3422     cpu_get_seg(f, &env->gdt);
3423     cpu_get_seg(f, &env->idt);
3424     
3425     qemu_get_be32s(f, &env->sysenter_cs);
3426     qemu_get_be32s(f, &env->sysenter_esp);
3427     qemu_get_be32s(f, &env->sysenter_eip);
3428     
3429     qemu_get_betls(f, &env->cr[0]);
3430     qemu_get_betls(f, &env->cr[2]);
3431     qemu_get_betls(f, &env->cr[3]);
3432     qemu_get_betls(f, &env->cr[4]);
3433     
3434     for(i = 0; i < 8; i++)
3435         qemu_get_betls(f, &env->dr[i]);
3436
3437     /* MMU */
3438     qemu_get_be32s(f, &env->a20_mask);
3439
3440     qemu_get_be32s(f, &env->mxcsr);
3441     for(i = 0; i < CPU_NB_REGS; i++) {
3442         qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3443         qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3444     }
3445
3446 #ifdef TARGET_X86_64
3447     qemu_get_be64s(f, &env->efer);
3448     qemu_get_be64s(f, &env->star);
3449     qemu_get_be64s(f, &env->lstar);
3450     qemu_get_be64s(f, &env->cstar);
3451     qemu_get_be64s(f, &env->fmask);
3452     qemu_get_be64s(f, &env->kernelgsbase);
3453 #endif
3454
3455     /* XXX: compute hflags from scratch, except for CPL and IIF */
3456     env->hflags = hflags;
3457     tlb_flush(env, 1);
3458     return 0;
3459 }
3460
3461 #elif defined(TARGET_PPC)
3462 void cpu_save(QEMUFile *f, void *opaque)
3463 {
3464 }
3465
3466 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3467 {
3468     return 0;
3469 }
3470
3471 #elif defined(TARGET_MIPS)
3472 void cpu_save(QEMUFile *f, void *opaque)
3473 {
3474 }
3475
3476 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3477 {
3478     return 0;
3479 }
3480
3481 #elif defined(TARGET_SPARC)
3482 void cpu_save(QEMUFile *f, void *opaque)
3483 {
3484     CPUState *env = opaque;
3485     int i;
3486     uint32_t tmp;
3487
3488     for(i = 0; i < 8; i++)
3489         qemu_put_betls(f, &env->gregs[i]);
3490     for(i = 0; i < NWINDOWS * 16; i++)
3491         qemu_put_betls(f, &env->regbase[i]);
3492
3493     /* FPU */
3494     for(i = 0; i < TARGET_FPREGS; i++) {
3495         union {
3496             TARGET_FPREG_T f;
3497             target_ulong i;
3498         } u;
3499         u.f = env->fpr[i];
3500         qemu_put_betl(f, u.i);
3501     }
3502
3503     qemu_put_betls(f, &env->pc);
3504     qemu_put_betls(f, &env->npc);
3505     qemu_put_betls(f, &env->y);
3506     tmp = GET_PSR(env);
3507     qemu_put_be32(f, tmp);
3508     qemu_put_betls(f, &env->fsr);
3509     qemu_put_betls(f, &env->tbr);
3510 #ifndef TARGET_SPARC64
3511     qemu_put_be32s(f, &env->wim);
3512     /* MMU */
3513     for(i = 0; i < 16; i++)
3514         qemu_put_be32s(f, &env->mmuregs[i]);
3515 #endif
3516 }
3517
3518 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3519 {
3520     CPUState *env = opaque;
3521     int i;
3522     uint32_t tmp;
3523
3524     for(i = 0; i < 8; i++)
3525         qemu_get_betls(f, &env->gregs[i]);
3526     for(i = 0; i < NWINDOWS * 16; i++)
3527         qemu_get_betls(f, &env->regbase[i]);
3528
3529     /* FPU */
3530     for(i = 0; i < TARGET_FPREGS; i++) {
3531         union {
3532             TARGET_FPREG_T f;
3533             target_ulong i;
3534         } u;
3535         u.i = qemu_get_betl(f);
3536         env->fpr[i] = u.f;
3537     }
3538
3539     qemu_get_betls(f, &env->pc);
3540     qemu_get_betls(f, &env->npc);
3541     qemu_get_betls(f, &env->y);
3542     tmp = qemu_get_be32(f);
3543     env->cwp = 0; /* needed to ensure that the wrapping registers are
3544                      correctly updated */
3545     PUT_PSR(env, tmp);
3546     qemu_get_betls(f, &env->fsr);
3547     qemu_get_betls(f, &env->tbr);
3548 #ifndef TARGET_SPARC64
3549     qemu_get_be32s(f, &env->wim);
3550     /* MMU */
3551     for(i = 0; i < 16; i++)
3552         qemu_get_be32s(f, &env->mmuregs[i]);
3553 #endif
3554     tlb_flush(env, 1);
3555     return 0;
3556 }
3557
3558 #elif defined(TARGET_ARM)
3559
3560 /* ??? Need to implement these.  */
3561 void cpu_save(QEMUFile *f, void *opaque)
3562 {
3563 }
3564
3565 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3566 {
3567     return 0;
3568 }
3569
3570 #else
3571
3572 #warning No CPU save/restore functions
3573
3574 #endif
3575
3576 /***********************************************************/
3577 /* ram save/restore */
3578
3579 /* we just avoid storing empty pages */
3580 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
3581 {
3582     int i, v;
3583
3584     v = buf[0];
3585     for(i = 1; i < len; i++) {
3586         if (buf[i] != v)
3587             goto normal_save;
3588     }
3589     qemu_put_byte(f, 1);
3590     qemu_put_byte(f, v);
3591     return;
3592  normal_save:
3593     qemu_put_byte(f, 0); 
3594     qemu_put_buffer(f, buf, len);
3595 }
3596
3597 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3598 {
3599     int v;
3600
3601     v = qemu_get_byte(f);
3602     switch(v) {
3603     case 0:
3604         if (qemu_get_buffer(f, buf, len) != len)
3605             return -EIO;
3606         break;
3607     case 1:
3608         v = qemu_get_byte(f);
3609         memset(buf, v, len);
3610         break;
3611     default:
3612         return -EINVAL;
3613     }
3614     return 0;
3615 }
3616
3617 static void ram_save(QEMUFile *f, void *opaque)
3618 {
3619     int i;
3620     qemu_put_be32(f, phys_ram_size);
3621     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3622         ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3623     }
3624 }
3625
3626 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3627 {
3628     int i, ret;
3629
3630     if (version_id != 1)
3631         return -EINVAL;
3632     if (qemu_get_be32(f) != phys_ram_size)
3633         return -EINVAL;
3634     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3635         ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3636         if (ret)
3637             return ret;
3638     }
3639     return 0;
3640 }
3641
3642 /***********************************************************/
3643 /* machine registration */
3644
3645 QEMUMachine *first_machine = NULL;
3646
3647 int qemu_register_machine(QEMUMachine *m)
3648 {
3649     QEMUMachine **pm;
3650     pm = &first_machine;
3651     while (*pm != NULL)
3652         pm = &(*pm)->next;
3653     m->next = NULL;
3654     *pm = m;
3655     return 0;
3656 }
3657
3658 QEMUMachine *find_machine(const char *name)
3659 {
3660     QEMUMachine *m;
3661
3662     for(m = first_machine; m != NULL; m = m->next) {
3663         if (!strcmp(m->name, name))
3664             return m;
3665     }
3666     return NULL;
3667 }
3668
3669 /***********************************************************/
3670 /* main execution loop */
3671
3672 void gui_update(void *opaque)
3673 {
3674     display_state.dpy_refresh(&display_state);
3675     qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
3676 }
3677
3678 struct vm_change_state_entry {
3679     VMChangeStateHandler *cb;
3680     void *opaque;
3681     LIST_ENTRY (vm_change_state_entry) entries;
3682 };
3683
3684 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3685
3686 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3687                                                      void *opaque)
3688 {
3689     VMChangeStateEntry *e;
3690
3691     e = qemu_mallocz(sizeof (*e));
3692     if (!e)
3693         return NULL;
3694
3695     e->cb = cb;
3696     e->opaque = opaque;
3697     LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3698     return e;
3699 }
3700
3701 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3702 {
3703     LIST_REMOVE (e, entries);
3704     qemu_free (e);
3705 }
3706
3707 static void vm_state_notify(int running)
3708 {
3709     VMChangeStateEntry *e;
3710
3711     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3712         e->cb(e->opaque, running);
3713     }
3714 }
3715
3716 /* XXX: support several handlers */
3717 static VMStopHandler *vm_stop_cb;
3718 static void *vm_stop_opaque;
3719
3720 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3721 {
3722     vm_stop_cb = cb;
3723     vm_stop_opaque = opaque;
3724     return 0;
3725 }
3726
3727 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3728 {
3729     vm_stop_cb = NULL;
3730 }
3731
3732 void vm_start(void)
3733 {
3734     if (!vm_running) {
3735         cpu_enable_ticks();
3736         vm_running = 1;
3737         vm_state_notify(1);
3738     }
3739 }
3740
3741 void vm_stop(int reason) 
3742 {
3743     if (vm_running) {
3744         cpu_disable_ticks();
3745         vm_running = 0;
3746         if (reason != 0) {
3747             if (vm_stop_cb) {
3748                 vm_stop_cb(vm_stop_opaque, reason);
3749             }
3750         }
3751         vm_state_notify(0);
3752     }
3753 }
3754
3755 /* reset/shutdown handler */
3756
3757 typedef struct QEMUResetEntry {
3758     QEMUResetHandler *func;
3759     void *opaque;
3760     struct QEMUResetEntry *next;
3761 } QEMUResetEntry;
3762
3763 static QEMUResetEntry *first_reset_entry;
3764 static int reset_requested;
3765 static int shutdown_requested;
3766 static int powerdown_requested;
3767
3768 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3769 {
3770     QEMUResetEntry **pre, *re;
3771
3772     pre = &first_reset_entry;
3773     while (*pre != NULL)
3774         pre = &(*pre)->next;
3775     re = qemu_mallocz(sizeof(QEMUResetEntry));
3776     re->func = func;
3777     re->opaque = opaque;
3778     re->next = NULL;
3779     *pre = re;
3780 }
3781
3782 void qemu_system_reset(void)
3783 {
3784     QEMUResetEntry *re;
3785
3786     /* reset all devices */
3787     for(re = first_reset_entry; re != NULL; re = re->next) {
3788         re->func(re->opaque);
3789     }
3790 }
3791
3792 void qemu_system_reset_request(void)
3793 {
3794     reset_requested = 1;
3795     if (cpu_single_env)
3796         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3797 }
3798
3799 void qemu_system_shutdown_request(void)
3800 {
3801     shutdown_requested = 1;
3802     if (cpu_single_env)
3803         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3804 }
3805
3806 void qemu_system_powerdown_request(void)
3807 {
3808     powerdown_requested = 1;
3809     if (cpu_single_env)
3810         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3811 }
3812
3813 void main_loop_wait(int timeout)
3814 {
3815 #ifndef _WIN32
3816     struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
3817     IOHandlerRecord *ioh, *ioh_next;
3818 #endif
3819     int ret;
3820
3821 #ifdef _WIN32
3822         if (timeout > 0)
3823             Sleep(timeout);
3824 #else
3825         /* poll any events */
3826         /* XXX: separate device handlers from system ones */
3827         pf = ufds;
3828         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3829             pf->events = 0;
3830             pf->fd = ioh->fd;
3831             if (ioh->fd_read &&
3832                 (!ioh->fd_read_poll ||
3833                  ioh->fd_read_poll(ioh->opaque) != 0)) {
3834                 pf->events |= POLLIN;
3835             }
3836             if (ioh->fd_write) {
3837                 pf->events |= POLLOUT;
3838             }
3839             ioh->ufd = pf;
3840             pf++;
3841         }
3842         
3843         ret = poll(ufds, pf - ufds, timeout);
3844         if (ret > 0) {
3845             /* XXX: better handling of removal */
3846             for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
3847                 ioh_next = ioh->next;
3848                 pf = ioh->ufd;
3849                 if (pf->revents & POLLIN) {
3850                     ioh->fd_read(ioh->opaque);
3851                 }
3852                 if (pf->revents & POLLOUT) {
3853                     ioh->fd_write(ioh->opaque);
3854                 }
3855             }
3856         }
3857 #endif /* !defined(_WIN32) */
3858 #if defined(CONFIG_SLIRP)
3859         /* XXX: merge with poll() */
3860         if (slirp_inited) {
3861             fd_set rfds, wfds, xfds;
3862             int nfds;
3863             struct timeval tv;
3864
3865             nfds = -1;
3866             FD_ZERO(&rfds);
3867             FD_ZERO(&wfds);
3868             FD_ZERO(&xfds);
3869             slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3870             tv.tv_sec = 0;
3871             tv.tv_usec = 0;
3872             ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3873             if (ret >= 0) {
3874                 slirp_select_poll(&rfds, &wfds, &xfds);
3875             }
3876         }
3877 #endif
3878
3879         if (vm_running) {
3880             qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
3881                             qemu_get_clock(vm_clock));
3882             /* run dma transfers, if any */
3883             DMA_run();
3884         }
3885
3886         /* real time timers */
3887         qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
3888                         qemu_get_clock(rt_clock));
3889 }
3890
3891 static CPUState *cur_cpu;
3892
3893 int main_loop(void)
3894 {
3895     int ret, timeout;
3896     CPUState *env;
3897
3898     cur_cpu = first_cpu;
3899     for(;;) {
3900         if (vm_running) {
3901
3902             env = cur_cpu;
3903             for(;;) {
3904                 /* get next cpu */
3905                 env = env->next_cpu;
3906                 if (!env)
3907                     env = first_cpu;
3908                 ret = cpu_exec(env);
3909                 if (ret != EXCP_HALTED)
3910                     break;
3911                 /* all CPUs are halted ? */
3912                 if (env == cur_cpu) {
3913                     ret = EXCP_HLT;
3914                     break;
3915                 }
3916             }
3917             cur_cpu = env;
3918
3919             if (shutdown_requested) {
3920                 ret = EXCP_INTERRUPT;
3921                 break;
3922             }
3923             if (reset_requested) {
3924                 reset_requested = 0;
3925                 qemu_system_reset();
3926                 ret = EXCP_INTERRUPT;
3927             }
3928             if (powerdown_requested) {
3929                 powerdown_requested = 0;
3930                 qemu_system_powerdown();
3931                 ret = EXCP_INTERRUPT;
3932             }
3933             if (ret == EXCP_DEBUG) {
3934                 vm_stop(EXCP_DEBUG);
3935             }
3936             /* if hlt instruction, we wait until the next IRQ */
3937             /* XXX: use timeout computed from timers */
3938             if (ret == EXCP_HLT)
3939                 timeout = 10;
3940             else
3941                 timeout = 0;
3942         } else {
3943             timeout = 10;
3944         }
3945         main_loop_wait(timeout);
3946     }
3947     cpu_disable_ticks();
3948     return ret;
3949 }
3950
3951 void help(void)
3952 {
3953     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
3954            "usage: %s [options] [disk_image]\n"
3955            "\n"
3956            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3957            "\n"
3958            "Standard options:\n"
3959            "-M machine      select emulated machine (-M ? for list)\n"
3960            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
3961            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
3962            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
3963            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3964            "-boot [a|c|d]   boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
3965            "-snapshot       write to temporary files instead of disk image files\n"
3966            "-m megs         set virtual RAM size to megs MB [default=%d]\n"
3967            "-smp n          set the number of CPUs to 'n' [default=1]\n"
3968            "-nographic      disable graphical output and redirect serial I/Os to console\n"
3969 #ifndef _WIN32
3970            "-k language     use keyboard layout (for example \"fr\" for French)\n"
3971 #endif
3972 #ifdef HAS_AUDIO
3973            "-audio-help     print list of audio drivers and their options\n"
3974            "-soundhw c1,... enable audio support\n"
3975            "                and only specified sound cards (comma separated list)\n"
3976            "                use -soundhw ? to get the list of supported cards\n"
3977            "                use -soundhw all to enable all of them\n"
3978 #endif
3979            "-localtime      set the real time clock to local time [default=utc]\n"
3980            "-full-screen    start in full screen\n"
3981 #ifdef TARGET_I386
3982            "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
3983 #endif
3984            "-usb            enable the USB driver (will be the default soon)\n"
3985            "-usbdevice name add the host or guest USB device 'name'\n"
3986 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3987            "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
3988 #endif
3989            "\n"
3990            "Network options:\n"
3991            "-net nic[,vlan=n][,macaddr=addr]\n"
3992            "                create a new Network Interface Card and connect it to VLAN 'n'\n"
3993 #ifdef CONFIG_SLIRP
3994            "-net user[,vlan=n]\n"
3995            "                connect the user mode network stack to VLAN 'n'\n"
3996 #endif
3997 #ifndef _WIN32
3998            "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
3999            "                connect the host TAP network interface to VLAN 'n' and use\n"
4000            "                the network script 'file' (default=%s);\n"
4001            "                use 'fd=h' to connect to an already opened TAP interface\n"
4002            "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4003            "                connect the vlan 'n' to another VLAN using a socket connection\n"
4004            "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4005            "                connect the vlan 'n' to multicast maddr and port\n"
4006 #endif
4007            "-net none       use it alone to have zero network devices; if no -net option\n"
4008            "                is provided, the default is '-net nic -net user'\n"
4009            "\n"
4010 #ifdef CONFIG_SLIRP
4011            "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
4012 #ifndef _WIN32
4013            "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
4014 #endif
4015            "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4016            "                redirect TCP or UDP connections from host to guest [-net user]\n"
4017 #endif
4018            "\n"
4019            "Linux boot specific:\n"
4020            "-kernel bzImage use 'bzImage' as kernel image\n"
4021            "-append cmdline use 'cmdline' as kernel command line\n"
4022            "-initrd file    use 'file' as initial ram disk\n"
4023            "\n"
4024            "Debug/Expert options:\n"
4025            "-monitor dev    redirect the monitor to char device 'dev'\n"
4026            "-serial dev     redirect the serial port to char device 'dev'\n"
4027            "-parallel dev   redirect the parallel port to char device 'dev'\n"
4028            "-pidfile file   Write PID to 'file'\n"
4029            "-S              freeze CPU at startup (use 'c' to start execution)\n"
4030            "-s              wait gdb connection to port %d\n"
4031            "-p port         change gdb connection port\n"
4032            "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
4033            "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
4034            "                translation (t=none or lba) (usually qemu can guess them)\n"
4035            "-L path         set the directory for the BIOS and VGA BIOS\n"
4036 #ifdef USE_KQEMU
4037            "-no-kqemu       disable KQEMU kernel module usage\n"
4038 #endif
4039 #ifdef USE_CODE_COPY
4040            "-no-code-copy   disable code copy acceleration\n"
4041 #endif
4042 #ifdef TARGET_I386
4043            "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
4044            "                (default is CL-GD5446 PCI VGA)\n"
4045 #endif
4046            "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
4047            "\n"
4048            "During emulation, the following keys are useful:\n"
4049            "ctrl-alt-f      toggle full screen\n"
4050            "ctrl-alt-n      switch to virtual console 'n'\n"
4051            "ctrl-alt        toggle mouse and keyboard grab\n"
4052            "\n"
4053            "When using -nographic, press 'ctrl-a h' to get some help.\n"
4054            ,
4055 #ifdef CONFIG_SOFTMMU
4056            "qemu",
4057 #else
4058            "qemu-fast",
4059 #endif
4060            DEFAULT_RAM_SIZE,
4061 #ifndef _WIN32
4062            DEFAULT_NETWORK_SCRIPT,
4063 #endif
4064            DEFAULT_GDBSTUB_PORT,
4065            "/tmp/qemu.log");
4066 #ifndef CONFIG_SOFTMMU
4067     printf("\n"
4068            "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4069            "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4070            "PC emulation.\n");
4071 #endif
4072     exit(1);
4073 }
4074
4075 #define HAS_ARG 0x0001
4076
4077 enum {
4078     QEMU_OPTION_h,
4079
4080     QEMU_OPTION_M,
4081     QEMU_OPTION_fda,
4082     QEMU_OPTION_fdb,
4083     QEMU_OPTION_hda,
4084     QEMU_OPTION_hdb,
4085     QEMU_OPTION_hdc,
4086     QEMU_OPTION_hdd,
4087     QEMU_OPTION_cdrom,
4088     QEMU_OPTION_boot,
4089     QEMU_OPTION_snapshot,
4090     QEMU_OPTION_m,
4091     QEMU_OPTION_nographic,
4092 #ifdef HAS_AUDIO
4093     QEMU_OPTION_audio_help,
4094     QEMU_OPTION_soundhw,
4095 #endif
4096
4097     QEMU_OPTION_net,
4098     QEMU_OPTION_tftp,
4099     QEMU_OPTION_smb,
4100     QEMU_OPTION_redir,
4101
4102     QEMU_OPTION_kernel,
4103     QEMU_OPTION_append,
4104     QEMU_OPTION_initrd,
4105
4106     QEMU_OPTION_S,
4107     QEMU_OPTION_s,
4108     QEMU_OPTION_p,
4109     QEMU_OPTION_d,
4110     QEMU_OPTION_hdachs,
4111     QEMU_OPTION_L,
4112     QEMU_OPTION_no_code_copy,
4113     QEMU_OPTION_k,
4114     QEMU_OPTION_localtime,
4115     QEMU_OPTION_cirrusvga,
4116     QEMU_OPTION_g,
4117     QEMU_OPTION_std_vga,
4118     QEMU_OPTION_monitor,
4119     QEMU_OPTION_serial,
4120     QEMU_OPTION_parallel,
4121     QEMU_OPTION_loadvm,
4122     QEMU_OPTION_full_screen,
4123     QEMU_OPTION_pidfile,
4124     QEMU_OPTION_no_kqemu,
4125     QEMU_OPTION_win2k_hack,
4126     QEMU_OPTION_usb,
4127     QEMU_OPTION_usbdevice,
4128     QEMU_OPTION_smp,
4129 };
4130
4131 typedef struct QEMUOption {
4132     const char *name;
4133     int flags;
4134     int index;
4135 } QEMUOption;
4136
4137 const QEMUOption qemu_options[] = {
4138     { "h", 0, QEMU_OPTION_h },
4139
4140     { "M", HAS_ARG, QEMU_OPTION_M },
4141     { "fda", HAS_ARG, QEMU_OPTION_fda },
4142     { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4143     { "hda", HAS_ARG, QEMU_OPTION_hda },
4144     { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4145     { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4146     { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4147     { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4148     { "boot", HAS_ARG, QEMU_OPTION_boot },
4149     { "snapshot", 0, QEMU_OPTION_snapshot },
4150     { "m", HAS_ARG, QEMU_OPTION_m },
4151     { "nographic", 0, QEMU_OPTION_nographic },
4152     { "k", HAS_ARG, QEMU_OPTION_k },
4153 #ifdef HAS_AUDIO
4154     { "audio-help", 0, QEMU_OPTION_audio_help },
4155     { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4156 #endif
4157
4158     { "net", HAS_ARG, QEMU_OPTION_net},
4159 #ifdef CONFIG_SLIRP
4160     { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4161 #ifndef _WIN32
4162     { "smb", HAS_ARG, QEMU_OPTION_smb },
4163 #endif
4164     { "redir", HAS_ARG, QEMU_OPTION_redir },
4165 #endif
4166
4167     { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4168     { "append", HAS_ARG, QEMU_OPTION_append },
4169     { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4170
4171     { "S", 0, QEMU_OPTION_S },
4172     { "s", 0, QEMU_OPTION_s },
4173     { "p", HAS_ARG, QEMU_OPTION_p },
4174     { "d", HAS_ARG, QEMU_OPTION_d },
4175     { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4176     { "L", HAS_ARG, QEMU_OPTION_L },
4177     { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4178 #ifdef USE_KQEMU
4179     { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4180 #endif
4181 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4182     { "g", 1, QEMU_OPTION_g },
4183 #endif
4184     { "localtime", 0, QEMU_OPTION_localtime },
4185     { "std-vga", 0, QEMU_OPTION_std_vga },
4186     { "monitor", 1, QEMU_OPTION_monitor },
4187     { "serial", 1, QEMU_OPTION_serial },
4188     { "parallel", 1, QEMU_OPTION_parallel },
4189     { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4190     { "full-screen", 0, QEMU_OPTION_full_screen },
4191     { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4192     { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4193     { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4194     { "smp", HAS_ARG, QEMU_OPTION_smp },
4195     
4196     /* temporary options */
4197     { "usb", 0, QEMU_OPTION_usb },
4198     { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4199     { NULL },
4200 };
4201
4202 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4203
4204 /* this stack is only used during signal handling */
4205 #define SIGNAL_STACK_SIZE 32768
4206
4207 static uint8_t *signal_stack;
4208
4209 #endif
4210
4211 /* password input */
4212
4213 static BlockDriverState *get_bdrv(int index)
4214 {
4215     BlockDriverState *bs;
4216
4217     if (index < 4) {
4218         bs = bs_table[index];
4219     } else if (index < 6) {
4220         bs = fd_table[index - 4];
4221     } else {
4222         bs = NULL;
4223     }
4224     return bs;
4225 }
4226
4227 static void read_passwords(void)
4228 {
4229     BlockDriverState *bs;
4230     int i, j;
4231     char password[256];
4232
4233     for(i = 0; i < 6; i++) {
4234         bs = get_bdrv(i);
4235         if (bs && bdrv_is_encrypted(bs)) {
4236             term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4237             for(j = 0; j < 3; j++) {
4238                 monitor_readline("Password: ", 
4239                                  1, password, sizeof(password));
4240                 if (bdrv_set_key(bs, password) == 0)
4241                     break;
4242                 term_printf("invalid password\n");
4243             }
4244         }
4245     }
4246 }
4247
4248 /* XXX: currently we cannot use simultaneously different CPUs */
4249 void register_machines(void)
4250 {
4251 #if defined(TARGET_I386)
4252     qemu_register_machine(&pc_machine);
4253     qemu_register_machine(&isapc_machine);
4254 #elif defined(TARGET_PPC)
4255     qemu_register_machine(&heathrow_machine);
4256     qemu_register_machine(&core99_machine);
4257     qemu_register_machine(&prep_machine);
4258 #elif defined(TARGET_MIPS)
4259     qemu_register_machine(&mips_machine);
4260 #elif defined(TARGET_SPARC)
4261 #ifdef TARGET_SPARC64
4262     qemu_register_machine(&sun4u_machine);
4263 #else
4264     qemu_register_machine(&sun4m_machine);
4265 #endif
4266 #elif defined(TARGET_ARM)
4267     qemu_register_machine(&integratorcp_machine);
4268 #else
4269 #error unsupported CPU
4270 #endif
4271 }
4272
4273 #ifdef HAS_AUDIO
4274 struct soundhw soundhw[] = {
4275     {
4276         "sb16",
4277         "Creative Sound Blaster 16",
4278         0,
4279         1,
4280         { .init_isa = SB16_init }
4281     },
4282
4283 #ifdef CONFIG_ADLIB
4284     {
4285         "adlib",
4286 #ifdef HAS_YMF262
4287         "Yamaha YMF262 (OPL3)",
4288 #else
4289         "Yamaha YM3812 (OPL2)",
4290 #endif
4291         0,
4292         1,
4293         { .init_isa = Adlib_init }
4294     },
4295 #endif
4296
4297 #ifdef CONFIG_GUS
4298     {
4299         "gus",
4300         "Gravis Ultrasound GF1",
4301         0,
4302         1,
4303         { .init_isa = GUS_init }
4304     },
4305 #endif
4306
4307     {
4308         "es1370",
4309         "ENSONIQ AudioPCI ES1370",
4310         0,
4311         0,
4312         { .init_pci = es1370_init }
4313     },
4314
4315     { NULL, NULL, 0, 0, { NULL } }
4316 };
4317
4318 static void select_soundhw (const char *optarg)
4319 {
4320     struct soundhw *c;
4321
4322     if (*optarg == '?') {
4323     show_valid_cards:
4324
4325         printf ("Valid sound card names (comma separated):\n");
4326         for (c = soundhw; c->name; ++c) {
4327             printf ("%-11s %s\n", c->name, c->descr);
4328         }
4329         printf ("\n-soundhw all will enable all of the above\n");
4330         exit (*optarg != '?');
4331     }
4332     else {
4333         size_t l;
4334         const char *p;
4335         char *e;
4336         int bad_card = 0;
4337
4338         if (!strcmp (optarg, "all")) {
4339             for (c = soundhw; c->name; ++c) {
4340                 c->enabled = 1;
4341             }
4342             return;
4343         }
4344
4345         p = optarg;
4346         while (*p) {
4347             e = strchr (p, ',');
4348             l = !e ? strlen (p) : (size_t) (e - p);
4349
4350             for (c = soundhw; c->name; ++c) {
4351                 if (!strncmp (c->name, p, l)) {
4352                     c->enabled = 1;
4353                     break;
4354                 }
4355             }
4356
4357             if (!c->name) {
4358                 if (l > 80) {
4359                     fprintf (stderr,
4360                              "Unknown sound card name (too big to show)\n");
4361                 }
4362                 else {
4363                     fprintf (stderr, "Unknown sound card name `%.*s'\n",
4364                              (int) l, p);
4365                 }
4366                 bad_card = 1;
4367             }
4368             p += l + (e != NULL);
4369         }
4370
4371         if (bad_card)
4372             goto show_valid_cards;
4373     }
4374 }
4375 #endif
4376
4377 #define MAX_NET_CLIENTS 32
4378
4379 int main(int argc, char **argv)
4380 {
4381 #ifdef CONFIG_GDBSTUB
4382     int use_gdbstub, gdbstub_port;
4383 #endif
4384     int i, cdrom_index;
4385     int snapshot, linux_boot;
4386     const char *initrd_filename;
4387     const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4388     const char *kernel_filename, *kernel_cmdline;
4389     DisplayState *ds = &display_state;
4390     int cyls, heads, secs, translation;
4391     int start_emulation = 1;
4392     char net_clients[MAX_NET_CLIENTS][256];
4393     int nb_net_clients;
4394     int optind;
4395     const char *r, *optarg;
4396     CharDriverState *monitor_hd;
4397     char monitor_device[128];
4398     char serial_devices[MAX_SERIAL_PORTS][128];
4399     int serial_device_index;
4400     char parallel_devices[MAX_PARALLEL_PORTS][128];
4401     int parallel_device_index;
4402     const char *loadvm = NULL;
4403     QEMUMachine *machine;
4404     char usb_devices[MAX_VM_USB_PORTS][128];
4405     int usb_devices_index;
4406
4407     LIST_INIT (&vm_change_state_head);
4408 #if !defined(CONFIG_SOFTMMU)
4409     /* we never want that malloc() uses mmap() */
4410     mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
4411 #endif
4412     register_machines();
4413     machine = first_machine;
4414     initrd_filename = NULL;
4415     for(i = 0; i < MAX_FD; i++)
4416         fd_filename[i] = NULL;
4417     for(i = 0; i < MAX_DISKS; i++)
4418         hd_filename[i] = NULL;
4419     ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4420     vga_ram_size = VGA_RAM_SIZE;
4421     bios_size = BIOS_SIZE;
4422 #ifdef CONFIG_GDBSTUB
4423     use_gdbstub = 0;
4424     gdbstub_port = DEFAULT_GDBSTUB_PORT;
4425 #endif
4426     snapshot = 0;
4427     nographic = 0;
4428     kernel_filename = NULL;
4429     kernel_cmdline = "";
4430 #ifdef TARGET_PPC
4431     cdrom_index = 1;
4432 #else
4433     cdrom_index = 2;
4434 #endif
4435     cyls = heads = secs = 0;
4436     translation = BIOS_ATA_TRANSLATION_AUTO;
4437     pstrcpy(monitor_device, sizeof(monitor_device), "vc");
4438
4439     pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
4440     for(i = 1; i < MAX_SERIAL_PORTS; i++)
4441         serial_devices[i][0] = '\0';
4442     serial_device_index = 0;
4443     
4444     pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
4445     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4446         parallel_devices[i][0] = '\0';
4447     parallel_device_index = 0;
4448     
4449     usb_devices_index = 0;
4450     
4451     nb_net_clients = 0;
4452
4453     nb_nics = 0;
4454     /* default mac address of the first network interface */
4455     
4456     optind = 1;
4457     for(;;) {
4458         if (optind >= argc)
4459             break;
4460         r = argv[optind];
4461         if (r[0] != '-') {
4462             hd_filename[0] = argv[optind++];
4463         } else {
4464             const QEMUOption *popt;
4465
4466             optind++;
4467             popt = qemu_options;
4468             for(;;) {
4469                 if (!popt->name) {
4470                     fprintf(stderr, "%s: invalid option -- '%s'\n", 
4471                             argv[0], r);
4472                     exit(1);
4473                 }
4474                 if (!strcmp(popt->name, r + 1))
4475                     break;
4476                 popt++;
4477             }
4478             if (popt->flags & HAS_ARG) {
4479                 if (optind >= argc) {
4480                     fprintf(stderr, "%s: option '%s' requires an argument\n",
4481                             argv[0], r);
4482                     exit(1);
4483                 }
4484                 optarg = argv[optind++];
4485             } else {
4486                 optarg = NULL;
4487             }
4488
4489             switch(popt->index) {
4490             case QEMU_OPTION_M:
4491                 machine = find_machine(optarg);
4492                 if (!machine) {
4493                     QEMUMachine *m;
4494                     printf("Supported machines are:\n");
4495                     for(m = first_machine; m != NULL; m = m->next) {
4496                         printf("%-10s %s%s\n",
4497                                m->name, m->desc, 
4498                                m == first_machine ? " (default)" : "");
4499                     }
4500                     exit(1);
4501                 }
4502                 break;
4503             case QEMU_OPTION_initrd:
4504                 initrd_filename = optarg;
4505                 break;
4506             case QEMU_OPTION_hda:
4507             case QEMU_OPTION_hdb:
4508             case QEMU_OPTION_hdc:
4509             case QEMU_OPTION_hdd:
4510                 {
4511                     int hd_index;
4512                     hd_index = popt->index - QEMU_OPTION_hda;
4513                     hd_filename[hd_index] = optarg;
4514                     if (hd_index == cdrom_index)
4515                         cdrom_index = -1;
4516                 }
4517                 break;
4518             case QEMU_OPTION_snapshot:
4519                 snapshot = 1;
4520                 break;
4521             case QEMU_OPTION_hdachs:
4522                 {
4523                     const char *p;
4524                     p = optarg;
4525                     cyls = strtol(p, (char **)&p, 0);
4526                     if (cyls < 1 || cyls > 16383)
4527                         goto chs_fail;
4528                     if (*p != ',')
4529                         goto chs_fail;
4530                     p++;
4531                     heads = strtol(p, (char **)&p, 0);
4532                     if (heads < 1 || heads > 16)
4533                         goto chs_fail;
4534                     if (*p != ',')
4535                         goto chs_fail;
4536                     p++;
4537                     secs = strtol(p, (char **)&p, 0);
4538                     if (secs < 1 || secs > 63)
4539                         goto chs_fail;
4540                     if (*p == ',') {
4541                         p++;
4542                         if (!strcmp(p, "none"))
4543                             translation = BIOS_ATA_TRANSLATION_NONE;
4544                         else if (!strcmp(p, "lba"))
4545                             translation = BIOS_ATA_TRANSLATION_LBA;
4546                         else if (!strcmp(p, "auto"))
4547                             translation = BIOS_ATA_TRANSLATION_AUTO;
4548                         else
4549                             goto chs_fail;
4550                     } else if (*p != '\0') {
4551                     chs_fail:
4552                         fprintf(stderr, "qemu: invalid physical CHS format\n");
4553                         exit(1);
4554                     }
4555                 }
4556                 break;
4557             case QEMU_OPTION_nographic:
4558                 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
4559                 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
4560                 nographic = 1;
4561                 break;
4562             case QEMU_OPTION_kernel:
4563                 kernel_filename = optarg;
4564                 break;
4565             case QEMU_OPTION_append:
4566                 kernel_cmdline = optarg;
4567                 break;
4568             case QEMU_OPTION_cdrom:
4569                 if (cdrom_index >= 0) {
4570                     hd_filename[cdrom_index] = optarg;
4571                 }
4572                 break;
4573             case QEMU_OPTION_boot:
4574                 boot_device = optarg[0];
4575                 if (boot_device != 'a' && 
4576 #ifdef TARGET_SPARC
4577                     // Network boot
4578                     boot_device != 'n' &&
4579 #endif
4580                     boot_device != 'c' && boot_device != 'd') {
4581                     fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
4582                     exit(1);
4583                 }
4584                 break;
4585             case QEMU_OPTION_fda:
4586                 fd_filename[0] = optarg;
4587                 break;
4588             case QEMU_OPTION_fdb:
4589                 fd_filename[1] = optarg;
4590                 break;
4591             case QEMU_OPTION_no_code_copy:
4592                 code_copy_enabled = 0;
4593                 break;
4594             case QEMU_OPTION_net:
4595                 if (nb_net_clients >= MAX_NET_CLIENTS) {
4596                     fprintf(stderr, "qemu: too many network clients\n");
4597                     exit(1);
4598                 }
4599                 pstrcpy(net_clients[nb_net_clients],
4600                         sizeof(net_clients[0]),
4601                         optarg);
4602                 nb_net_clients++;
4603                 break;
4604 #ifdef CONFIG_SLIRP
4605             case QEMU_OPTION_tftp:
4606                 tftp_prefix = optarg;
4607                 break;
4608 #ifndef _WIN32
4609             case QEMU_OPTION_smb:
4610                 net_slirp_smb(optarg);
4611                 break;
4612 #endif
4613             case QEMU_OPTION_redir:
4614                 net_slirp_redir(optarg);                
4615                 break;
4616 #endif
4617 #ifdef HAS_AUDIO
4618             case QEMU_OPTION_audio_help:
4619                 AUD_help ();
4620                 exit (0);
4621                 break;
4622             case QEMU_OPTION_soundhw:
4623                 select_soundhw (optarg);
4624                 break;
4625 #endif
4626             case QEMU_OPTION_h:
4627                 help();
4628                 break;
4629             case QEMU_OPTION_m:
4630                 ram_size = atoi(optarg) * 1024 * 1024;
4631                 if (ram_size <= 0)
4632                     help();
4633                 if (ram_size > PHYS_RAM_MAX_SIZE) {
4634                     fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
4635                             PHYS_RAM_MAX_SIZE / (1024 * 1024));
4636                     exit(1);
4637                 }
4638                 break;
4639             case QEMU_OPTION_d:
4640                 {
4641                     int mask;
4642                     CPULogItem *item;
4643                     
4644                     mask = cpu_str_to_log_mask(optarg);
4645                     if (!mask) {
4646                         printf("Log items (comma separated):\n");
4647                     for(item = cpu_log_items; item->mask != 0; item++) {
4648                         printf("%-10s %s\n", item->name, item->help);
4649                     }
4650                     exit(1);
4651                     }
4652                     cpu_set_log(mask);
4653                 }
4654                 break;
4655 #ifdef CONFIG_GDBSTUB
4656             case QEMU_OPTION_s:
4657                 use_gdbstub = 1;
4658                 break;
4659             case QEMU_OPTION_p:
4660                 gdbstub_port = atoi(optarg);
4661                 break;
4662 #endif
4663             case QEMU_OPTION_L:
4664                 bios_dir = optarg;
4665                 break;
4666             case QEMU_OPTION_S:
4667                 start_emulation = 0;
4668                 break;
4669             case QEMU_OPTION_k:
4670                 keyboard_layout = optarg;
4671                 break;
4672             case QEMU_OPTION_localtime:
4673                 rtc_utc = 0;
4674                 break;
4675             case QEMU_OPTION_cirrusvga:
4676                 cirrus_vga_enabled = 1;
4677                 break;
4678             case QEMU_OPTION_std_vga:
4679                 cirrus_vga_enabled = 0;
4680                 break;
4681             case QEMU_OPTION_g:
4682                 {
4683                     const char *p;
4684                     int w, h, depth;
4685                     p = optarg;
4686                     w = strtol(p, (char **)&p, 10);
4687                     if (w <= 0) {
4688                     graphic_error:
4689                         fprintf(stderr, "qemu: invalid resolution or depth\n");
4690                         exit(1);
4691                     }
4692                     if (*p != 'x')
4693                         goto graphic_error;
4694                     p++;
4695                     h = strtol(p, (char **)&p, 10);
4696                     if (h <= 0)
4697                         goto graphic_error;
4698                     if (*p == 'x') {
4699                         p++;
4700                         depth = strtol(p, (char **)&p, 10);
4701                         if (depth != 8 && depth != 15 && depth != 16 && 
4702                             depth != 24 && depth != 32)
4703                             goto graphic_error;
4704                     } else if (*p == '\0') {
4705                         depth = graphic_depth;
4706                     } else {
4707                         goto graphic_error;
4708                     }
4709                     
4710                     graphic_width = w;
4711                     graphic_height = h;
4712                     graphic_depth = depth;
4713                 }
4714                 break;
4715             case QEMU_OPTION_monitor:
4716                 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
4717                 break;
4718             case QEMU_OPTION_serial:
4719                 if (serial_device_index >= MAX_SERIAL_PORTS) {
4720                     fprintf(stderr, "qemu: too many serial ports\n");
4721                     exit(1);
4722                 }
4723                 pstrcpy(serial_devices[serial_device_index], 
4724                         sizeof(serial_devices[0]), optarg);
4725                 serial_device_index++;
4726                 break;
4727             case QEMU_OPTION_parallel:
4728                 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4729                     fprintf(stderr, "qemu: too many parallel ports\n");
4730                     exit(1);
4731                 }
4732                 pstrcpy(parallel_devices[parallel_device_index], 
4733                         sizeof(parallel_devices[0]), optarg);
4734                 parallel_device_index++;
4735                 break;
4736             case QEMU_OPTION_loadvm:
4737                 loadvm = optarg;
4738                 break;
4739             case QEMU_OPTION_full_screen:
4740                 full_screen = 1;
4741                 break;
4742             case QEMU_OPTION_pidfile:
4743                 create_pidfile(optarg);
4744                 break;
4745 #ifdef TARGET_I386
4746             case QEMU_OPTION_win2k_hack:
4747                 win2k_install_hack = 1;
4748                 break;
4749 #endif
4750 #ifdef USE_KQEMU
4751             case QEMU_OPTION_no_kqemu:
4752                 kqemu_allowed = 0;
4753                 break;
4754 #endif
4755             case QEMU_OPTION_usb:
4756                 usb_enabled = 1;
4757                 break;
4758             case QEMU_OPTION_usbdevice:
4759                 usb_enabled = 1;
4760                 if (usb_devices_index >= MAX_VM_USB_PORTS) {
4761                     fprintf(stderr, "Too many USB devices\n");
4762                     exit(1);
4763                 }
4764                 pstrcpy(usb_devices[usb_devices_index],
4765                         sizeof(usb_devices[usb_devices_index]),
4766                         optarg);
4767                 usb_devices_index++;
4768                 break;
4769             case QEMU_OPTION_smp:
4770                 smp_cpus = atoi(optarg);
4771                 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
4772                     fprintf(stderr, "Invalid number of CPUs\n");
4773                     exit(1);
4774                 }
4775                 break;
4776             }
4777         }
4778     }
4779
4780     linux_boot = (kernel_filename != NULL);
4781         
4782     if (!linux_boot && 
4783         hd_filename[0] == '\0' && 
4784         (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
4785         fd_filename[0] == '\0')
4786         help();
4787     
4788     /* boot to cd by default if no hard disk */
4789     if (hd_filename[0] == '\0' && boot_device == 'c') {
4790         if (fd_filename[0] != '\0')
4791             boot_device = 'a';
4792         else
4793             boot_device = 'd';
4794     }
4795
4796 #if !defined(CONFIG_SOFTMMU)
4797     /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
4798     {
4799         static uint8_t stdout_buf[4096];
4800         setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
4801     }
4802 #else
4803     setvbuf(stdout, NULL, _IOLBF, 0);
4804 #endif
4805     
4806     /* init network clients */
4807     if (nb_net_clients == 0) {
4808         /* if no clients, we use a default config */
4809         pstrcpy(net_clients[0], sizeof(net_clients[0]),
4810                 "nic");
4811         pstrcpy(net_clients[1], sizeof(net_clients[0]),
4812                 "user");
4813         nb_net_clients = 2;
4814     }
4815
4816     for(i = 0;i < nb_net_clients; i++) {
4817         if (net_client_init(net_clients[i]) < 0)
4818             exit(1);
4819     }
4820
4821     /* init the memory */
4822     phys_ram_size = ram_size + vga_ram_size + bios_size;
4823
4824 #ifdef CONFIG_SOFTMMU
4825     phys_ram_base = qemu_vmalloc(phys_ram_size);
4826     if (!phys_ram_base) {
4827         fprintf(stderr, "Could not allocate physical memory\n");
4828         exit(1);
4829     }
4830 #else
4831     /* as we must map the same page at several addresses, we must use
4832        a fd */
4833     {
4834         const char *tmpdir;
4835
4836         tmpdir = getenv("QEMU_TMPDIR");
4837         if (!tmpdir)
4838             tmpdir = "/tmp";
4839         snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
4840         if (mkstemp(phys_ram_file) < 0) {
4841             fprintf(stderr, "Could not create temporary memory file '%s'\n", 
4842                     phys_ram_file);
4843             exit(1);
4844         }
4845         phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
4846         if (phys_ram_fd < 0) {
4847             fprintf(stderr, "Could not open temporary memory file '%s'\n", 
4848                     phys_ram_file);
4849             exit(1);
4850         }
4851         ftruncate(phys_ram_fd, phys_ram_size);
4852         unlink(phys_ram_file);
4853         phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
4854                              phys_ram_size, 
4855                              PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
4856                              phys_ram_fd, 0);
4857         if (phys_ram_base == MAP_FAILED) {
4858             fprintf(stderr, "Could not map physical memory\n");
4859             exit(1);
4860         }
4861     }
4862 #endif
4863
4864     /* we always create the cdrom drive, even if no disk is there */
4865     bdrv_init();
4866     if (cdrom_index >= 0) {
4867         bs_table[cdrom_index] = bdrv_new("cdrom");
4868         bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
4869     }
4870
4871     /* open the virtual block devices */
4872     for(i = 0; i < MAX_DISKS; i++) {
4873         if (hd_filename[i]) {
4874             if (!bs_table[i]) {
4875                 char buf[64];
4876                 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
4877                 bs_table[i] = bdrv_new(buf);
4878             }
4879             if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
4880                 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
4881                         hd_filename[i]);
4882                 exit(1);
4883             }
4884             if (i == 0 && cyls != 0) {
4885                 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
4886                 bdrv_set_translation_hint(bs_table[i], translation);
4887             }
4888         }
4889     }
4890
4891     /* we always create at least one floppy disk */
4892     fd_table[0] = bdrv_new("fda");
4893     bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
4894
4895     for(i = 0; i < MAX_FD; i++) {
4896         if (fd_filename[i]) {
4897             if (!fd_table[i]) {
4898                 char buf[64];
4899                 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
4900                 fd_table[i] = bdrv_new(buf);
4901                 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
4902             }
4903             if (fd_filename[i] != '\0') {
4904                 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
4905                     fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
4906                             fd_filename[i]);
4907                     exit(1);
4908                 }
4909             }
4910         }
4911     }
4912
4913     /* init USB devices */
4914     if (usb_enabled) {
4915         vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
4916         for(i = 0; i < usb_devices_index; i++) {
4917             if (usb_device_add(usb_devices[i]) < 0) {
4918                 fprintf(stderr, "Warning: could not add USB device %s\n",
4919                         usb_devices[i]);
4920             }
4921         }
4922     }
4923
4924     register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
4925     register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
4926
4927     init_ioports();
4928     cpu_calibrate_ticks();
4929
4930     /* terminal init */
4931     if (nographic) {
4932         dumb_display_init(ds);
4933     } else {
4934 #if defined(CONFIG_SDL)
4935         sdl_display_init(ds, full_screen);
4936 #elif defined(CONFIG_COCOA)
4937         cocoa_display_init(ds, full_screen);
4938 #else
4939         dumb_display_init(ds);
4940 #endif
4941     }
4942
4943     vga_console = graphic_console_init(ds);
4944     
4945     monitor_hd = qemu_chr_open(monitor_device);
4946     if (!monitor_hd) {
4947         fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
4948         exit(1);
4949     }
4950     monitor_init(monitor_hd, !nographic);
4951
4952     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
4953         if (serial_devices[i][0] != '\0') {
4954             serial_hds[i] = qemu_chr_open(serial_devices[i]);
4955             if (!serial_hds[i]) {
4956                 fprintf(stderr, "qemu: could not open serial device '%s'\n", 
4957                         serial_devices[i]);
4958                 exit(1);
4959             }
4960             if (!strcmp(serial_devices[i], "vc"))
4961                 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
4962         }
4963     }
4964
4965     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
4966         if (parallel_devices[i][0] != '\0') {
4967             parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
4968             if (!parallel_hds[i]) {
4969                 fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
4970                         parallel_devices[i]);
4971                 exit(1);
4972             }
4973             if (!strcmp(parallel_devices[i], "vc"))
4974                 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
4975         }
4976     }
4977
4978     /* setup cpu signal handlers for MMU / self modifying code handling */
4979 #if !defined(CONFIG_SOFTMMU)
4980     
4981 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4982     {
4983         stack_t stk;
4984         signal_stack = memalign(16, SIGNAL_STACK_SIZE);
4985         stk.ss_sp = signal_stack;
4986         stk.ss_size = SIGNAL_STACK_SIZE;
4987         stk.ss_flags = 0;
4988
4989         if (sigaltstack(&stk, NULL) < 0) {
4990             perror("sigaltstack");
4991             exit(1);
4992         }
4993     }
4994 #endif
4995     {
4996         struct sigaction act;
4997         
4998         sigfillset(&act.sa_mask);
4999         act.sa_flags = SA_SIGINFO;
5000 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5001         act.sa_flags |= SA_ONSTACK;
5002 #endif
5003         act.sa_sigaction = host_segv_handler;
5004         sigaction(SIGSEGV, &act, NULL);
5005         sigaction(SIGBUS, &act, NULL);
5006 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5007         sigaction(SIGFPE, &act, NULL);
5008 #endif
5009     }
5010 #endif
5011
5012 #ifndef _WIN32
5013     {
5014         struct sigaction act;
5015         sigfillset(&act.sa_mask);
5016         act.sa_flags = 0;
5017         act.sa_handler = SIG_IGN;
5018         sigaction(SIGPIPE, &act, NULL);
5019     }
5020 #endif
5021     init_timers();
5022
5023     machine->init(ram_size, vga_ram_size, boot_device,
5024                   ds, fd_filename, snapshot,
5025                   kernel_filename, kernel_cmdline, initrd_filename);
5026
5027     gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5028     qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5029
5030 #ifdef CONFIG_GDBSTUB
5031     if (use_gdbstub) {
5032         if (gdbserver_start(gdbstub_port) < 0) {
5033             fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
5034                     gdbstub_port);
5035             exit(1);
5036         } else {
5037             printf("Waiting gdb connection on port %d\n", gdbstub_port);
5038         }
5039     } else 
5040 #endif
5041     if (loadvm)
5042         qemu_loadvm(loadvm);
5043
5044     {
5045         /* XXX: simplify init */
5046         read_passwords();
5047         if (start_emulation) {
5048             vm_start();
5049         }
5050     }
5051     main_loop();
5052     quit_timers();
5053     return 0;
5054 }