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