Run monitor over unix domain sockets, by Anthony Liguori.
[qemu] / vl.c
1 /*
2  * QEMU System Emulator
3  * 
4  * Copyright (c) 2003-2006 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 #include <zlib.h>
33
34 #ifndef _WIN32
35 #include <sys/times.h>
36 #include <sys/wait.h>
37 #include <termios.h>
38 #include <sys/poll.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <dirent.h>
44 #include <netdb.h>
45 #ifdef _BSD
46 #include <sys/stat.h>
47 #ifndef __APPLE__
48 #include <libutil.h>
49 #endif
50 #else
51 #ifndef __sun__
52 #include <linux/if.h>
53 #include <linux/if_tun.h>
54 #include <pty.h>
55 #include <malloc.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
58 #endif
59 #endif
60 #endif
61
62 #if defined(CONFIG_SLIRP)
63 #include "libslirp.h"
64 #endif
65
66 #ifdef _WIN32
67 #include <malloc.h>
68 #include <sys/timeb.h>
69 #include <windows.h>
70 #define getopt_long_only getopt_long
71 #define memalign(align, size) malloc(size)
72 #endif
73
74 #include "qemu_socket.h"
75
76 #ifdef CONFIG_SDL
77 #ifdef __APPLE__
78 #include <SDL/SDL.h>
79 #endif
80 #endif /* CONFIG_SDL */
81
82 #ifdef CONFIG_COCOA
83 #undef main
84 #define main qemu_main
85 #endif /* CONFIG_COCOA */
86
87 #include "disas.h"
88
89 #include "exec-all.h"
90
91 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
92
93 //#define DEBUG_UNUSED_IOPORT
94 //#define DEBUG_IOPORT
95
96 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
97
98 #ifdef TARGET_PPC
99 #define DEFAULT_RAM_SIZE 144
100 #else
101 #define DEFAULT_RAM_SIZE 128
102 #endif
103 /* in ms */
104 #define GUI_REFRESH_INTERVAL 30
105
106 /* Max number of USB devices that can be specified on the commandline.  */
107 #define MAX_USB_CMDLINE 8
108
109 /* XXX: use a two level table to limit memory usage */
110 #define MAX_IOPORTS 65536
111
112 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
113 char phys_ram_file[1024];
114 void *ioport_opaque[MAX_IOPORTS];
115 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
116 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
117 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
118    to store the VM snapshots */
119 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
120 /* point to the block driver where the snapshots are managed */
121 BlockDriverState *bs_snapshots;
122 int vga_ram_size;
123 int bios_size;
124 static DisplayState display_state;
125 int nographic;
126 const char* keyboard_layout = NULL;
127 int64_t ticks_per_sec;
128 int boot_device = 'c';
129 int ram_size;
130 int pit_min_timer_count = 0;
131 int nb_nics;
132 NICInfo nd_table[MAX_NICS];
133 QEMUTimer *gui_timer;
134 int vm_running;
135 int rtc_utc = 1;
136 int cirrus_vga_enabled = 1;
137 #ifdef TARGET_SPARC
138 int graphic_width = 1024;
139 int graphic_height = 768;
140 #else
141 int graphic_width = 800;
142 int graphic_height = 600;
143 #endif
144 int graphic_depth = 15;
145 int full_screen = 0;
146 int no_quit = 0;
147 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
148 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
149 #ifdef TARGET_I386
150 int win2k_install_hack = 0;
151 #endif
152 int usb_enabled = 0;
153 static VLANState *first_vlan;
154 int smp_cpus = 1;
155 int vnc_display = -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 int acpi_enabled = 1;
164 int fd_bootchk = 1;
165 int no_reboot = 0;
166
167 /***********************************************************/
168 /* x86 ISA bus support */
169
170 target_phys_addr_t isa_mem_base = 0;
171 PicState2 *isa_pic;
172
173 uint32_t default_ioport_readb(void *opaque, uint32_t address)
174 {
175 #ifdef DEBUG_UNUSED_IOPORT
176     fprintf(stderr, "inb: port=0x%04x\n", address);
177 #endif
178     return 0xff;
179 }
180
181 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
182 {
183 #ifdef DEBUG_UNUSED_IOPORT
184     fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
185 #endif
186 }
187
188 /* default is to make two byte accesses */
189 uint32_t default_ioport_readw(void *opaque, uint32_t address)
190 {
191     uint32_t data;
192     data = ioport_read_table[0][address](ioport_opaque[address], address);
193     address = (address + 1) & (MAX_IOPORTS - 1);
194     data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
195     return data;
196 }
197
198 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
199 {
200     ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
201     address = (address + 1) & (MAX_IOPORTS - 1);
202     ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
203 }
204
205 uint32_t default_ioport_readl(void *opaque, uint32_t address)
206 {
207 #ifdef DEBUG_UNUSED_IOPORT
208     fprintf(stderr, "inl: port=0x%04x\n", address);
209 #endif
210     return 0xffffffff;
211 }
212
213 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
214 {
215 #ifdef DEBUG_UNUSED_IOPORT
216     fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
217 #endif
218 }
219
220 void init_ioports(void)
221 {
222     int i;
223
224     for(i = 0; i < MAX_IOPORTS; i++) {
225         ioport_read_table[0][i] = default_ioport_readb;
226         ioport_write_table[0][i] = default_ioport_writeb;
227         ioport_read_table[1][i] = default_ioport_readw;
228         ioport_write_table[1][i] = default_ioport_writew;
229         ioport_read_table[2][i] = default_ioport_readl;
230         ioport_write_table[2][i] = default_ioport_writel;
231     }
232 }
233
234 /* size is the word size in byte */
235 int register_ioport_read(int start, int length, int size, 
236                          IOPortReadFunc *func, void *opaque)
237 {
238     int i, bsize;
239
240     if (size == 1) {
241         bsize = 0;
242     } else if (size == 2) {
243         bsize = 1;
244     } else if (size == 4) {
245         bsize = 2;
246     } else {
247         hw_error("register_ioport_read: invalid size");
248         return -1;
249     }
250     for(i = start; i < start + length; i += size) {
251         ioport_read_table[bsize][i] = func;
252         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
253             hw_error("register_ioport_read: invalid opaque");
254         ioport_opaque[i] = opaque;
255     }
256     return 0;
257 }
258
259 /* size is the word size in byte */
260 int register_ioport_write(int start, int length, int size, 
261                           IOPortWriteFunc *func, void *opaque)
262 {
263     int i, bsize;
264
265     if (size == 1) {
266         bsize = 0;
267     } else if (size == 2) {
268         bsize = 1;
269     } else if (size == 4) {
270         bsize = 2;
271     } else {
272         hw_error("register_ioport_write: invalid size");
273         return -1;
274     }
275     for(i = start; i < start + length; i += size) {
276         ioport_write_table[bsize][i] = func;
277         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
278             hw_error("register_ioport_read: invalid opaque");
279         ioport_opaque[i] = opaque;
280     }
281     return 0;
282 }
283
284 void isa_unassign_ioport(int start, int length)
285 {
286     int i;
287
288     for(i = start; i < start + length; i++) {
289         ioport_read_table[0][i] = default_ioport_readb;
290         ioport_read_table[1][i] = default_ioport_readw;
291         ioport_read_table[2][i] = default_ioport_readl;
292
293         ioport_write_table[0][i] = default_ioport_writeb;
294         ioport_write_table[1][i] = default_ioport_writew;
295         ioport_write_table[2][i] = default_ioport_writel;
296     }
297 }
298
299 /***********************************************************/
300
301 void pstrcpy(char *buf, int buf_size, const char *str)
302 {
303     int c;
304     char *q = buf;
305
306     if (buf_size <= 0)
307         return;
308
309     for(;;) {
310         c = *str++;
311         if (c == 0 || q >= buf + buf_size - 1)
312             break;
313         *q++ = c;
314     }
315     *q = '\0';
316 }
317
318 /* strcat and truncate. */
319 char *pstrcat(char *buf, int buf_size, const char *s)
320 {
321     int len;
322     len = strlen(buf);
323     if (len < buf_size) 
324         pstrcpy(buf + len, buf_size - len, s);
325     return buf;
326 }
327
328 int strstart(const char *str, const char *val, const char **ptr)
329 {
330     const char *p, *q;
331     p = str;
332     q = val;
333     while (*q != '\0') {
334         if (*p != *q)
335             return 0;
336         p++;
337         q++;
338     }
339     if (ptr)
340         *ptr = p;
341     return 1;
342 }
343
344 void cpu_outb(CPUState *env, int addr, int val)
345 {
346 #ifdef DEBUG_IOPORT
347     if (loglevel & CPU_LOG_IOPORT)
348         fprintf(logfile, "outb: %04x %02x\n", addr, val);
349 #endif    
350     ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
351 #ifdef USE_KQEMU
352     if (env)
353         env->last_io_time = cpu_get_time_fast();
354 #endif
355 }
356
357 void cpu_outw(CPUState *env, int addr, int val)
358 {
359 #ifdef DEBUG_IOPORT
360     if (loglevel & CPU_LOG_IOPORT)
361         fprintf(logfile, "outw: %04x %04x\n", addr, val);
362 #endif    
363     ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
364 #ifdef USE_KQEMU
365     if (env)
366         env->last_io_time = cpu_get_time_fast();
367 #endif
368 }
369
370 void cpu_outl(CPUState *env, int addr, int val)
371 {
372 #ifdef DEBUG_IOPORT
373     if (loglevel & CPU_LOG_IOPORT)
374         fprintf(logfile, "outl: %04x %08x\n", addr, val);
375 #endif
376     ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
377 #ifdef USE_KQEMU
378     if (env)
379         env->last_io_time = cpu_get_time_fast();
380 #endif
381 }
382
383 int cpu_inb(CPUState *env, int addr)
384 {
385     int val;
386     val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
387 #ifdef DEBUG_IOPORT
388     if (loglevel & CPU_LOG_IOPORT)
389         fprintf(logfile, "inb : %04x %02x\n", addr, val);
390 #endif
391 #ifdef USE_KQEMU
392     if (env)
393         env->last_io_time = cpu_get_time_fast();
394 #endif
395     return val;
396 }
397
398 int cpu_inw(CPUState *env, int addr)
399 {
400     int val;
401     val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
402 #ifdef DEBUG_IOPORT
403     if (loglevel & CPU_LOG_IOPORT)
404         fprintf(logfile, "inw : %04x %04x\n", addr, val);
405 #endif
406 #ifdef USE_KQEMU
407     if (env)
408         env->last_io_time = cpu_get_time_fast();
409 #endif
410     return val;
411 }
412
413 int cpu_inl(CPUState *env, int addr)
414 {
415     int val;
416     val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
417 #ifdef DEBUG_IOPORT
418     if (loglevel & CPU_LOG_IOPORT)
419         fprintf(logfile, "inl : %04x %08x\n", addr, val);
420 #endif
421 #ifdef USE_KQEMU
422     if (env)
423         env->last_io_time = cpu_get_time_fast();
424 #endif
425     return val;
426 }
427
428 /***********************************************************/
429 void hw_error(const char *fmt, ...)
430 {
431     va_list ap;
432     CPUState *env;
433
434     va_start(ap, fmt);
435     fprintf(stderr, "qemu: hardware error: ");
436     vfprintf(stderr, fmt, ap);
437     fprintf(stderr, "\n");
438     for(env = first_cpu; env != NULL; env = env->next_cpu) {
439         fprintf(stderr, "CPU #%d:\n", env->cpu_index);
440 #ifdef TARGET_I386
441         cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
442 #else
443         cpu_dump_state(env, stderr, fprintf, 0);
444 #endif
445     }
446     va_end(ap);
447     abort();
448 }
449
450 /***********************************************************/
451 /* keyboard/mouse */
452
453 static QEMUPutKBDEvent *qemu_put_kbd_event;
454 static void *qemu_put_kbd_event_opaque;
455 static QEMUPutMouseEvent *qemu_put_mouse_event;
456 static void *qemu_put_mouse_event_opaque;
457 static int qemu_put_mouse_event_absolute;
458
459 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
460 {
461     qemu_put_kbd_event_opaque = opaque;
462     qemu_put_kbd_event = func;
463 }
464
465 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
466 {
467     qemu_put_mouse_event_opaque = opaque;
468     qemu_put_mouse_event = func;
469     qemu_put_mouse_event_absolute = absolute;
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 int kbd_mouse_is_absolute(void)
488 {
489     return qemu_put_mouse_event_absolute;
490 }
491
492 /* compute with 96 bit intermediate result: (a*b)/c */
493 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
494 {
495     union {
496         uint64_t ll;
497         struct {
498 #ifdef WORDS_BIGENDIAN
499             uint32_t high, low;
500 #else
501             uint32_t low, high;
502 #endif            
503         } l;
504     } u, res;
505     uint64_t rl, rh;
506
507     u.ll = a;
508     rl = (uint64_t)u.l.low * (uint64_t)b;
509     rh = (uint64_t)u.l.high * (uint64_t)b;
510     rh += (rl >> 32);
511     res.l.high = rh / c;
512     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
513     return res.ll;
514 }
515
516 /***********************************************************/
517 /* real time host monotonic timer */
518
519 #define QEMU_TIMER_BASE 1000000000LL
520
521 #ifdef WIN32
522
523 static int64_t clock_freq;
524
525 static void init_get_clock(void)
526 {
527     LARGE_INTEGER freq;
528     int ret;
529     ret = QueryPerformanceFrequency(&freq);
530     if (ret == 0) {
531         fprintf(stderr, "Could not calibrate ticks\n");
532         exit(1);
533     }
534     clock_freq = freq.QuadPart;
535 }
536
537 static int64_t get_clock(void)
538 {
539     LARGE_INTEGER ti;
540     QueryPerformanceCounter(&ti);
541     return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
542 }
543
544 #else
545
546 static int use_rt_clock;
547
548 static void init_get_clock(void)
549 {
550     use_rt_clock = 0;
551 #if defined(__linux__)
552     {
553         struct timespec ts;
554         if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
555             use_rt_clock = 1;
556         }
557     }
558 #endif
559 }
560
561 static int64_t get_clock(void)
562 {
563 #if defined(__linux__)
564     if (use_rt_clock) {
565         struct timespec ts;
566         clock_gettime(CLOCK_MONOTONIC, &ts);
567         return ts.tv_sec * 1000000000LL + ts.tv_nsec;
568     } else 
569 #endif
570     {
571         /* XXX: using gettimeofday leads to problems if the date
572            changes, so it should be avoided. */
573         struct timeval tv;
574         gettimeofday(&tv, NULL);
575         return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
576     }
577 }
578
579 #endif
580
581 /***********************************************************/
582 /* guest cycle counter */
583
584 static int64_t cpu_ticks_prev;
585 static int64_t cpu_ticks_offset;
586 static int64_t cpu_clock_offset;
587 static int cpu_ticks_enabled;
588
589 /* return the host CPU cycle counter and handle stop/restart */
590 int64_t cpu_get_ticks(void)
591 {
592     if (!cpu_ticks_enabled) {
593         return cpu_ticks_offset;
594     } else {
595         int64_t ticks;
596         ticks = cpu_get_real_ticks();
597         if (cpu_ticks_prev > ticks) {
598             /* Note: non increasing ticks may happen if the host uses
599                software suspend */
600             cpu_ticks_offset += cpu_ticks_prev - ticks;
601         }
602         cpu_ticks_prev = ticks;
603         return ticks + cpu_ticks_offset;
604     }
605 }
606
607 /* return the host CPU monotonic timer and handle stop/restart */
608 static int64_t cpu_get_clock(void)
609 {
610     int64_t ti;
611     if (!cpu_ticks_enabled) {
612         return cpu_clock_offset;
613     } else {
614         ti = get_clock();
615         return ti + cpu_clock_offset;
616     }
617 }
618
619 /* enable cpu_get_ticks() */
620 void cpu_enable_ticks(void)
621 {
622     if (!cpu_ticks_enabled) {
623         cpu_ticks_offset -= cpu_get_real_ticks();
624         cpu_clock_offset -= get_clock();
625         cpu_ticks_enabled = 1;
626     }
627 }
628
629 /* disable cpu_get_ticks() : the clock is stopped. You must not call
630    cpu_get_ticks() after that.  */
631 void cpu_disable_ticks(void)
632 {
633     if (cpu_ticks_enabled) {
634         cpu_ticks_offset = cpu_get_ticks();
635         cpu_clock_offset = cpu_get_clock();
636         cpu_ticks_enabled = 0;
637     }
638 }
639
640 /***********************************************************/
641 /* timers */
642  
643 #define QEMU_TIMER_REALTIME 0
644 #define QEMU_TIMER_VIRTUAL  1
645
646 struct QEMUClock {
647     int type;
648     /* XXX: add frequency */
649 };
650
651 struct QEMUTimer {
652     QEMUClock *clock;
653     int64_t expire_time;
654     QEMUTimerCB *cb;
655     void *opaque;
656     struct QEMUTimer *next;
657 };
658
659 QEMUClock *rt_clock;
660 QEMUClock *vm_clock;
661
662 static QEMUTimer *active_timers[2];
663 #ifdef _WIN32
664 static MMRESULT timerID;
665 static HANDLE host_alarm = NULL;
666 static unsigned int period = 1;
667 #else
668 /* frequency of the times() clock tick */
669 static int timer_freq;
670 #endif
671
672 QEMUClock *qemu_new_clock(int type)
673 {
674     QEMUClock *clock;
675     clock = qemu_mallocz(sizeof(QEMUClock));
676     if (!clock)
677         return NULL;
678     clock->type = type;
679     return clock;
680 }
681
682 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
683 {
684     QEMUTimer *ts;
685
686     ts = qemu_mallocz(sizeof(QEMUTimer));
687     ts->clock = clock;
688     ts->cb = cb;
689     ts->opaque = opaque;
690     return ts;
691 }
692
693 void qemu_free_timer(QEMUTimer *ts)
694 {
695     qemu_free(ts);
696 }
697
698 /* stop a timer, but do not dealloc it */
699 void qemu_del_timer(QEMUTimer *ts)
700 {
701     QEMUTimer **pt, *t;
702
703     /* NOTE: this code must be signal safe because
704        qemu_timer_expired() can be called from a signal. */
705     pt = &active_timers[ts->clock->type];
706     for(;;) {
707         t = *pt;
708         if (!t)
709             break;
710         if (t == ts) {
711             *pt = t->next;
712             break;
713         }
714         pt = &t->next;
715     }
716 }
717
718 /* modify the current timer so that it will be fired when current_time
719    >= expire_time. The corresponding callback will be called. */
720 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
721 {
722     QEMUTimer **pt, *t;
723
724     qemu_del_timer(ts);
725
726     /* add the timer in the sorted list */
727     /* NOTE: this code must be signal safe because
728        qemu_timer_expired() can be called from a signal. */
729     pt = &active_timers[ts->clock->type];
730     for(;;) {
731         t = *pt;
732         if (!t)
733             break;
734         if (t->expire_time > expire_time) 
735             break;
736         pt = &t->next;
737     }
738     ts->expire_time = expire_time;
739     ts->next = *pt;
740     *pt = ts;
741 }
742
743 int qemu_timer_pending(QEMUTimer *ts)
744 {
745     QEMUTimer *t;
746     for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
747         if (t == ts)
748             return 1;
749     }
750     return 0;
751 }
752
753 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
754 {
755     if (!timer_head)
756         return 0;
757     return (timer_head->expire_time <= current_time);
758 }
759
760 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
761 {
762     QEMUTimer *ts;
763     
764     for(;;) {
765         ts = *ptimer_head;
766         if (!ts || ts->expire_time > current_time)
767             break;
768         /* remove timer from the list before calling the callback */
769         *ptimer_head = ts->next;
770         ts->next = NULL;
771         
772         /* run the callback (the timer list can be modified) */
773         ts->cb(ts->opaque);
774     }
775 }
776
777 int64_t qemu_get_clock(QEMUClock *clock)
778 {
779     switch(clock->type) {
780     case QEMU_TIMER_REALTIME:
781         return get_clock() / 1000000;
782     default:
783     case QEMU_TIMER_VIRTUAL:
784         return cpu_get_clock();
785     }
786 }
787
788 static void init_timers(void)
789 {
790     init_get_clock();
791     ticks_per_sec = QEMU_TIMER_BASE;
792     rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
793     vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
794 }
795
796 /* save a timer */
797 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
798 {
799     uint64_t expire_time;
800
801     if (qemu_timer_pending(ts)) {
802         expire_time = ts->expire_time;
803     } else {
804         expire_time = -1;
805     }
806     qemu_put_be64(f, expire_time);
807 }
808
809 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
810 {
811     uint64_t expire_time;
812
813     expire_time = qemu_get_be64(f);
814     if (expire_time != -1) {
815         qemu_mod_timer(ts, expire_time);
816     } else {
817         qemu_del_timer(ts);
818     }
819 }
820
821 static void timer_save(QEMUFile *f, void *opaque)
822 {
823     if (cpu_ticks_enabled) {
824         hw_error("cannot save state if virtual timers are running");
825     }
826     qemu_put_be64s(f, &cpu_ticks_offset);
827     qemu_put_be64s(f, &ticks_per_sec);
828     qemu_put_be64s(f, &cpu_clock_offset);
829 }
830
831 static int timer_load(QEMUFile *f, void *opaque, int version_id)
832 {
833     if (version_id != 1 && version_id != 2)
834         return -EINVAL;
835     if (cpu_ticks_enabled) {
836         return -EINVAL;
837     }
838     qemu_get_be64s(f, &cpu_ticks_offset);
839     qemu_get_be64s(f, &ticks_per_sec);
840     if (version_id == 2) {
841         qemu_get_be64s(f, &cpu_clock_offset);
842     }
843     return 0;
844 }
845
846 #ifdef _WIN32
847 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
848                                  DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
849 #else
850 static void host_alarm_handler(int host_signum)
851 #endif
852 {
853 #if 0
854 #define DISP_FREQ 1000
855     {
856         static int64_t delta_min = INT64_MAX;
857         static int64_t delta_max, delta_cum, last_clock, delta, ti;
858         static int count;
859         ti = qemu_get_clock(vm_clock);
860         if (last_clock != 0) {
861             delta = ti - last_clock;
862             if (delta < delta_min)
863                 delta_min = delta;
864             if (delta > delta_max)
865                 delta_max = delta;
866             delta_cum += delta;
867             if (++count == DISP_FREQ) {
868                 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
869                        muldiv64(delta_min, 1000000, ticks_per_sec),
870                        muldiv64(delta_max, 1000000, ticks_per_sec),
871                        muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
872                        (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
873                 count = 0;
874                 delta_min = INT64_MAX;
875                 delta_max = 0;
876                 delta_cum = 0;
877             }
878         }
879         last_clock = ti;
880     }
881 #endif
882     if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
883                            qemu_get_clock(vm_clock)) ||
884         qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
885                            qemu_get_clock(rt_clock))) {
886 #ifdef _WIN32
887         SetEvent(host_alarm);
888 #endif
889         CPUState *env = cpu_single_env;
890         if (env) {
891             /* stop the currently executing cpu because a timer occured */
892             cpu_interrupt(env, CPU_INTERRUPT_EXIT);
893 #ifdef USE_KQEMU
894             if (env->kqemu_enabled) {
895                 kqemu_cpu_interrupt(env);
896             }
897 #endif
898         }
899     }
900 }
901
902 #ifndef _WIN32
903
904 #if defined(__linux__)
905
906 #define RTC_FREQ 1024
907
908 static int rtc_fd;
909
910 static int start_rtc_timer(void)
911 {
912     rtc_fd = open("/dev/rtc", O_RDONLY);
913     if (rtc_fd < 0)
914         return -1;
915     if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
916         fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
917                 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
918                 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
919         goto fail;
920     }
921     if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
922     fail:
923         close(rtc_fd);
924         return -1;
925     }
926     pit_min_timer_count = PIT_FREQ / RTC_FREQ;
927     return 0;
928 }
929
930 #else
931
932 static int start_rtc_timer(void)
933 {
934     return -1;
935 }
936
937 #endif /* !defined(__linux__) */
938
939 #endif /* !defined(_WIN32) */
940
941 static void init_timer_alarm(void)
942 {
943 #ifdef _WIN32
944     {
945         int count=0;
946         TIMECAPS tc;
947
948         ZeroMemory(&tc, sizeof(TIMECAPS));
949         timeGetDevCaps(&tc, sizeof(TIMECAPS));
950         if (period < tc.wPeriodMin)
951             period = tc.wPeriodMin;
952         timeBeginPeriod(period);
953         timerID = timeSetEvent(1,     // interval (ms)
954                                period,     // resolution
955                                host_alarm_handler, // function
956                                (DWORD)&count,  // user parameter
957                                TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
958         if( !timerID ) {
959             perror("failed timer alarm");
960             exit(1);
961         }
962         host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
963         if (!host_alarm) {
964             perror("failed CreateEvent");
965             exit(1);
966         }
967         qemu_add_wait_object(host_alarm, NULL, NULL);
968     }
969     pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
970 #else
971     {
972         struct sigaction act;
973         struct itimerval itv;
974         
975         /* get times() syscall frequency */
976         timer_freq = sysconf(_SC_CLK_TCK);
977         
978         /* timer signal */
979         sigfillset(&act.sa_mask);
980        act.sa_flags = 0;
981 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
982         act.sa_flags |= SA_ONSTACK;
983 #endif
984         act.sa_handler = host_alarm_handler;
985         sigaction(SIGALRM, &act, NULL);
986
987         itv.it_interval.tv_sec = 0;
988         itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
989         itv.it_value.tv_sec = 0;
990         itv.it_value.tv_usec = 10 * 1000;
991         setitimer(ITIMER_REAL, &itv, NULL);
992         /* we probe the tick duration of the kernel to inform the user if
993            the emulated kernel requested a too high timer frequency */
994         getitimer(ITIMER_REAL, &itv);
995
996 #if defined(__linux__)
997         /* XXX: force /dev/rtc usage because even 2.6 kernels may not
998            have timers with 1 ms resolution. The correct solution will
999            be to use the POSIX real time timers available in recent
1000            2.6 kernels */
1001         if (itv.it_interval.tv_usec > 1000 || 1) {
1002             /* try to use /dev/rtc to have a faster timer */
1003             if (start_rtc_timer() < 0)
1004                 goto use_itimer;
1005             /* disable itimer */
1006             itv.it_interval.tv_sec = 0;
1007             itv.it_interval.tv_usec = 0;
1008             itv.it_value.tv_sec = 0;
1009             itv.it_value.tv_usec = 0;
1010             setitimer(ITIMER_REAL, &itv, NULL);
1011
1012             /* use the RTC */
1013             sigaction(SIGIO, &act, NULL);
1014             fcntl(rtc_fd, F_SETFL, O_ASYNC);
1015             fcntl(rtc_fd, F_SETOWN, getpid());
1016         } else 
1017 #endif /* defined(__linux__) */
1018         {
1019         use_itimer:
1020             pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1021                                    PIT_FREQ) / 1000000;
1022         }
1023     }
1024 #endif
1025 }
1026
1027 void quit_timers(void)
1028 {
1029 #ifdef _WIN32
1030     timeKillEvent(timerID);
1031     timeEndPeriod(period);
1032     if (host_alarm) {
1033         CloseHandle(host_alarm);
1034         host_alarm = NULL;
1035     }
1036 #endif
1037 }
1038
1039 /***********************************************************/
1040 /* character device */
1041
1042 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1043 {
1044     return s->chr_write(s, buf, len);
1045 }
1046
1047 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1048 {
1049     if (!s->chr_ioctl)
1050         return -ENOTSUP;
1051     return s->chr_ioctl(s, cmd, arg);
1052 }
1053
1054 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1055 {
1056     char buf[4096];
1057     va_list ap;
1058     va_start(ap, fmt);
1059     vsnprintf(buf, sizeof(buf), fmt, ap);
1060     qemu_chr_write(s, buf, strlen(buf));
1061     va_end(ap);
1062 }
1063
1064 void qemu_chr_send_event(CharDriverState *s, int event)
1065 {
1066     if (s->chr_send_event)
1067         s->chr_send_event(s, event);
1068 }
1069
1070 void qemu_chr_add_read_handler(CharDriverState *s, 
1071                                IOCanRWHandler *fd_can_read, 
1072                                IOReadHandler *fd_read, void *opaque)
1073 {
1074     s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1075 }
1076              
1077 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1078 {
1079     s->chr_event = chr_event;
1080 }
1081
1082 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1083 {
1084     return len;
1085 }
1086
1087 static void null_chr_add_read_handler(CharDriverState *chr, 
1088                                     IOCanRWHandler *fd_can_read, 
1089                                     IOReadHandler *fd_read, void *opaque)
1090 {
1091 }
1092
1093 CharDriverState *qemu_chr_open_null(void)
1094 {
1095     CharDriverState *chr;
1096
1097     chr = qemu_mallocz(sizeof(CharDriverState));
1098     if (!chr)
1099         return NULL;
1100     chr->chr_write = null_chr_write;
1101     chr->chr_add_read_handler = null_chr_add_read_handler;
1102     return chr;
1103 }
1104
1105 #ifdef _WIN32
1106
1107 static void socket_cleanup(void)
1108 {
1109     WSACleanup();
1110 }
1111
1112 static int socket_init(void)
1113 {
1114     WSADATA Data;
1115     int ret, err;
1116
1117     ret = WSAStartup(MAKEWORD(2,2), &Data);
1118     if (ret != 0) {
1119         err = WSAGetLastError();
1120         fprintf(stderr, "WSAStartup: %d\n", err);
1121         return -1;
1122     }
1123     atexit(socket_cleanup);
1124     return 0;
1125 }
1126
1127 static int send_all(int fd, const uint8_t *buf, int len1)
1128 {
1129     int ret, len;
1130     
1131     len = len1;
1132     while (len > 0) {
1133         ret = send(fd, buf, len, 0);
1134         if (ret < 0) {
1135             int errno;
1136             errno = WSAGetLastError();
1137             if (errno != WSAEWOULDBLOCK) {
1138                 return -1;
1139             }
1140         } else if (ret == 0) {
1141             break;
1142         } else {
1143             buf += ret;
1144             len -= ret;
1145         }
1146     }
1147     return len1 - len;
1148 }
1149
1150 void socket_set_nonblock(int fd)
1151 {
1152     unsigned long opt = 1;
1153     ioctlsocket(fd, FIONBIO, &opt);
1154 }
1155
1156 #else
1157
1158 static int unix_write(int fd, const uint8_t *buf, int len1)
1159 {
1160     int ret, len;
1161
1162     len = len1;
1163     while (len > 0) {
1164         ret = write(fd, buf, len);
1165         if (ret < 0) {
1166             if (errno != EINTR && errno != EAGAIN)
1167                 return -1;
1168         } else if (ret == 0) {
1169             break;
1170         } else {
1171             buf += ret;
1172             len -= ret;
1173         }
1174     }
1175     return len1 - len;
1176 }
1177
1178 static inline int send_all(int fd, const uint8_t *buf, int len1)
1179 {
1180     return unix_write(fd, buf, len1);
1181 }
1182
1183 void socket_set_nonblock(int fd)
1184 {
1185     fcntl(fd, F_SETFL, O_NONBLOCK);
1186 }
1187 #endif /* !_WIN32 */
1188
1189 #ifndef _WIN32
1190
1191 typedef struct {
1192     int fd_in, fd_out;
1193     IOCanRWHandler *fd_can_read; 
1194     IOReadHandler *fd_read;
1195     void *fd_opaque;
1196     int max_size;
1197 } FDCharDriver;
1198
1199 #define STDIO_MAX_CLIENTS 2
1200
1201 static int stdio_nb_clients;
1202 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1203
1204 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1205 {
1206     FDCharDriver *s = chr->opaque;
1207     return unix_write(s->fd_out, buf, len);
1208 }
1209
1210 static int fd_chr_read_poll(void *opaque)
1211 {
1212     CharDriverState *chr = opaque;
1213     FDCharDriver *s = chr->opaque;
1214
1215     s->max_size = s->fd_can_read(s->fd_opaque);
1216     return s->max_size;
1217 }
1218
1219 static void fd_chr_read(void *opaque)
1220 {
1221     CharDriverState *chr = opaque;
1222     FDCharDriver *s = chr->opaque;
1223     int size, len;
1224     uint8_t buf[1024];
1225     
1226     len = sizeof(buf);
1227     if (len > s->max_size)
1228         len = s->max_size;
1229     if (len == 0)
1230         return;
1231     size = read(s->fd_in, buf, len);
1232     if (size == 0) {
1233         /* FD has been closed. Remove it from the active list.  */
1234         qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1235         return;
1236     }
1237     if (size > 0) {
1238         s->fd_read(s->fd_opaque, buf, size);
1239     }
1240 }
1241
1242 static void fd_chr_add_read_handler(CharDriverState *chr, 
1243                                     IOCanRWHandler *fd_can_read, 
1244                                     IOReadHandler *fd_read, void *opaque)
1245 {
1246     FDCharDriver *s = chr->opaque;
1247
1248     if (s->fd_in >= 0) {
1249         s->fd_can_read = fd_can_read;
1250         s->fd_read = fd_read;
1251         s->fd_opaque = opaque;
1252         if (nographic && s->fd_in == 0) {
1253         } else {
1254             qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1255                                  fd_chr_read, NULL, chr);
1256         }
1257     }
1258 }
1259
1260 /* open a character device to a unix fd */
1261 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1262 {
1263     CharDriverState *chr;
1264     FDCharDriver *s;
1265
1266     chr = qemu_mallocz(sizeof(CharDriverState));
1267     if (!chr)
1268         return NULL;
1269     s = qemu_mallocz(sizeof(FDCharDriver));
1270     if (!s) {
1271         free(chr);
1272         return NULL;
1273     }
1274     s->fd_in = fd_in;
1275     s->fd_out = fd_out;
1276     chr->opaque = s;
1277     chr->chr_write = fd_chr_write;
1278     chr->chr_add_read_handler = fd_chr_add_read_handler;
1279     return chr;
1280 }
1281
1282 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1283 {
1284     int fd_out;
1285
1286     fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1287     if (fd_out < 0)
1288         return NULL;
1289     return qemu_chr_open_fd(-1, fd_out);
1290 }
1291
1292 CharDriverState *qemu_chr_open_pipe(const char *filename)
1293 {
1294     int fd;
1295
1296     fd = open(filename, O_RDWR | O_BINARY);
1297     if (fd < 0)
1298         return NULL;
1299     return qemu_chr_open_fd(fd, fd);
1300 }
1301
1302
1303 /* for STDIO, we handle the case where several clients use it
1304    (nographic mode) */
1305
1306 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1307
1308 #define TERM_FIFO_MAX_SIZE 1
1309
1310 static int term_got_escape, client_index;
1311 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1312 static int term_fifo_size;
1313 static int term_timestamps;
1314 static int64_t term_timestamps_start;
1315
1316 void term_print_help(void)
1317 {
1318     printf("\n"
1319            "C-a h    print this help\n"
1320            "C-a x    exit emulator\n"
1321            "C-a s    save disk data back to file (if -snapshot)\n"
1322            "C-a b    send break (magic sysrq)\n"
1323            "C-a t    toggle console timestamps\n"
1324            "C-a c    switch between console and monitor\n"
1325            "C-a C-a  send C-a\n"
1326            );
1327 }
1328
1329 /* called when a char is received */
1330 static void stdio_received_byte(int ch)
1331 {
1332     if (term_got_escape) {
1333         term_got_escape = 0;
1334         switch(ch) {
1335         case 'h':
1336             term_print_help();
1337             break;
1338         case 'x':
1339             exit(0);
1340             break;
1341         case 's': 
1342             {
1343                 int i;
1344                 for (i = 0; i < MAX_DISKS; i++) {
1345                     if (bs_table[i])
1346                         bdrv_commit(bs_table[i]);
1347                 }
1348             }
1349             break;
1350         case 'b':
1351             if (client_index < stdio_nb_clients) {
1352                 CharDriverState *chr;
1353                 FDCharDriver *s;
1354
1355                 chr = stdio_clients[client_index];
1356                 s = chr->opaque;
1357                 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1358             }
1359             break;
1360         case 'c':
1361             client_index++;
1362             if (client_index >= stdio_nb_clients)
1363                 client_index = 0;
1364             if (client_index == 0) {
1365                 /* send a new line in the monitor to get the prompt */
1366                 ch = '\r';
1367                 goto send_char;
1368             }
1369             break;
1370         case 't':
1371             term_timestamps = !term_timestamps;
1372             term_timestamps_start = -1;
1373             break;
1374         case TERM_ESCAPE:
1375             goto send_char;
1376         }
1377     } else if (ch == TERM_ESCAPE) {
1378         term_got_escape = 1;
1379     } else {
1380     send_char:
1381         if (client_index < stdio_nb_clients) {
1382             uint8_t buf[1];
1383             CharDriverState *chr;
1384             FDCharDriver *s;
1385             
1386             chr = stdio_clients[client_index];
1387             s = chr->opaque;
1388             if (s->fd_can_read(s->fd_opaque) > 0) {
1389                 buf[0] = ch;
1390                 s->fd_read(s->fd_opaque, buf, 1);
1391             } else if (term_fifo_size == 0) {
1392                 term_fifo[term_fifo_size++] = ch;
1393             }
1394         }
1395     }
1396 }
1397
1398 static int stdio_read_poll(void *opaque)
1399 {
1400     CharDriverState *chr;
1401     FDCharDriver *s;
1402
1403     if (client_index < stdio_nb_clients) {
1404         chr = stdio_clients[client_index];
1405         s = chr->opaque;
1406         /* try to flush the queue if needed */
1407         if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1408             s->fd_read(s->fd_opaque, term_fifo, 1);
1409             term_fifo_size = 0;
1410         }
1411         /* see if we can absorb more chars */
1412         if (term_fifo_size == 0)
1413             return 1;
1414         else
1415             return 0;
1416     } else {
1417         return 1;
1418     }
1419 }
1420
1421 static void stdio_read(void *opaque)
1422 {
1423     int size;
1424     uint8_t buf[1];
1425     
1426     size = read(0, buf, 1);
1427     if (size == 0) {
1428         /* stdin has been closed. Remove it from the active list.  */
1429         qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1430         return;
1431     }
1432     if (size > 0)
1433         stdio_received_byte(buf[0]);
1434 }
1435
1436 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1437 {
1438     FDCharDriver *s = chr->opaque;
1439     if (!term_timestamps) {
1440         return unix_write(s->fd_out, buf, len);
1441     } else {
1442         int i;
1443         char buf1[64];
1444
1445         for(i = 0; i < len; i++) {
1446             unix_write(s->fd_out, buf + i, 1);
1447             if (buf[i] == '\n') {
1448                 int64_t ti;
1449                 int secs;
1450
1451                 ti = get_clock();
1452                 if (term_timestamps_start == -1)
1453                     term_timestamps_start = ti;
1454                 ti -= term_timestamps_start;
1455                 secs = ti / 1000000000;
1456                 snprintf(buf1, sizeof(buf1), 
1457                          "[%02d:%02d:%02d.%03d] ",
1458                          secs / 3600,
1459                          (secs / 60) % 60,
1460                          secs % 60,
1461                          (int)((ti / 1000000) % 1000));
1462                 unix_write(s->fd_out, buf1, strlen(buf1));
1463             }
1464         }
1465         return len;
1466     }
1467 }
1468
1469 /* init terminal so that we can grab keys */
1470 static struct termios oldtty;
1471 static int old_fd0_flags;
1472
1473 static void term_exit(void)
1474 {
1475     tcsetattr (0, TCSANOW, &oldtty);
1476     fcntl(0, F_SETFL, old_fd0_flags);
1477 }
1478
1479 static void term_init(void)
1480 {
1481     struct termios tty;
1482
1483     tcgetattr (0, &tty);
1484     oldtty = tty;
1485     old_fd0_flags = fcntl(0, F_GETFL);
1486
1487     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1488                           |INLCR|IGNCR|ICRNL|IXON);
1489     tty.c_oflag |= OPOST;
1490     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1491     /* if graphical mode, we allow Ctrl-C handling */
1492     if (nographic)
1493         tty.c_lflag &= ~ISIG;
1494     tty.c_cflag &= ~(CSIZE|PARENB);
1495     tty.c_cflag |= CS8;
1496     tty.c_cc[VMIN] = 1;
1497     tty.c_cc[VTIME] = 0;
1498     
1499     tcsetattr (0, TCSANOW, &tty);
1500
1501     atexit(term_exit);
1502
1503     fcntl(0, F_SETFL, O_NONBLOCK);
1504 }
1505
1506 CharDriverState *qemu_chr_open_stdio(void)
1507 {
1508     CharDriverState *chr;
1509
1510     if (nographic) {
1511         if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1512             return NULL;
1513         chr = qemu_chr_open_fd(0, 1);
1514         chr->chr_write = stdio_write;
1515         if (stdio_nb_clients == 0)
1516             qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1517         client_index = stdio_nb_clients;
1518     } else {
1519         if (stdio_nb_clients != 0)
1520             return NULL;
1521         chr = qemu_chr_open_fd(0, 1);
1522     }
1523     stdio_clients[stdio_nb_clients++] = chr;
1524     if (stdio_nb_clients == 1) {
1525         /* set the terminal in raw mode */
1526         term_init();
1527     }
1528     return chr;
1529 }
1530
1531 #if defined(__linux__)
1532 CharDriverState *qemu_chr_open_pty(void)
1533 {
1534     struct termios tty;
1535     char slave_name[1024];
1536     int master_fd, slave_fd;
1537     
1538     /* Not satisfying */
1539     if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1540         return NULL;
1541     }
1542     
1543     /* Disabling local echo and line-buffered output */
1544     tcgetattr (master_fd, &tty);
1545     tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1546     tty.c_cc[VMIN] = 1;
1547     tty.c_cc[VTIME] = 0;
1548     tcsetattr (master_fd, TCSAFLUSH, &tty);
1549
1550     fprintf(stderr, "char device redirected to %s\n", slave_name);
1551     return qemu_chr_open_fd(master_fd, master_fd);
1552 }
1553
1554 static void tty_serial_init(int fd, int speed, 
1555                             int parity, int data_bits, int stop_bits)
1556 {
1557     struct termios tty;
1558     speed_t spd;
1559
1560 #if 0
1561     printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1562            speed, parity, data_bits, stop_bits);
1563 #endif
1564     tcgetattr (fd, &tty);
1565
1566     switch(speed) {
1567     case 50:
1568         spd = B50;
1569         break;
1570     case 75:
1571         spd = B75;
1572         break;
1573     case 300:
1574         spd = B300;
1575         break;
1576     case 600:
1577         spd = B600;
1578         break;
1579     case 1200:
1580         spd = B1200;
1581         break;
1582     case 2400:
1583         spd = B2400;
1584         break;
1585     case 4800:
1586         spd = B4800;
1587         break;
1588     case 9600:
1589         spd = B9600;
1590         break;
1591     case 19200:
1592         spd = B19200;
1593         break;
1594     case 38400:
1595         spd = B38400;
1596         break;
1597     case 57600:
1598         spd = B57600;
1599         break;
1600     default:
1601     case 115200:
1602         spd = B115200;
1603         break;
1604     }
1605
1606     cfsetispeed(&tty, spd);
1607     cfsetospeed(&tty, spd);
1608
1609     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1610                           |INLCR|IGNCR|ICRNL|IXON);
1611     tty.c_oflag |= OPOST;
1612     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1613     tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1614     switch(data_bits) {
1615     default:
1616     case 8:
1617         tty.c_cflag |= CS8;
1618         break;
1619     case 7:
1620         tty.c_cflag |= CS7;
1621         break;
1622     case 6:
1623         tty.c_cflag |= CS6;
1624         break;
1625     case 5:
1626         tty.c_cflag |= CS5;
1627         break;
1628     }
1629     switch(parity) {
1630     default:
1631     case 'N':
1632         break;
1633     case 'E':
1634         tty.c_cflag |= PARENB;
1635         break;
1636     case 'O':
1637         tty.c_cflag |= PARENB | PARODD;
1638         break;
1639     }
1640     if (stop_bits == 2)
1641         tty.c_cflag |= CSTOPB;
1642     
1643     tcsetattr (fd, TCSANOW, &tty);
1644 }
1645
1646 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1647 {
1648     FDCharDriver *s = chr->opaque;
1649     
1650     switch(cmd) {
1651     case CHR_IOCTL_SERIAL_SET_PARAMS:
1652         {
1653             QEMUSerialSetParams *ssp = arg;
1654             tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1655                             ssp->data_bits, ssp->stop_bits);
1656         }
1657         break;
1658     case CHR_IOCTL_SERIAL_SET_BREAK:
1659         {
1660             int enable = *(int *)arg;
1661             if (enable)
1662                 tcsendbreak(s->fd_in, 1);
1663         }
1664         break;
1665     default:
1666         return -ENOTSUP;
1667     }
1668     return 0;
1669 }
1670
1671 CharDriverState *qemu_chr_open_tty(const char *filename)
1672 {
1673     CharDriverState *chr;
1674     int fd;
1675
1676     fd = open(filename, O_RDWR | O_NONBLOCK);
1677     if (fd < 0)
1678         return NULL;
1679     fcntl(fd, F_SETFL, O_NONBLOCK);
1680     tty_serial_init(fd, 115200, 'N', 8, 1);
1681     chr = qemu_chr_open_fd(fd, fd);
1682     if (!chr)
1683         return NULL;
1684     chr->chr_ioctl = tty_serial_ioctl;
1685     return chr;
1686 }
1687
1688 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1689 {
1690     int fd = (int)chr->opaque;
1691     uint8_t b;
1692
1693     switch(cmd) {
1694     case CHR_IOCTL_PP_READ_DATA:
1695         if (ioctl(fd, PPRDATA, &b) < 0)
1696             return -ENOTSUP;
1697         *(uint8_t *)arg = b;
1698         break;
1699     case CHR_IOCTL_PP_WRITE_DATA:
1700         b = *(uint8_t *)arg;
1701         if (ioctl(fd, PPWDATA, &b) < 0)
1702             return -ENOTSUP;
1703         break;
1704     case CHR_IOCTL_PP_READ_CONTROL:
1705         if (ioctl(fd, PPRCONTROL, &b) < 0)
1706             return -ENOTSUP;
1707         *(uint8_t *)arg = b;
1708         break;
1709     case CHR_IOCTL_PP_WRITE_CONTROL:
1710         b = *(uint8_t *)arg;
1711         if (ioctl(fd, PPWCONTROL, &b) < 0)
1712             return -ENOTSUP;
1713         break;
1714     case CHR_IOCTL_PP_READ_STATUS:
1715         if (ioctl(fd, PPRSTATUS, &b) < 0)
1716             return -ENOTSUP;
1717         *(uint8_t *)arg = b;
1718         break;
1719     default:
1720         return -ENOTSUP;
1721     }
1722     return 0;
1723 }
1724
1725 CharDriverState *qemu_chr_open_pp(const char *filename)
1726 {
1727     CharDriverState *chr;
1728     int fd;
1729
1730     fd = open(filename, O_RDWR);
1731     if (fd < 0)
1732         return NULL;
1733
1734     if (ioctl(fd, PPCLAIM) < 0) {
1735         close(fd);
1736         return NULL;
1737     }
1738
1739     chr = qemu_mallocz(sizeof(CharDriverState));
1740     if (!chr) {
1741         close(fd);
1742         return NULL;
1743     }
1744     chr->opaque = (void *)fd;
1745     chr->chr_write = null_chr_write;
1746     chr->chr_add_read_handler = null_chr_add_read_handler;
1747     chr->chr_ioctl = pp_ioctl;
1748     return chr;
1749 }
1750
1751 #else
1752 CharDriverState *qemu_chr_open_pty(void)
1753 {
1754     return NULL;
1755 }
1756 #endif
1757
1758 #endif /* !defined(_WIN32) */
1759
1760 #ifdef _WIN32
1761 typedef struct {
1762     IOCanRWHandler *fd_can_read; 
1763     IOReadHandler *fd_read;
1764     void *win_opaque;
1765     int max_size;
1766     HANDLE hcom, hrecv, hsend;
1767     OVERLAPPED orecv, osend;
1768     BOOL fpipe;
1769     DWORD len;
1770 } WinCharState;
1771
1772 #define NSENDBUF 2048
1773 #define NRECVBUF 2048
1774 #define MAXCONNECT 1
1775 #define NTIMEOUT 5000
1776
1777 static int win_chr_poll(void *opaque);
1778 static int win_chr_pipe_poll(void *opaque);
1779
1780 static void win_chr_close2(WinCharState *s)
1781 {
1782     if (s->hsend) {
1783         CloseHandle(s->hsend);
1784         s->hsend = NULL;
1785     }
1786     if (s->hrecv) {
1787         CloseHandle(s->hrecv);
1788         s->hrecv = NULL;
1789     }
1790     if (s->hcom) {
1791         CloseHandle(s->hcom);
1792         s->hcom = NULL;
1793     }
1794     if (s->fpipe)
1795         qemu_del_polling_cb(win_chr_pipe_poll, s);
1796     else
1797         qemu_del_polling_cb(win_chr_poll, s);
1798 }
1799
1800 static void win_chr_close(CharDriverState *chr)
1801 {
1802     WinCharState *s = chr->opaque;
1803     win_chr_close2(s);
1804 }
1805
1806 static int win_chr_init(WinCharState *s, const char *filename)
1807 {
1808     COMMCONFIG comcfg;
1809     COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1810     COMSTAT comstat;
1811     DWORD size;
1812     DWORD err;
1813     
1814     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1815     if (!s->hsend) {
1816         fprintf(stderr, "Failed CreateEvent\n");
1817         goto fail;
1818     }
1819     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1820     if (!s->hrecv) {
1821         fprintf(stderr, "Failed CreateEvent\n");
1822         goto fail;
1823     }
1824
1825     s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1826                       OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1827     if (s->hcom == INVALID_HANDLE_VALUE) {
1828         fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1829         s->hcom = NULL;
1830         goto fail;
1831     }
1832     
1833     if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1834         fprintf(stderr, "Failed SetupComm\n");
1835         goto fail;
1836     }
1837     
1838     ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1839     size = sizeof(COMMCONFIG);
1840     GetDefaultCommConfig(filename, &comcfg, &size);
1841     comcfg.dcb.DCBlength = sizeof(DCB);
1842     CommConfigDialog(filename, NULL, &comcfg);
1843
1844     if (!SetCommState(s->hcom, &comcfg.dcb)) {
1845         fprintf(stderr, "Failed SetCommState\n");
1846         goto fail;
1847     }
1848
1849     if (!SetCommMask(s->hcom, EV_ERR)) {
1850         fprintf(stderr, "Failed SetCommMask\n");
1851         goto fail;
1852     }
1853
1854     cto.ReadIntervalTimeout = MAXDWORD;
1855     if (!SetCommTimeouts(s->hcom, &cto)) {
1856         fprintf(stderr, "Failed SetCommTimeouts\n");
1857         goto fail;
1858     }
1859     
1860     if (!ClearCommError(s->hcom, &err, &comstat)) {
1861         fprintf(stderr, "Failed ClearCommError\n");
1862         goto fail;
1863     }
1864     qemu_add_polling_cb(win_chr_poll, s);
1865     return 0;
1866
1867  fail:
1868     win_chr_close2(s);
1869     return -1;
1870 }
1871
1872 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1873 {
1874     WinCharState *s = chr->opaque;
1875     DWORD len, ret, size, err;
1876
1877     len = len1;
1878     ZeroMemory(&s->osend, sizeof(s->osend));
1879     s->osend.hEvent = s->hsend;
1880     while (len > 0) {
1881         if (s->hsend)
1882             ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1883         else
1884             ret = WriteFile(s->hcom, buf, len, &size, NULL);
1885         if (!ret) {
1886             err = GetLastError();
1887             if (err == ERROR_IO_PENDING) {
1888                 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1889                 if (ret) {
1890                     buf += size;
1891                     len -= size;
1892                 } else {
1893                     break;
1894                 }
1895             } else {
1896                 break;
1897             }
1898         } else {
1899             buf += size;
1900             len -= size;
1901         }
1902     }
1903     return len1 - len;
1904 }
1905
1906 static int win_chr_read_poll(WinCharState *s)
1907 {
1908     s->max_size = s->fd_can_read(s->win_opaque);
1909     return s->max_size;
1910 }
1911             
1912 static void win_chr_readfile(WinCharState *s)
1913 {
1914     int ret, err;
1915     uint8_t buf[1024];
1916     DWORD size;
1917     
1918     ZeroMemory(&s->orecv, sizeof(s->orecv));
1919     s->orecv.hEvent = s->hrecv;
1920     ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1921     if (!ret) {
1922         err = GetLastError();
1923         if (err == ERROR_IO_PENDING) {
1924             ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1925         }
1926     }
1927
1928     if (size > 0) {
1929         s->fd_read(s->win_opaque, buf, size);
1930     }
1931 }
1932
1933 static void win_chr_read(WinCharState *s)
1934 {
1935     if (s->len > s->max_size)
1936         s->len = s->max_size;
1937     if (s->len == 0)
1938         return;
1939     
1940     win_chr_readfile(s);
1941 }
1942
1943 static int win_chr_poll(void *opaque)
1944 {
1945     WinCharState *s = opaque;
1946     COMSTAT status;
1947     DWORD comerr;
1948     
1949     ClearCommError(s->hcom, &comerr, &status);
1950     if (status.cbInQue > 0) {
1951         s->len = status.cbInQue;
1952         win_chr_read_poll(s);
1953         win_chr_read(s);
1954         return 1;
1955     }
1956     return 0;
1957 }
1958
1959 static void win_chr_add_read_handler(CharDriverState *chr, 
1960                                     IOCanRWHandler *fd_can_read, 
1961                                     IOReadHandler *fd_read, void *opaque)
1962 {
1963     WinCharState *s = chr->opaque;
1964
1965     s->fd_can_read = fd_can_read;
1966     s->fd_read = fd_read;
1967     s->win_opaque = opaque;
1968 }
1969
1970 CharDriverState *qemu_chr_open_win(const char *filename)
1971 {
1972     CharDriverState *chr;
1973     WinCharState *s;
1974     
1975     chr = qemu_mallocz(sizeof(CharDriverState));
1976     if (!chr)
1977         return NULL;
1978     s = qemu_mallocz(sizeof(WinCharState));
1979     if (!s) {
1980         free(chr);
1981         return NULL;
1982     }
1983     chr->opaque = s;
1984     chr->chr_write = win_chr_write;
1985     chr->chr_add_read_handler = win_chr_add_read_handler;
1986     chr->chr_close = win_chr_close;
1987
1988     if (win_chr_init(s, filename) < 0) {
1989         free(s);
1990         free(chr);
1991         return NULL;
1992     }
1993     return chr;
1994 }
1995
1996 static int win_chr_pipe_poll(void *opaque)
1997 {
1998     WinCharState *s = opaque;
1999     DWORD size;
2000
2001     PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2002     if (size > 0) {
2003         s->len = size;
2004         win_chr_read_poll(s);
2005         win_chr_read(s);
2006         return 1;
2007     }
2008     return 0;
2009 }
2010
2011 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2012 {
2013     OVERLAPPED ov;
2014     int ret;
2015     DWORD size;
2016     char openname[256];
2017     
2018     s->fpipe = TRUE;
2019
2020     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2021     if (!s->hsend) {
2022         fprintf(stderr, "Failed CreateEvent\n");
2023         goto fail;
2024     }
2025     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2026     if (!s->hrecv) {
2027         fprintf(stderr, "Failed CreateEvent\n");
2028         goto fail;
2029     }
2030     
2031     snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2032     s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2033                               PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2034                               PIPE_WAIT,
2035                               MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2036     if (s->hcom == INVALID_HANDLE_VALUE) {
2037         fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2038         s->hcom = NULL;
2039         goto fail;
2040     }
2041
2042     ZeroMemory(&ov, sizeof(ov));
2043     ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2044     ret = ConnectNamedPipe(s->hcom, &ov);
2045     if (ret) {
2046         fprintf(stderr, "Failed ConnectNamedPipe\n");
2047         goto fail;
2048     }
2049
2050     ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2051     if (!ret) {
2052         fprintf(stderr, "Failed GetOverlappedResult\n");
2053         if (ov.hEvent) {
2054             CloseHandle(ov.hEvent);
2055             ov.hEvent = NULL;
2056         }
2057         goto fail;
2058     }
2059
2060     if (ov.hEvent) {
2061         CloseHandle(ov.hEvent);
2062         ov.hEvent = NULL;
2063     }
2064     qemu_add_polling_cb(win_chr_pipe_poll, s);
2065     return 0;
2066
2067  fail:
2068     win_chr_close2(s);
2069     return -1;
2070 }
2071
2072
2073 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2074 {
2075     CharDriverState *chr;
2076     WinCharState *s;
2077
2078     chr = qemu_mallocz(sizeof(CharDriverState));
2079     if (!chr)
2080         return NULL;
2081     s = qemu_mallocz(sizeof(WinCharState));
2082     if (!s) {
2083         free(chr);
2084         return NULL;
2085     }
2086     chr->opaque = s;
2087     chr->chr_write = win_chr_write;
2088     chr->chr_add_read_handler = win_chr_add_read_handler;
2089     chr->chr_close = win_chr_close;
2090     
2091     if (win_chr_pipe_init(s, filename) < 0) {
2092         free(s);
2093         free(chr);
2094         return NULL;
2095     }
2096     return chr;
2097 }
2098
2099 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2100 {
2101     CharDriverState *chr;
2102     WinCharState *s;
2103
2104     chr = qemu_mallocz(sizeof(CharDriverState));
2105     if (!chr)
2106         return NULL;
2107     s = qemu_mallocz(sizeof(WinCharState));
2108     if (!s) {
2109         free(chr);
2110         return NULL;
2111     }
2112     s->hcom = fd_out;
2113     chr->opaque = s;
2114     chr->chr_write = win_chr_write;
2115     chr->chr_add_read_handler = win_chr_add_read_handler;
2116     return chr;
2117 }
2118     
2119 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2120 {
2121     HANDLE fd_out;
2122     
2123     fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2124                         OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2125     if (fd_out == INVALID_HANDLE_VALUE)
2126         return NULL;
2127
2128     return qemu_chr_open_win_file(fd_out);
2129 }
2130 #endif
2131
2132 /***********************************************************/
2133 /* UDP Net console */
2134
2135 typedef struct {
2136     IOCanRWHandler *fd_can_read;
2137     IOReadHandler *fd_read;
2138     void *fd_opaque;
2139     int fd;
2140     struct sockaddr_in daddr;
2141     char buf[1024];
2142     int bufcnt;
2143     int bufptr;
2144     int max_size;
2145 } NetCharDriver;
2146
2147 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2148 {
2149     NetCharDriver *s = chr->opaque;
2150
2151     return sendto(s->fd, buf, len, 0,
2152                   (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2153 }
2154
2155 static int udp_chr_read_poll(void *opaque)
2156 {
2157     CharDriverState *chr = opaque;
2158     NetCharDriver *s = chr->opaque;
2159
2160     s->max_size = s->fd_can_read(s->fd_opaque);
2161
2162     /* If there were any stray characters in the queue process them
2163      * first
2164      */
2165     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2166         s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2167         s->bufptr++;
2168         s->max_size = s->fd_can_read(s->fd_opaque);
2169     }
2170     return s->max_size;
2171 }
2172
2173 static void udp_chr_read(void *opaque)
2174 {
2175     CharDriverState *chr = opaque;
2176     NetCharDriver *s = chr->opaque;
2177
2178     if (s->max_size == 0)
2179         return;
2180     s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2181     s->bufptr = s->bufcnt;
2182     if (s->bufcnt <= 0)
2183         return;
2184
2185     s->bufptr = 0;
2186     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2187         s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2188         s->bufptr++;
2189         s->max_size = s->fd_can_read(s->fd_opaque);
2190     }
2191 }
2192
2193 static void udp_chr_add_read_handler(CharDriverState *chr,
2194                                     IOCanRWHandler *fd_can_read,
2195                                     IOReadHandler *fd_read, void *opaque)
2196 {
2197     NetCharDriver *s = chr->opaque;
2198
2199     if (s->fd >= 0) {
2200         s->fd_can_read = fd_can_read;
2201         s->fd_read = fd_read;
2202         s->fd_opaque = opaque;
2203         qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2204                              udp_chr_read, NULL, chr);
2205     }
2206 }
2207
2208 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2209 int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2210 int parse_host_src_port(struct sockaddr_in *haddr,
2211                         struct sockaddr_in *saddr,
2212                         const char *str);
2213
2214 CharDriverState *qemu_chr_open_udp(const char *def)
2215 {
2216     CharDriverState *chr = NULL;
2217     NetCharDriver *s = NULL;
2218     int fd = -1;
2219     struct sockaddr_in saddr;
2220
2221     chr = qemu_mallocz(sizeof(CharDriverState));
2222     if (!chr)
2223         goto return_err;
2224     s = qemu_mallocz(sizeof(NetCharDriver));
2225     if (!s)
2226         goto return_err;
2227
2228     fd = socket(PF_INET, SOCK_DGRAM, 0);
2229     if (fd < 0) {
2230         perror("socket(PF_INET, SOCK_DGRAM)");
2231         goto return_err;
2232     }
2233
2234     if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2235         printf("Could not parse: %s\n", def);
2236         goto return_err;
2237     }
2238
2239     if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2240     {
2241         perror("bind");
2242         goto return_err;
2243     }
2244
2245     s->fd = fd;
2246     s->bufcnt = 0;
2247     s->bufptr = 0;
2248     chr->opaque = s;
2249     chr->chr_write = udp_chr_write;
2250     chr->chr_add_read_handler = udp_chr_add_read_handler;
2251     return chr;
2252
2253 return_err:
2254     if (chr)
2255         free(chr);
2256     if (s)
2257         free(s);
2258     if (fd >= 0)
2259         closesocket(fd);
2260     return NULL;
2261 }
2262
2263 /***********************************************************/
2264 /* TCP Net console */
2265
2266 typedef struct {
2267     IOCanRWHandler *fd_can_read;
2268     IOReadHandler *fd_read;
2269     void *fd_opaque;
2270     int fd, listen_fd;
2271     int connected;
2272     int max_size;
2273     int do_telnetopt;
2274     int is_unix;
2275 } TCPCharDriver;
2276
2277 static void tcp_chr_accept(void *opaque);
2278
2279 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2280 {
2281     TCPCharDriver *s = chr->opaque;
2282     if (s->connected) {
2283         return send_all(s->fd, buf, len);
2284     } else {
2285         /* XXX: indicate an error ? */
2286         return len;
2287     }
2288 }
2289
2290 static int tcp_chr_read_poll(void *opaque)
2291 {
2292     CharDriverState *chr = opaque;
2293     TCPCharDriver *s = chr->opaque;
2294     if (!s->connected)
2295         return 0;
2296     if (!s->fd_can_read)
2297         return 0;
2298     s->max_size = s->fd_can_read(s->fd_opaque);
2299     return s->max_size;
2300 }
2301
2302 #define IAC 255
2303 #define IAC_BREAK 243
2304 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2305                                       TCPCharDriver *s,
2306                                       char *buf, int *size)
2307 {
2308     /* Handle any telnet client's basic IAC options to satisfy char by
2309      * char mode with no echo.  All IAC options will be removed from
2310      * the buf and the do_telnetopt variable will be used to track the
2311      * state of the width of the IAC information.
2312      *
2313      * IAC commands come in sets of 3 bytes with the exception of the
2314      * "IAC BREAK" command and the double IAC.
2315      */
2316
2317     int i;
2318     int j = 0;
2319
2320     for (i = 0; i < *size; i++) {
2321         if (s->do_telnetopt > 1) {
2322             if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2323                 /* Double IAC means send an IAC */
2324                 if (j != i)
2325                     buf[j] = buf[i];
2326                 j++;
2327                 s->do_telnetopt = 1;
2328             } else {
2329                 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2330                     /* Handle IAC break commands by sending a serial break */
2331                     chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2332                     s->do_telnetopt++;
2333                 }
2334                 s->do_telnetopt++;
2335             }
2336             if (s->do_telnetopt >= 4) {
2337                 s->do_telnetopt = 1;
2338             }
2339         } else {
2340             if ((unsigned char)buf[i] == IAC) {
2341                 s->do_telnetopt = 2;
2342             } else {
2343                 if (j != i)
2344                     buf[j] = buf[i];
2345                 j++;
2346             }
2347         }
2348     }
2349     *size = j;
2350 }
2351
2352 static void tcp_chr_read(void *opaque)
2353 {
2354     CharDriverState *chr = opaque;
2355     TCPCharDriver *s = chr->opaque;
2356     uint8_t buf[1024];
2357     int len, size;
2358
2359     if (!s->connected || s->max_size <= 0)
2360         return;
2361     len = sizeof(buf);
2362     if (len > s->max_size)
2363         len = s->max_size;
2364     size = recv(s->fd, buf, len, 0);
2365     if (size == 0) {
2366         /* connection closed */
2367         s->connected = 0;
2368         if (s->listen_fd >= 0) {
2369             qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2370         }
2371         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2372         closesocket(s->fd);
2373         s->fd = -1;
2374     } else if (size > 0) {
2375         if (s->do_telnetopt)
2376             tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2377         if (size > 0)
2378             s->fd_read(s->fd_opaque, buf, size);
2379     }
2380 }
2381
2382 static void tcp_chr_add_read_handler(CharDriverState *chr,
2383                                      IOCanRWHandler *fd_can_read,
2384                                     IOReadHandler *fd_read, void *opaque)
2385 {
2386     TCPCharDriver *s = chr->opaque;
2387
2388     s->fd_can_read = fd_can_read;
2389     s->fd_read = fd_read;
2390     s->fd_opaque = opaque;
2391 }
2392
2393 static void tcp_chr_connect(void *opaque)
2394 {
2395     CharDriverState *chr = opaque;
2396     TCPCharDriver *s = chr->opaque;
2397
2398     s->connected = 1;
2399     qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2400                          tcp_chr_read, NULL, chr);
2401 }
2402
2403 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2404 static void tcp_chr_telnet_init(int fd)
2405 {
2406     char buf[3];
2407     /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2408     IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2409     send(fd, (char *)buf, 3, 0);
2410     IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2411     send(fd, (char *)buf, 3, 0);
2412     IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2413     send(fd, (char *)buf, 3, 0);
2414     IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2415     send(fd, (char *)buf, 3, 0);
2416 }
2417
2418 static void tcp_chr_accept(void *opaque)
2419 {
2420     CharDriverState *chr = opaque;
2421     TCPCharDriver *s = chr->opaque;
2422     struct sockaddr_in saddr;
2423 #ifndef _WIN32
2424     struct sockaddr_un uaddr;
2425 #endif
2426     struct sockaddr *addr;
2427     socklen_t len;
2428     int fd;
2429
2430     for(;;) {
2431 #ifndef _WIN32
2432         if (s->is_unix) {
2433             len = sizeof(uaddr);
2434             addr = (struct sockaddr *)&uaddr;
2435         } else
2436 #endif
2437         {
2438             len = sizeof(saddr);
2439             addr = (struct sockaddr *)&saddr;
2440         }
2441         fd = accept(s->listen_fd, addr, &len);
2442         if (fd < 0 && errno != EINTR) {
2443             return;
2444         } else if (fd >= 0) {
2445             if (s->do_telnetopt)
2446                 tcp_chr_telnet_init(fd);
2447             break;
2448         }
2449     }
2450     socket_set_nonblock(fd);
2451     s->fd = fd;
2452     qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2453     tcp_chr_connect(chr);
2454 }
2455
2456 static void tcp_chr_close(CharDriverState *chr)
2457 {
2458     TCPCharDriver *s = chr->opaque;
2459     if (s->fd >= 0)
2460         closesocket(s->fd);
2461     if (s->listen_fd >= 0)
2462         closesocket(s->listen_fd);
2463     qemu_free(s);
2464 }
2465
2466 static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2467                                           int is_telnet,
2468                                           int is_unix)
2469 {
2470     CharDriverState *chr = NULL;
2471     TCPCharDriver *s = NULL;
2472     int fd = -1, ret, err, val;
2473     int is_listen = 0;
2474     int is_waitconnect = 1;
2475     const char *ptr;
2476     struct sockaddr_in saddr;
2477 #ifndef _WIN32
2478     struct sockaddr_un uaddr;
2479 #endif
2480     struct sockaddr *addr;
2481     socklen_t addrlen;
2482
2483 #ifndef _WIN32
2484     if (is_unix) {
2485         addr = (struct sockaddr *)&uaddr;
2486         addrlen = sizeof(uaddr);
2487         if (parse_unix_path(&uaddr, host_str) < 0)
2488             goto fail;
2489     } else
2490 #endif
2491     {
2492         addr = (struct sockaddr *)&saddr;
2493         addrlen = sizeof(saddr);
2494         if (parse_host_port(&saddr, host_str) < 0)
2495             goto fail;
2496     }
2497
2498     ptr = host_str;
2499     while((ptr = strchr(ptr,','))) {
2500         ptr++;
2501         if (!strncmp(ptr,"server",6)) {
2502             is_listen = 1;
2503         } else if (!strncmp(ptr,"nowait",6)) {
2504             is_waitconnect = 0;
2505         } else {
2506             printf("Unknown option: %s\n", ptr);
2507             goto fail;
2508         }
2509     }
2510     if (!is_listen)
2511         is_waitconnect = 0;
2512
2513     chr = qemu_mallocz(sizeof(CharDriverState));
2514     if (!chr)
2515         goto fail;
2516     s = qemu_mallocz(sizeof(TCPCharDriver));
2517     if (!s)
2518         goto fail;
2519
2520 #ifndef _WIN32
2521     if (is_unix)
2522         fd = socket(PF_UNIX, SOCK_STREAM, 0);
2523     else
2524 #endif
2525         fd = socket(PF_INET, SOCK_STREAM, 0);
2526         
2527     if (fd < 0) 
2528         goto fail;
2529
2530     if (!is_waitconnect)
2531         socket_set_nonblock(fd);
2532
2533     s->connected = 0;
2534     s->fd = -1;
2535     s->listen_fd = -1;
2536     s->is_unix = is_unix;
2537
2538     chr->opaque = s;
2539     chr->chr_write = tcp_chr_write;
2540     chr->chr_add_read_handler = tcp_chr_add_read_handler;
2541     chr->chr_close = tcp_chr_close;
2542
2543     if (is_listen) {
2544         /* allow fast reuse */
2545 #ifndef _WIN32
2546         if (is_unix) {
2547             char path[109];
2548             strncpy(path, uaddr.sun_path, 108);
2549             path[108] = 0;
2550             unlink(path);
2551         } else
2552 #endif
2553         {
2554             val = 1;
2555             setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2556         }
2557         
2558         ret = bind(fd, addr, addrlen);
2559         if (ret < 0)
2560             goto fail;
2561
2562         ret = listen(fd, 0);
2563         if (ret < 0)
2564             goto fail;
2565
2566         s->listen_fd = fd;
2567         qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2568         if (is_telnet)
2569             s->do_telnetopt = 1;
2570     } else {
2571         for(;;) {
2572             ret = connect(fd, addr, addrlen);
2573             if (ret < 0) {
2574                 err = socket_error();
2575                 if (err == EINTR || err == EWOULDBLOCK) {
2576                 } else if (err == EINPROGRESS) {
2577                     break;
2578                 } else {
2579                     goto fail;
2580                 }
2581             } else {
2582                 s->connected = 1;
2583                 break;
2584             }
2585         }
2586         s->fd = fd;
2587         if (s->connected)
2588             tcp_chr_connect(chr);
2589         else
2590             qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2591     }
2592     
2593     if (is_listen && is_waitconnect) {
2594         printf("QEMU waiting for connection on: %s\n", host_str);
2595         tcp_chr_accept(chr);
2596         socket_set_nonblock(s->listen_fd);
2597     }
2598
2599     return chr;
2600  fail:
2601     if (fd >= 0)
2602         closesocket(fd);
2603     qemu_free(s);
2604     qemu_free(chr);
2605     return NULL;
2606 }
2607
2608 CharDriverState *qemu_chr_open(const char *filename)
2609 {
2610     const char *p;
2611
2612     if (!strcmp(filename, "vc")) {
2613         return text_console_init(&display_state);
2614     } else if (!strcmp(filename, "null")) {
2615         return qemu_chr_open_null();
2616     } else 
2617     if (strstart(filename, "tcp:", &p)) {
2618         return qemu_chr_open_tcp(p, 0, 0);
2619     } else
2620     if (strstart(filename, "telnet:", &p)) {
2621         return qemu_chr_open_tcp(p, 1, 0);
2622     } else
2623     if (strstart(filename, "udp:", &p)) {
2624         return qemu_chr_open_udp(p);
2625     } else
2626 #ifndef _WIN32
2627     if (strstart(filename, "unix:", &p)) {
2628         return qemu_chr_open_tcp(p, 0, 1);
2629     } else if (strstart(filename, "file:", &p)) {
2630         return qemu_chr_open_file_out(p);
2631     } else if (strstart(filename, "pipe:", &p)) {
2632         return qemu_chr_open_pipe(p);
2633     } else if (!strcmp(filename, "pty")) {
2634         return qemu_chr_open_pty();
2635     } else if (!strcmp(filename, "stdio")) {
2636         return qemu_chr_open_stdio();
2637     } else 
2638 #endif
2639 #if defined(__linux__)
2640     if (strstart(filename, "/dev/parport", NULL)) {
2641         return qemu_chr_open_pp(filename);
2642     } else 
2643     if (strstart(filename, "/dev/", NULL)) {
2644         return qemu_chr_open_tty(filename);
2645     } else 
2646 #endif
2647 #ifdef _WIN32
2648     if (strstart(filename, "COM", NULL)) {
2649         return qemu_chr_open_win(filename);
2650     } else
2651     if (strstart(filename, "pipe:", &p)) {
2652         return qemu_chr_open_win_pipe(p);
2653     } else
2654     if (strstart(filename, "file:", &p)) {
2655         return qemu_chr_open_win_file_out(p);
2656     }
2657 #endif
2658     {
2659         return NULL;
2660     }
2661 }
2662
2663 void qemu_chr_close(CharDriverState *chr)
2664 {
2665     if (chr->chr_close)
2666         chr->chr_close(chr);
2667 }
2668
2669 /***********************************************************/
2670 /* network device redirectors */
2671
2672 void hex_dump(FILE *f, const uint8_t *buf, int size)
2673 {
2674     int len, i, j, c;
2675
2676     for(i=0;i<size;i+=16) {
2677         len = size - i;
2678         if (len > 16)
2679             len = 16;
2680         fprintf(f, "%08x ", i);
2681         for(j=0;j<16;j++) {
2682             if (j < len)
2683                 fprintf(f, " %02x", buf[i+j]);
2684             else
2685                 fprintf(f, "   ");
2686         }
2687         fprintf(f, " ");
2688         for(j=0;j<len;j++) {
2689             c = buf[i+j];
2690             if (c < ' ' || c > '~')
2691                 c = '.';
2692             fprintf(f, "%c", c);
2693         }
2694         fprintf(f, "\n");
2695     }
2696 }
2697
2698 static int parse_macaddr(uint8_t *macaddr, const char *p)
2699 {
2700     int i;
2701     for(i = 0; i < 6; i++) {
2702         macaddr[i] = strtol(p, (char **)&p, 16);
2703         if (i == 5) {
2704             if (*p != '\0') 
2705                 return -1;
2706         } else {
2707             if (*p != ':') 
2708                 return -1;
2709             p++;
2710         }
2711     }
2712     return 0;
2713 }
2714
2715 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2716 {
2717     const char *p, *p1;
2718     int len;
2719     p = *pp;
2720     p1 = strchr(p, sep);
2721     if (!p1)
2722         return -1;
2723     len = p1 - p;
2724     p1++;
2725     if (buf_size > 0) {
2726         if (len > buf_size - 1)
2727             len = buf_size - 1;
2728         memcpy(buf, p, len);
2729         buf[len] = '\0';
2730     }
2731     *pp = p1;
2732     return 0;
2733 }
2734
2735 int parse_host_src_port(struct sockaddr_in *haddr,
2736                         struct sockaddr_in *saddr,
2737                         const char *input_str)
2738 {
2739     char *str = strdup(input_str);
2740     char *host_str = str;
2741     char *src_str;
2742     char *ptr;
2743
2744     /*
2745      * Chop off any extra arguments at the end of the string which
2746      * would start with a comma, then fill in the src port information
2747      * if it was provided else use the "any address" and "any port".
2748      */
2749     if ((ptr = strchr(str,',')))
2750         *ptr = '\0';
2751
2752     if ((src_str = strchr(input_str,'@'))) {
2753         *src_str = '\0';
2754         src_str++;
2755     }
2756
2757     if (parse_host_port(haddr, host_str) < 0)
2758         goto fail;
2759
2760     if (!src_str || *src_str == '\0')
2761         src_str = ":0";
2762
2763     if (parse_host_port(saddr, src_str) < 0)
2764         goto fail;
2765
2766     free(str);
2767     return(0);
2768
2769 fail:
2770     free(str);
2771     return -1;
2772 }
2773
2774 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2775 {
2776     char buf[512];
2777     struct hostent *he;
2778     const char *p, *r;
2779     int port;
2780
2781     p = str;
2782     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2783         return -1;
2784     saddr->sin_family = AF_INET;
2785     if (buf[0] == '\0') {
2786         saddr->sin_addr.s_addr = 0;
2787     } else {
2788         if (isdigit(buf[0])) {
2789             if (!inet_aton(buf, &saddr->sin_addr))
2790                 return -1;
2791         } else {
2792             if ((he = gethostbyname(buf)) == NULL)
2793                 return - 1;
2794             saddr->sin_addr = *(struct in_addr *)he->h_addr;
2795         }
2796     }
2797     port = strtol(p, (char **)&r, 0);
2798     if (r == p)
2799         return -1;
2800     saddr->sin_port = htons(port);
2801     return 0;
2802 }
2803
2804 int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2805 {
2806     const char *p;
2807     int len;
2808
2809     len = MIN(108, strlen(str));
2810     p = strchr(str, ',');
2811     if (p)
2812         len = MIN(len, p - str);
2813
2814     memset(uaddr, 0, sizeof(*uaddr));
2815
2816     uaddr->sun_family = AF_UNIX;
2817     memcpy(uaddr->sun_path, str, len);
2818
2819     return 0;
2820 }
2821
2822 /* find or alloc a new VLAN */
2823 VLANState *qemu_find_vlan(int id)
2824 {
2825     VLANState **pvlan, *vlan;
2826     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2827         if (vlan->id == id)
2828             return vlan;
2829     }
2830     vlan = qemu_mallocz(sizeof(VLANState));
2831     if (!vlan)
2832         return NULL;
2833     vlan->id = id;
2834     vlan->next = NULL;
2835     pvlan = &first_vlan;
2836     while (*pvlan != NULL)
2837         pvlan = &(*pvlan)->next;
2838     *pvlan = vlan;
2839     return vlan;
2840 }
2841
2842 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2843                                       IOReadHandler *fd_read,
2844                                       IOCanRWHandler *fd_can_read,
2845                                       void *opaque)
2846 {
2847     VLANClientState *vc, **pvc;
2848     vc = qemu_mallocz(sizeof(VLANClientState));
2849     if (!vc)
2850         return NULL;
2851     vc->fd_read = fd_read;
2852     vc->fd_can_read = fd_can_read;
2853     vc->opaque = opaque;
2854     vc->vlan = vlan;
2855
2856     vc->next = NULL;
2857     pvc = &vlan->first_client;
2858     while (*pvc != NULL)
2859         pvc = &(*pvc)->next;
2860     *pvc = vc;
2861     return vc;
2862 }
2863
2864 int qemu_can_send_packet(VLANClientState *vc1)
2865 {
2866     VLANState *vlan = vc1->vlan;
2867     VLANClientState *vc;
2868
2869     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2870         if (vc != vc1) {
2871             if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2872                 return 0;
2873         }
2874     }
2875     return 1;
2876 }
2877
2878 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2879 {
2880     VLANState *vlan = vc1->vlan;
2881     VLANClientState *vc;
2882
2883 #if 0
2884     printf("vlan %d send:\n", vlan->id);
2885     hex_dump(stdout, buf, size);
2886 #endif
2887     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2888         if (vc != vc1) {
2889             vc->fd_read(vc->opaque, buf, size);
2890         }
2891     }
2892 }
2893
2894 #if defined(CONFIG_SLIRP)
2895
2896 /* slirp network adapter */
2897
2898 static int slirp_inited;
2899 static VLANClientState *slirp_vc;
2900
2901 int slirp_can_output(void)
2902 {
2903     return !slirp_vc || qemu_can_send_packet(slirp_vc);
2904 }
2905
2906 void slirp_output(const uint8_t *pkt, int pkt_len)
2907 {
2908 #if 0
2909     printf("slirp output:\n");
2910     hex_dump(stdout, pkt, pkt_len);
2911 #endif
2912     if (!slirp_vc)
2913         return;
2914     qemu_send_packet(slirp_vc, pkt, pkt_len);
2915 }
2916
2917 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2918 {
2919 #if 0
2920     printf("slirp input:\n");
2921     hex_dump(stdout, buf, size);
2922 #endif
2923     slirp_input(buf, size);
2924 }
2925
2926 static int net_slirp_init(VLANState *vlan)
2927 {
2928     if (!slirp_inited) {
2929         slirp_inited = 1;
2930         slirp_init();
2931     }
2932     slirp_vc = qemu_new_vlan_client(vlan, 
2933                                     slirp_receive, NULL, NULL);
2934     snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2935     return 0;
2936 }
2937
2938 static void net_slirp_redir(const char *redir_str)
2939 {
2940     int is_udp;
2941     char buf[256], *r;
2942     const char *p;
2943     struct in_addr guest_addr;
2944     int host_port, guest_port;
2945     
2946     if (!slirp_inited) {
2947         slirp_inited = 1;
2948         slirp_init();
2949     }
2950
2951     p = redir_str;
2952     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2953         goto fail;
2954     if (!strcmp(buf, "tcp")) {
2955         is_udp = 0;
2956     } else if (!strcmp(buf, "udp")) {
2957         is_udp = 1;
2958     } else {
2959         goto fail;
2960     }
2961
2962     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2963         goto fail;
2964     host_port = strtol(buf, &r, 0);
2965     if (r == buf)
2966         goto fail;
2967
2968     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2969         goto fail;
2970     if (buf[0] == '\0') {
2971         pstrcpy(buf, sizeof(buf), "10.0.2.15");
2972     }
2973     if (!inet_aton(buf, &guest_addr))
2974         goto fail;
2975     
2976     guest_port = strtol(p, &r, 0);
2977     if (r == p)
2978         goto fail;
2979     
2980     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2981         fprintf(stderr, "qemu: could not set up redirection\n");
2982         exit(1);
2983     }
2984     return;
2985  fail:
2986     fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2987     exit(1);
2988 }
2989     
2990 #ifndef _WIN32
2991
2992 char smb_dir[1024];
2993
2994 static void smb_exit(void)
2995 {
2996     DIR *d;
2997     struct dirent *de;
2998     char filename[1024];
2999
3000     /* erase all the files in the directory */
3001     d = opendir(smb_dir);
3002     for(;;) {
3003         de = readdir(d);
3004         if (!de)
3005             break;
3006         if (strcmp(de->d_name, ".") != 0 &&
3007             strcmp(de->d_name, "..") != 0) {
3008             snprintf(filename, sizeof(filename), "%s/%s", 
3009                      smb_dir, de->d_name);
3010             unlink(filename);
3011         }
3012     }
3013     closedir(d);
3014     rmdir(smb_dir);
3015 }
3016
3017 /* automatic user mode samba server configuration */
3018 void net_slirp_smb(const char *exported_dir)
3019 {
3020     char smb_conf[1024];
3021     char smb_cmdline[1024];
3022     FILE *f;
3023
3024     if (!slirp_inited) {
3025         slirp_inited = 1;
3026         slirp_init();
3027     }
3028
3029     /* XXX: better tmp dir construction */
3030     snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3031     if (mkdir(smb_dir, 0700) < 0) {
3032         fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3033         exit(1);
3034     }
3035     snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3036     
3037     f = fopen(smb_conf, "w");
3038     if (!f) {
3039         fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3040         exit(1);
3041     }
3042     fprintf(f, 
3043             "[global]\n"
3044             "private dir=%s\n"
3045             "smb ports=0\n"
3046             "socket address=127.0.0.1\n"
3047             "pid directory=%s\n"
3048             "lock directory=%s\n"
3049             "log file=%s/log.smbd\n"
3050             "smb passwd file=%s/smbpasswd\n"
3051             "security = share\n"
3052             "[qemu]\n"
3053             "path=%s\n"
3054             "read only=no\n"
3055             "guest ok=yes\n",
3056             smb_dir,
3057             smb_dir,
3058             smb_dir,
3059             smb_dir,
3060             smb_dir,
3061             exported_dir
3062             );
3063     fclose(f);
3064     atexit(smb_exit);
3065
3066     snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
3067              smb_conf);
3068     
3069     slirp_add_exec(0, smb_cmdline, 4, 139);
3070 }
3071
3072 #endif /* !defined(_WIN32) */
3073
3074 #endif /* CONFIG_SLIRP */
3075
3076 #if !defined(_WIN32)
3077
3078 typedef struct TAPState {
3079     VLANClientState *vc;
3080     int fd;
3081 } TAPState;
3082
3083 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3084 {
3085     TAPState *s = opaque;
3086     int ret;
3087     for(;;) {
3088         ret = write(s->fd, buf, size);
3089         if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3090         } else {
3091             break;
3092         }
3093     }
3094 }
3095
3096 static void tap_send(void *opaque)
3097 {
3098     TAPState *s = opaque;
3099     uint8_t buf[4096];
3100     int size;
3101
3102     size = read(s->fd, buf, sizeof(buf));
3103     if (size > 0) {
3104         qemu_send_packet(s->vc, buf, size);
3105     }
3106 }
3107
3108 /* fd support */
3109
3110 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3111 {
3112     TAPState *s;
3113
3114     s = qemu_mallocz(sizeof(TAPState));
3115     if (!s)
3116         return NULL;
3117     s->fd = fd;
3118     s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3119     qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3120     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3121     return s;
3122 }
3123
3124 #ifdef _BSD
3125 static int tap_open(char *ifname, int ifname_size)
3126 {
3127     int fd;
3128     char *dev;
3129     struct stat s;
3130
3131     fd = open("/dev/tap", O_RDWR);
3132     if (fd < 0) {
3133         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3134         return -1;
3135     }
3136
3137     fstat(fd, &s);
3138     dev = devname(s.st_rdev, S_IFCHR);
3139     pstrcpy(ifname, ifname_size, dev);
3140
3141     fcntl(fd, F_SETFL, O_NONBLOCK);
3142     return fd;
3143 }
3144 #elif defined(__sun__)
3145 static int tap_open(char *ifname, int ifname_size)
3146 {
3147     fprintf(stderr, "warning: tap_open not yet implemented\n");
3148     return -1;
3149 }
3150 #else
3151 static int tap_open(char *ifname, int ifname_size)
3152 {
3153     struct ifreq ifr;
3154     int fd, ret;
3155     
3156     fd = open("/dev/net/tun", O_RDWR);
3157     if (fd < 0) {
3158         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3159         return -1;
3160     }
3161     memset(&ifr, 0, sizeof(ifr));
3162     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3163     if (ifname[0] != '\0')
3164         pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3165     else
3166         pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3167     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3168     if (ret != 0) {
3169         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3170         close(fd);
3171         return -1;
3172     }
3173     pstrcpy(ifname, ifname_size, ifr.ifr_name);
3174     fcntl(fd, F_SETFL, O_NONBLOCK);
3175     return fd;
3176 }
3177 #endif
3178
3179 static int net_tap_init(VLANState *vlan, const char *ifname1,
3180                         const char *setup_script)
3181 {
3182     TAPState *s;
3183     int pid, status, fd;
3184     char *args[3];
3185     char **parg;
3186     char ifname[128];
3187
3188     if (ifname1 != NULL)
3189         pstrcpy(ifname, sizeof(ifname), ifname1);
3190     else
3191         ifname[0] = '\0';
3192     fd = tap_open(ifname, sizeof(ifname));
3193     if (fd < 0)
3194         return -1;
3195
3196     if (!setup_script)
3197         setup_script = "";
3198     if (setup_script[0] != '\0') {
3199         /* try to launch network init script */
3200         pid = fork();
3201         if (pid >= 0) {
3202             if (pid == 0) {
3203                 parg = args;
3204                 *parg++ = (char *)setup_script;
3205                 *parg++ = ifname;
3206                 *parg++ = NULL;
3207                 execv(setup_script, args);
3208                 _exit(1);
3209             }
3210             while (waitpid(pid, &status, 0) != pid);
3211             if (!WIFEXITED(status) ||
3212                 WEXITSTATUS(status) != 0) {
3213                 fprintf(stderr, "%s: could not launch network script\n",
3214                         setup_script);
3215                 return -1;
3216             }
3217         }
3218     }
3219     s = net_tap_fd_init(vlan, fd);
3220     if (!s)
3221         return -1;
3222     snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3223              "tap: ifname=%s setup_script=%s", ifname, setup_script);
3224     return 0;
3225 }
3226
3227 #endif /* !_WIN32 */
3228
3229 /* network connection */
3230 typedef struct NetSocketState {
3231     VLANClientState *vc;
3232     int fd;
3233     int state; /* 0 = getting length, 1 = getting data */
3234     int index;
3235     int packet_len;
3236     uint8_t buf[4096];
3237     struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3238 } NetSocketState;
3239
3240 typedef struct NetSocketListenState {
3241     VLANState *vlan;
3242     int fd;
3243 } NetSocketListenState;
3244
3245 /* XXX: we consider we can send the whole packet without blocking */
3246 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3247 {
3248     NetSocketState *s = opaque;
3249     uint32_t len;
3250     len = htonl(size);
3251
3252     send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3253     send_all(s->fd, buf, size);
3254 }
3255
3256 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3257 {
3258     NetSocketState *s = opaque;
3259     sendto(s->fd, buf, size, 0, 
3260            (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3261 }
3262
3263 static void net_socket_send(void *opaque)
3264 {
3265     NetSocketState *s = opaque;
3266     int l, size, err;
3267     uint8_t buf1[4096];
3268     const uint8_t *buf;
3269
3270     size = recv(s->fd, buf1, sizeof(buf1), 0);
3271     if (size < 0) {
3272         err = socket_error();
3273         if (err != EWOULDBLOCK) 
3274             goto eoc;
3275     } else if (size == 0) {
3276         /* end of connection */
3277     eoc:
3278         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3279         closesocket(s->fd);
3280         return;
3281     }
3282     buf = buf1;
3283     while (size > 0) {
3284         /* reassemble a packet from the network */
3285         switch(s->state) {
3286         case 0:
3287             l = 4 - s->index;
3288             if (l > size)
3289                 l = size;
3290             memcpy(s->buf + s->index, buf, l);
3291             buf += l;
3292             size -= l;
3293             s->index += l;
3294             if (s->index == 4) {
3295                 /* got length */
3296                 s->packet_len = ntohl(*(uint32_t *)s->buf);
3297                 s->index = 0;
3298                 s->state = 1;
3299             }
3300             break;
3301         case 1:
3302             l = s->packet_len - s->index;
3303             if (l > size)
3304                 l = size;
3305             memcpy(s->buf + s->index, buf, l);
3306             s->index += l;
3307             buf += l;
3308             size -= l;
3309             if (s->index >= s->packet_len) {
3310                 qemu_send_packet(s->vc, s->buf, s->packet_len);
3311                 s->index = 0;
3312                 s->state = 0;
3313             }
3314             break;
3315         }
3316     }
3317 }
3318
3319 static void net_socket_send_dgram(void *opaque)
3320 {
3321     NetSocketState *s = opaque;
3322     int size;
3323
3324     size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3325     if (size < 0) 
3326         return;
3327     if (size == 0) {
3328         /* end of connection */
3329         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3330         return;
3331     }
3332     qemu_send_packet(s->vc, s->buf, size);
3333 }
3334
3335 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3336 {
3337     struct ip_mreq imr;
3338     int fd;
3339     int val, ret;
3340     if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3341         fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3342                 inet_ntoa(mcastaddr->sin_addr), 
3343                 (int)ntohl(mcastaddr->sin_addr.s_addr));
3344         return -1;
3345
3346     }
3347     fd = socket(PF_INET, SOCK_DGRAM, 0);
3348     if (fd < 0) {
3349         perror("socket(PF_INET, SOCK_DGRAM)");
3350         return -1;
3351     }
3352
3353     val = 1;
3354     ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3355                    (const char *)&val, sizeof(val));
3356     if (ret < 0) {
3357         perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3358         goto fail;
3359     }
3360
3361     ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3362     if (ret < 0) {
3363         perror("bind");
3364         goto fail;
3365     }
3366     
3367     /* Add host to multicast group */
3368     imr.imr_multiaddr = mcastaddr->sin_addr;
3369     imr.imr_interface.s_addr = htonl(INADDR_ANY);
3370
3371     ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3372                      (const char *)&imr, sizeof(struct ip_mreq));
3373     if (ret < 0) {
3374         perror("setsockopt(IP_ADD_MEMBERSHIP)");
3375         goto fail;
3376     }
3377
3378     /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3379     val = 1;
3380     ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3381                    (const char *)&val, sizeof(val));
3382     if (ret < 0) {
3383         perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3384         goto fail;
3385     }
3386
3387     socket_set_nonblock(fd);
3388     return fd;
3389 fail:
3390     if (fd >= 0) 
3391         closesocket(fd);
3392     return -1;
3393 }
3394
3395 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3396                                           int is_connected)
3397 {
3398     struct sockaddr_in saddr;
3399     int newfd;
3400     socklen_t saddr_len;
3401     NetSocketState *s;
3402
3403     /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3404      * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3405      * by ONLY ONE process: we must "clone" this dgram socket --jjo
3406      */
3407
3408     if (is_connected) {
3409         if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3410             /* must be bound */
3411             if (saddr.sin_addr.s_addr==0) {
3412                 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3413                         fd);
3414                 return NULL;
3415             }
3416             /* clone dgram socket */
3417             newfd = net_socket_mcast_create(&saddr);
3418             if (newfd < 0) {
3419                 /* error already reported by net_socket_mcast_create() */
3420                 close(fd);
3421                 return NULL;
3422             }
3423             /* clone newfd to fd, close newfd */
3424             dup2(newfd, fd);
3425             close(newfd);
3426         
3427         } else {
3428             fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3429                     fd, strerror(errno));
3430             return NULL;
3431         }
3432     }
3433
3434     s = qemu_mallocz(sizeof(NetSocketState));
3435     if (!s)
3436         return NULL;
3437     s->fd = fd;
3438
3439     s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3440     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3441
3442     /* mcast: save bound address as dst */
3443     if (is_connected) s->dgram_dst=saddr;
3444
3445     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3446             "socket: fd=%d (%s mcast=%s:%d)", 
3447             fd, is_connected? "cloned" : "",
3448             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3449     return s;
3450 }
3451
3452 static void net_socket_connect(void *opaque)
3453 {
3454     NetSocketState *s = opaque;
3455     qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3456 }
3457
3458 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3459                                           int is_connected)
3460 {
3461     NetSocketState *s;
3462     s = qemu_mallocz(sizeof(NetSocketState));
3463     if (!s)
3464         return NULL;
3465     s->fd = fd;
3466     s->vc = qemu_new_vlan_client(vlan, 
3467                                  net_socket_receive, NULL, s);
3468     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3469              "socket: fd=%d", fd);
3470     if (is_connected) {
3471         net_socket_connect(s);
3472     } else {
3473         qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3474     }
3475     return s;
3476 }
3477
3478 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3479                                           int is_connected)
3480 {
3481     int so_type=-1, optlen=sizeof(so_type);
3482
3483     if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3484         fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3485         return NULL;
3486     }
3487     switch(so_type) {
3488     case SOCK_DGRAM:
3489         return net_socket_fd_init_dgram(vlan, fd, is_connected);
3490     case SOCK_STREAM:
3491         return net_socket_fd_init_stream(vlan, fd, is_connected);
3492     default:
3493         /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3494         fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3495         return net_socket_fd_init_stream(vlan, fd, is_connected);
3496     }
3497     return NULL;
3498 }
3499
3500 static void net_socket_accept(void *opaque)
3501 {
3502     NetSocketListenState *s = opaque;    
3503     NetSocketState *s1;
3504     struct sockaddr_in saddr;
3505     socklen_t len;
3506     int fd;
3507
3508     for(;;) {
3509         len = sizeof(saddr);
3510         fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3511         if (fd < 0 && errno != EINTR) {
3512             return;
3513         } else if (fd >= 0) {
3514             break;
3515         }
3516     }
3517     s1 = net_socket_fd_init(s->vlan, fd, 1); 
3518     if (!s1) {
3519         closesocket(fd);
3520     } else {
3521         snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3522                  "socket: connection from %s:%d", 
3523                  inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3524     }
3525 }
3526
3527 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3528 {
3529     NetSocketListenState *s;
3530     int fd, val, ret;
3531     struct sockaddr_in saddr;
3532
3533     if (parse_host_port(&saddr, host_str) < 0)
3534         return -1;
3535     
3536     s = qemu_mallocz(sizeof(NetSocketListenState));
3537     if (!s)
3538         return -1;
3539
3540     fd = socket(PF_INET, SOCK_STREAM, 0);
3541     if (fd < 0) {
3542         perror("socket");
3543         return -1;
3544     }
3545     socket_set_nonblock(fd);
3546
3547     /* allow fast reuse */
3548     val = 1;
3549     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3550     
3551     ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3552     if (ret < 0) {
3553         perror("bind");
3554         return -1;
3555     }
3556     ret = listen(fd, 0);
3557     if (ret < 0) {
3558         perror("listen");
3559         return -1;
3560     }
3561     s->vlan = vlan;
3562     s->fd = fd;
3563     qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3564     return 0;
3565 }
3566
3567 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3568 {
3569     NetSocketState *s;
3570     int fd, connected, ret, err;
3571     struct sockaddr_in saddr;
3572
3573     if (parse_host_port(&saddr, host_str) < 0)
3574         return -1;
3575
3576     fd = socket(PF_INET, SOCK_STREAM, 0);
3577     if (fd < 0) {
3578         perror("socket");
3579         return -1;
3580     }
3581     socket_set_nonblock(fd);
3582
3583     connected = 0;
3584     for(;;) {
3585         ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3586         if (ret < 0) {
3587             err = socket_error();
3588             if (err == EINTR || err == EWOULDBLOCK) {
3589             } else if (err == EINPROGRESS) {
3590                 break;
3591             } else {
3592                 perror("connect");
3593                 closesocket(fd);
3594                 return -1;
3595             }
3596         } else {
3597             connected = 1;
3598             break;
3599         }
3600     }
3601     s = net_socket_fd_init(vlan, fd, connected);
3602     if (!s)
3603         return -1;
3604     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3605              "socket: connect to %s:%d", 
3606              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3607     return 0;
3608 }
3609
3610 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3611 {
3612     NetSocketState *s;
3613     int fd;
3614     struct sockaddr_in saddr;
3615
3616     if (parse_host_port(&saddr, host_str) < 0)
3617         return -1;
3618
3619
3620     fd = net_socket_mcast_create(&saddr);
3621     if (fd < 0)
3622         return -1;
3623
3624     s = net_socket_fd_init(vlan, fd, 0);
3625     if (!s)
3626         return -1;
3627
3628     s->dgram_dst = saddr;
3629     
3630     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3631              "socket: mcast=%s:%d", 
3632              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3633     return 0;
3634
3635 }
3636
3637 static int get_param_value(char *buf, int buf_size,
3638                            const char *tag, const char *str)
3639 {
3640     const char *p;
3641     char *q;
3642     char option[128];
3643
3644     p = str;
3645     for(;;) {
3646         q = option;
3647         while (*p != '\0' && *p != '=') {
3648             if ((q - option) < sizeof(option) - 1)
3649                 *q++ = *p;
3650             p++;
3651         }
3652         *q = '\0';
3653         if (*p != '=')
3654             break;
3655         p++;
3656         if (!strcmp(tag, option)) {
3657             q = buf;
3658             while (*p != '\0' && *p != ',') {
3659                 if ((q - buf) < buf_size - 1)
3660                     *q++ = *p;
3661                 p++;
3662             }
3663             *q = '\0';
3664             return q - buf;
3665         } else {
3666             while (*p != '\0' && *p != ',') {
3667                 p++;
3668             }
3669         }
3670         if (*p != ',')
3671             break;
3672         p++;
3673     }
3674     return 0;
3675 }
3676
3677 int net_client_init(const char *str)
3678 {
3679     const char *p;
3680     char *q;
3681     char device[64];
3682     char buf[1024];
3683     int vlan_id, ret;
3684     VLANState *vlan;
3685
3686     p = str;
3687     q = device;
3688     while (*p != '\0' && *p != ',') {
3689         if ((q - device) < sizeof(device) - 1)
3690             *q++ = *p;
3691         p++;
3692     }
3693     *q = '\0';
3694     if (*p == ',')
3695         p++;
3696     vlan_id = 0;
3697     if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3698         vlan_id = strtol(buf, NULL, 0);
3699     }
3700     vlan = qemu_find_vlan(vlan_id);
3701     if (!vlan) {
3702         fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3703         return -1;
3704     }
3705     if (!strcmp(device, "nic")) {
3706         NICInfo *nd;
3707         uint8_t *macaddr;
3708
3709         if (nb_nics >= MAX_NICS) {
3710             fprintf(stderr, "Too Many NICs\n");
3711             return -1;
3712         }
3713         nd = &nd_table[nb_nics];
3714         macaddr = nd->macaddr;
3715         macaddr[0] = 0x52;
3716         macaddr[1] = 0x54;
3717         macaddr[2] = 0x00;
3718         macaddr[3] = 0x12;
3719         macaddr[4] = 0x34;
3720         macaddr[5] = 0x56 + nb_nics;
3721
3722         if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3723             if (parse_macaddr(macaddr, buf) < 0) {
3724                 fprintf(stderr, "invalid syntax for ethernet address\n");
3725                 return -1;
3726             }
3727         }
3728         if (get_param_value(buf, sizeof(buf), "model", p)) {
3729             nd->model = strdup(buf);
3730         }
3731         nd->vlan = vlan;
3732         nb_nics++;
3733         ret = 0;
3734     } else
3735     if (!strcmp(device, "none")) {
3736         /* does nothing. It is needed to signal that no network cards
3737            are wanted */
3738         ret = 0;
3739     } else
3740 #ifdef CONFIG_SLIRP
3741     if (!strcmp(device, "user")) {
3742         if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3743             pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3744         }
3745         ret = net_slirp_init(vlan);
3746     } else
3747 #endif
3748 #ifdef _WIN32
3749     if (!strcmp(device, "tap")) {
3750         char ifname[64];
3751         if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3752             fprintf(stderr, "tap: no interface name\n");
3753             return -1;
3754         }
3755         ret = tap_win32_init(vlan, ifname);
3756     } else
3757 #else
3758     if (!strcmp(device, "tap")) {
3759         char ifname[64];
3760         char setup_script[1024];
3761         int fd;
3762         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3763             fd = strtol(buf, NULL, 0);
3764             ret = -1;
3765             if (net_tap_fd_init(vlan, fd))
3766                 ret = 0;
3767         } else {
3768             get_param_value(ifname, sizeof(ifname), "ifname", p);
3769             if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3770                 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3771             }
3772             ret = net_tap_init(vlan, ifname, setup_script);
3773         }
3774     } else
3775 #endif
3776     if (!strcmp(device, "socket")) {
3777         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3778             int fd;
3779             fd = strtol(buf, NULL, 0);
3780             ret = -1;
3781             if (net_socket_fd_init(vlan, fd, 1))
3782                 ret = 0;
3783         } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3784             ret = net_socket_listen_init(vlan, buf);
3785         } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3786             ret = net_socket_connect_init(vlan, buf);
3787         } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3788             ret = net_socket_mcast_init(vlan, buf);
3789         } else {
3790             fprintf(stderr, "Unknown socket options: %s\n", p);
3791             return -1;
3792         }
3793     } else
3794     {
3795         fprintf(stderr, "Unknown network device: %s\n", device);
3796         return -1;
3797     }
3798     if (ret < 0) {
3799         fprintf(stderr, "Could not initialize device '%s'\n", device);
3800     }
3801     
3802     return ret;
3803 }
3804
3805 void do_info_network(void)
3806 {
3807     VLANState *vlan;
3808     VLANClientState *vc;
3809
3810     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3811         term_printf("VLAN %d devices:\n", vlan->id);
3812         for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3813             term_printf("  %s\n", vc->info_str);
3814     }
3815 }
3816  
3817 /***********************************************************/
3818 /* USB devices */
3819
3820 static USBPort *used_usb_ports;
3821 static USBPort *free_usb_ports;
3822
3823 /* ??? Maybe change this to register a hub to keep track of the topology.  */
3824 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3825                             usb_attachfn attach)
3826 {
3827     port->opaque = opaque;
3828     port->index = index;
3829     port->attach = attach;
3830     port->next = free_usb_ports;
3831     free_usb_ports = port;
3832 }
3833
3834 static int usb_device_add(const char *devname)
3835 {
3836     const char *p;
3837     USBDevice *dev;
3838     USBPort *port;
3839
3840     if (!free_usb_ports)
3841         return -1;
3842
3843     if (strstart(devname, "host:", &p)) {
3844         dev = usb_host_device_open(p);
3845     } else if (!strcmp(devname, "mouse")) {
3846         dev = usb_mouse_init();
3847     } else if (!strcmp(devname, "tablet")) {
3848         dev = usb_tablet_init();
3849     } else if (strstart(devname, "disk:", &p)) {
3850         dev = usb_msd_init(p);
3851     } else {
3852         return -1;
3853     }
3854     if (!dev)
3855         return -1;
3856
3857     /* Find a USB port to add the device to.  */
3858     port = free_usb_ports;
3859     if (!port->next) {
3860         USBDevice *hub;
3861
3862         /* Create a new hub and chain it on.  */
3863         free_usb_ports = NULL;
3864         port->next = used_usb_ports;
3865         used_usb_ports = port;
3866
3867         hub = usb_hub_init(VM_USB_HUB_SIZE);
3868         usb_attach(port, hub);
3869         port = free_usb_ports;
3870     }
3871
3872     free_usb_ports = port->next;
3873     port->next = used_usb_ports;
3874     used_usb_ports = port;
3875     usb_attach(port, dev);
3876     return 0;
3877 }
3878
3879 static int usb_device_del(const char *devname)
3880 {
3881     USBPort *port;
3882     USBPort **lastp;
3883     USBDevice *dev;
3884     int bus_num, addr;
3885     const char *p;
3886
3887     if (!used_usb_ports)
3888         return -1;
3889
3890     p = strchr(devname, '.');
3891     if (!p) 
3892         return -1;
3893     bus_num = strtoul(devname, NULL, 0);
3894     addr = strtoul(p + 1, NULL, 0);
3895     if (bus_num != 0)
3896         return -1;
3897
3898     lastp = &used_usb_ports;
3899     port = used_usb_ports;
3900     while (port && port->dev->addr != addr) {
3901         lastp = &port->next;
3902         port = port->next;
3903     }
3904
3905     if (!port)
3906         return -1;
3907
3908     dev = port->dev;
3909     *lastp = port->next;
3910     usb_attach(port, NULL);
3911     dev->handle_destroy(dev);
3912     port->next = free_usb_ports;
3913     free_usb_ports = port;
3914     return 0;
3915 }
3916
3917 void do_usb_add(const char *devname)
3918 {
3919     int ret;
3920     ret = usb_device_add(devname);
3921     if (ret < 0) 
3922         term_printf("Could not add USB device '%s'\n", devname);
3923 }
3924
3925 void do_usb_del(const char *devname)
3926 {
3927     int ret;
3928     ret = usb_device_del(devname);
3929     if (ret < 0) 
3930         term_printf("Could not remove USB device '%s'\n", devname);
3931 }
3932
3933 void usb_info(void)
3934 {
3935     USBDevice *dev;
3936     USBPort *port;
3937     const char *speed_str;
3938
3939     if (!usb_enabled) {
3940         term_printf("USB support not enabled\n");
3941         return;
3942     }
3943
3944     for (port = used_usb_ports; port; port = port->next) {
3945         dev = port->dev;
3946         if (!dev)
3947             continue;
3948         switch(dev->speed) {
3949         case USB_SPEED_LOW: 
3950             speed_str = "1.5"; 
3951             break;
3952         case USB_SPEED_FULL: 
3953             speed_str = "12"; 
3954             break;
3955         case USB_SPEED_HIGH: 
3956             speed_str = "480"; 
3957             break;
3958         default:
3959             speed_str = "?"; 
3960             break;
3961         }
3962         term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
3963                     0, dev->addr, speed_str, dev->devname);
3964     }
3965 }
3966
3967 /***********************************************************/
3968 /* pid file */
3969
3970 static char *pid_filename;
3971
3972 /* Remove PID file. Called on normal exit */
3973
3974 static void remove_pidfile(void) 
3975 {
3976     unlink (pid_filename);
3977 }
3978
3979 static void create_pidfile(const char *filename)
3980 {
3981     struct stat pidstat;
3982     FILE *f;
3983
3984     /* Try to write our PID to the named file */
3985     if (stat(filename, &pidstat) < 0) {
3986         if (errno == ENOENT) {
3987             if ((f = fopen (filename, "w")) == NULL) {
3988                 perror("Opening pidfile");
3989                 exit(1);
3990             }
3991             fprintf(f, "%d\n", getpid());
3992             fclose(f);
3993             pid_filename = qemu_strdup(filename);
3994             if (!pid_filename) {
3995                 fprintf(stderr, "Could not save PID filename");
3996                 exit(1);
3997             }
3998             atexit(remove_pidfile);
3999         }
4000     } else {
4001         fprintf(stderr, "%s already exists. Remove it and try again.\n", 
4002                 filename);
4003         exit(1);
4004     }
4005 }
4006
4007 /***********************************************************/
4008 /* dumb display */
4009
4010 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4011 {
4012 }
4013
4014 static void dumb_resize(DisplayState *ds, int w, int h)
4015 {
4016 }
4017
4018 static void dumb_refresh(DisplayState *ds)
4019 {
4020     vga_hw_update();
4021 }
4022
4023 void dumb_display_init(DisplayState *ds)
4024 {
4025     ds->data = NULL;
4026     ds->linesize = 0;
4027     ds->depth = 0;
4028     ds->dpy_update = dumb_update;
4029     ds->dpy_resize = dumb_resize;
4030     ds->dpy_refresh = dumb_refresh;
4031 }
4032
4033 /***********************************************************/
4034 /* I/O handling */
4035
4036 #define MAX_IO_HANDLERS 64
4037
4038 typedef struct IOHandlerRecord {
4039     int fd;
4040     IOCanRWHandler *fd_read_poll;
4041     IOHandler *fd_read;
4042     IOHandler *fd_write;
4043     void *opaque;
4044     /* temporary data */
4045     struct pollfd *ufd;
4046     struct IOHandlerRecord *next;
4047 } IOHandlerRecord;
4048
4049 static IOHandlerRecord *first_io_handler;
4050
4051 /* XXX: fd_read_poll should be suppressed, but an API change is
4052    necessary in the character devices to suppress fd_can_read(). */
4053 int qemu_set_fd_handler2(int fd, 
4054                          IOCanRWHandler *fd_read_poll, 
4055                          IOHandler *fd_read, 
4056                          IOHandler *fd_write, 
4057                          void *opaque)
4058 {
4059     IOHandlerRecord **pioh, *ioh;
4060
4061     if (!fd_read && !fd_write) {
4062         pioh = &first_io_handler;
4063         for(;;) {
4064             ioh = *pioh;
4065             if (ioh == NULL)
4066                 break;
4067             if (ioh->fd == fd) {
4068                 *pioh = ioh->next;
4069                 qemu_free(ioh);
4070                 break;
4071             }
4072             pioh = &ioh->next;
4073         }
4074     } else {
4075         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4076             if (ioh->fd == fd)
4077                 goto found;
4078         }
4079         ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4080         if (!ioh)
4081             return -1;
4082         ioh->next = first_io_handler;
4083         first_io_handler = ioh;
4084     found:
4085         ioh->fd = fd;
4086         ioh->fd_read_poll = fd_read_poll;
4087         ioh->fd_read = fd_read;
4088         ioh->fd_write = fd_write;
4089         ioh->opaque = opaque;
4090     }
4091     return 0;
4092 }
4093
4094 int qemu_set_fd_handler(int fd, 
4095                         IOHandler *fd_read, 
4096                         IOHandler *fd_write, 
4097                         void *opaque)
4098 {
4099     return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4100 }
4101
4102 /***********************************************************/
4103 /* Polling handling */
4104
4105 typedef struct PollingEntry {
4106     PollingFunc *func;
4107     void *opaque;
4108     struct PollingEntry *next;
4109 } PollingEntry;
4110
4111 static PollingEntry *first_polling_entry;
4112
4113 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4114 {
4115     PollingEntry **ppe, *pe;
4116     pe = qemu_mallocz(sizeof(PollingEntry));
4117     if (!pe)
4118         return -1;
4119     pe->func = func;
4120     pe->opaque = opaque;
4121     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4122     *ppe = pe;
4123     return 0;
4124 }
4125
4126 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4127 {
4128     PollingEntry **ppe, *pe;
4129     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4130         pe = *ppe;
4131         if (pe->func == func && pe->opaque == opaque) {
4132             *ppe = pe->next;
4133             qemu_free(pe);
4134             break;
4135         }
4136     }
4137 }
4138
4139 #ifdef _WIN32
4140 /***********************************************************/
4141 /* Wait objects support */
4142 typedef struct WaitObjects {
4143     int num;
4144     HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4145     WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4146     void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4147 } WaitObjects;
4148
4149 static WaitObjects wait_objects = {0};
4150     
4151 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4152 {
4153     WaitObjects *w = &wait_objects;
4154
4155     if (w->num >= MAXIMUM_WAIT_OBJECTS)
4156         return -1;
4157     w->events[w->num] = handle;
4158     w->func[w->num] = func;
4159     w->opaque[w->num] = opaque;
4160     w->num++;
4161     return 0;
4162 }
4163
4164 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4165 {
4166     int i, found;
4167     WaitObjects *w = &wait_objects;
4168
4169     found = 0;
4170     for (i = 0; i < w->num; i++) {
4171         if (w->events[i] == handle)
4172             found = 1;
4173         if (found) {
4174             w->events[i] = w->events[i + 1];
4175             w->func[i] = w->func[i + 1];
4176             w->opaque[i] = w->opaque[i + 1];
4177         }            
4178     }
4179     if (found)
4180         w->num--;
4181 }
4182 #endif
4183
4184 /***********************************************************/
4185 /* savevm/loadvm support */
4186
4187 #define IO_BUF_SIZE 32768
4188
4189 struct QEMUFile {
4190     FILE *outfile;
4191     BlockDriverState *bs;
4192     int is_file;
4193     int is_writable;
4194     int64_t base_offset;
4195     int64_t buf_offset; /* start of buffer when writing, end of buffer
4196                            when reading */
4197     int buf_index;
4198     int buf_size; /* 0 when writing */
4199     uint8_t buf[IO_BUF_SIZE];
4200 };
4201
4202 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4203 {
4204     QEMUFile *f;
4205
4206     f = qemu_mallocz(sizeof(QEMUFile));
4207     if (!f)
4208         return NULL;
4209     if (!strcmp(mode, "wb")) {
4210         f->is_writable = 1;
4211     } else if (!strcmp(mode, "rb")) {
4212         f->is_writable = 0;
4213     } else {
4214         goto fail;
4215     }
4216     f->outfile = fopen(filename, mode);
4217     if (!f->outfile)
4218         goto fail;
4219     f->is_file = 1;
4220     return f;
4221  fail:
4222     if (f->outfile)
4223         fclose(f->outfile);
4224     qemu_free(f);
4225     return NULL;
4226 }
4227
4228 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4229 {
4230     QEMUFile *f;
4231
4232     f = qemu_mallocz(sizeof(QEMUFile));
4233     if (!f)
4234         return NULL;
4235     f->is_file = 0;
4236     f->bs = bs;
4237     f->is_writable = is_writable;
4238     f->base_offset = offset;
4239     return f;
4240 }
4241
4242 void qemu_fflush(QEMUFile *f)
4243 {
4244     if (!f->is_writable)
4245         return;
4246     if (f->buf_index > 0) {
4247         if (f->is_file) {
4248             fseek(f->outfile, f->buf_offset, SEEK_SET);
4249             fwrite(f->buf, 1, f->buf_index, f->outfile);
4250         } else {
4251             bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4252                         f->buf, f->buf_index);
4253         }
4254         f->buf_offset += f->buf_index;
4255         f->buf_index = 0;
4256     }
4257 }
4258
4259 static void qemu_fill_buffer(QEMUFile *f)
4260 {
4261     int len;
4262
4263     if (f->is_writable)
4264         return;
4265     if (f->is_file) {
4266         fseek(f->outfile, f->buf_offset, SEEK_SET);
4267         len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4268         if (len < 0)
4269             len = 0;
4270     } else {
4271         len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4272                          f->buf, IO_BUF_SIZE);
4273         if (len < 0)
4274             len = 0;
4275     }
4276     f->buf_index = 0;
4277     f->buf_size = len;
4278     f->buf_offset += len;
4279 }
4280
4281 void qemu_fclose(QEMUFile *f)
4282 {
4283     if (f->is_writable)
4284         qemu_fflush(f);
4285     if (f->is_file) {
4286         fclose(f->outfile);
4287     }
4288     qemu_free(f);
4289 }
4290
4291 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4292 {
4293     int l;
4294     while (size > 0) {
4295         l = IO_BUF_SIZE - f->buf_index;
4296         if (l > size)
4297             l = size;
4298         memcpy(f->buf + f->buf_index, buf, l);
4299         f->buf_index += l;
4300         buf += l;
4301         size -= l;
4302         if (f->buf_index >= IO_BUF_SIZE)
4303             qemu_fflush(f);
4304     }
4305 }
4306
4307 void qemu_put_byte(QEMUFile *f, int v)
4308 {
4309     f->buf[f->buf_index++] = v;
4310     if (f->buf_index >= IO_BUF_SIZE)
4311         qemu_fflush(f);
4312 }
4313
4314 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4315 {
4316     int size, l;
4317
4318     size = size1;
4319     while (size > 0) {
4320         l = f->buf_size - f->buf_index;
4321         if (l == 0) {
4322             qemu_fill_buffer(f);
4323             l = f->buf_size - f->buf_index;
4324             if (l == 0)
4325                 break;
4326         }
4327         if (l > size)
4328             l = size;
4329         memcpy(buf, f->buf + f->buf_index, l);
4330         f->buf_index += l;
4331         buf += l;
4332         size -= l;
4333     }
4334     return size1 - size;
4335 }
4336
4337 int qemu_get_byte(QEMUFile *f)
4338 {
4339     if (f->buf_index >= f->buf_size) {
4340         qemu_fill_buffer(f);
4341         if (f->buf_index >= f->buf_size)
4342             return 0;
4343     }
4344     return f->buf[f->buf_index++];
4345 }
4346
4347 int64_t qemu_ftell(QEMUFile *f)
4348 {
4349     return f->buf_offset - f->buf_size + f->buf_index;
4350 }
4351
4352 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4353 {
4354     if (whence == SEEK_SET) {
4355         /* nothing to do */
4356     } else if (whence == SEEK_CUR) {
4357         pos += qemu_ftell(f);
4358     } else {
4359         /* SEEK_END not supported */
4360         return -1;
4361     }
4362     if (f->is_writable) {
4363         qemu_fflush(f);
4364         f->buf_offset = pos;
4365     } else {
4366         f->buf_offset = pos;
4367         f->buf_index = 0;
4368         f->buf_size = 0;
4369     }
4370     return pos;
4371 }
4372
4373 void qemu_put_be16(QEMUFile *f, unsigned int v)
4374 {
4375     qemu_put_byte(f, v >> 8);
4376     qemu_put_byte(f, v);
4377 }
4378
4379 void qemu_put_be32(QEMUFile *f, unsigned int v)
4380 {
4381     qemu_put_byte(f, v >> 24);
4382     qemu_put_byte(f, v >> 16);
4383     qemu_put_byte(f, v >> 8);
4384     qemu_put_byte(f, v);
4385 }
4386
4387 void qemu_put_be64(QEMUFile *f, uint64_t v)
4388 {
4389     qemu_put_be32(f, v >> 32);
4390     qemu_put_be32(f, v);
4391 }
4392
4393 unsigned int qemu_get_be16(QEMUFile *f)
4394 {
4395     unsigned int v;
4396     v = qemu_get_byte(f) << 8;
4397     v |= qemu_get_byte(f);
4398     return v;
4399 }
4400
4401 unsigned int qemu_get_be32(QEMUFile *f)
4402 {
4403     unsigned int v;
4404     v = qemu_get_byte(f) << 24;
4405     v |= qemu_get_byte(f) << 16;
4406     v |= qemu_get_byte(f) << 8;
4407     v |= qemu_get_byte(f);
4408     return v;
4409 }
4410
4411 uint64_t qemu_get_be64(QEMUFile *f)
4412 {
4413     uint64_t v;
4414     v = (uint64_t)qemu_get_be32(f) << 32;
4415     v |= qemu_get_be32(f);
4416     return v;
4417 }
4418
4419 typedef struct SaveStateEntry {
4420     char idstr[256];
4421     int instance_id;
4422     int version_id;
4423     SaveStateHandler *save_state;
4424     LoadStateHandler *load_state;
4425     void *opaque;
4426     struct SaveStateEntry *next;
4427 } SaveStateEntry;
4428
4429 static SaveStateEntry *first_se;
4430
4431 int register_savevm(const char *idstr, 
4432                     int instance_id, 
4433                     int version_id,
4434                     SaveStateHandler *save_state,
4435                     LoadStateHandler *load_state,
4436                     void *opaque)
4437 {
4438     SaveStateEntry *se, **pse;
4439
4440     se = qemu_malloc(sizeof(SaveStateEntry));
4441     if (!se)
4442         return -1;
4443     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4444     se->instance_id = instance_id;
4445     se->version_id = version_id;
4446     se->save_state = save_state;
4447     se->load_state = load_state;
4448     se->opaque = opaque;
4449     se->next = NULL;
4450
4451     /* add at the end of list */
4452     pse = &first_se;
4453     while (*pse != NULL)
4454         pse = &(*pse)->next;
4455     *pse = se;
4456     return 0;
4457 }
4458
4459 #define QEMU_VM_FILE_MAGIC   0x5145564d
4460 #define QEMU_VM_FILE_VERSION 0x00000002
4461
4462 int qemu_savevm_state(QEMUFile *f)
4463 {
4464     SaveStateEntry *se;
4465     int len, ret;
4466     int64_t cur_pos, len_pos, total_len_pos;
4467
4468     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4469     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4470     total_len_pos = qemu_ftell(f);
4471     qemu_put_be64(f, 0); /* total size */
4472
4473     for(se = first_se; se != NULL; se = se->next) {
4474         /* ID string */
4475         len = strlen(se->idstr);
4476         qemu_put_byte(f, len);
4477         qemu_put_buffer(f, se->idstr, len);
4478
4479         qemu_put_be32(f, se->instance_id);
4480         qemu_put_be32(f, se->version_id);
4481
4482         /* record size: filled later */
4483         len_pos = qemu_ftell(f);
4484         qemu_put_be32(f, 0);
4485         
4486         se->save_state(f, se->opaque);
4487
4488         /* fill record size */
4489         cur_pos = qemu_ftell(f);
4490         len = cur_pos - len_pos - 4;
4491         qemu_fseek(f, len_pos, SEEK_SET);
4492         qemu_put_be32(f, len);
4493         qemu_fseek(f, cur_pos, SEEK_SET);
4494     }
4495     cur_pos = qemu_ftell(f);
4496     qemu_fseek(f, total_len_pos, SEEK_SET);
4497     qemu_put_be64(f, cur_pos - total_len_pos - 8);
4498     qemu_fseek(f, cur_pos, SEEK_SET);
4499
4500     ret = 0;
4501     return ret;
4502 }
4503
4504 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4505 {
4506     SaveStateEntry *se;
4507
4508     for(se = first_se; se != NULL; se = se->next) {
4509         if (!strcmp(se->idstr, idstr) && 
4510             instance_id == se->instance_id)
4511             return se;
4512     }
4513     return NULL;
4514 }
4515
4516 int qemu_loadvm_state(QEMUFile *f)
4517 {
4518     SaveStateEntry *se;
4519     int len, ret, instance_id, record_len, version_id;
4520     int64_t total_len, end_pos, cur_pos;
4521     unsigned int v;
4522     char idstr[256];
4523     
4524     v = qemu_get_be32(f);
4525     if (v != QEMU_VM_FILE_MAGIC)
4526         goto fail;
4527     v = qemu_get_be32(f);
4528     if (v != QEMU_VM_FILE_VERSION) {
4529     fail:
4530         ret = -1;
4531         goto the_end;
4532     }
4533     total_len = qemu_get_be64(f);
4534     end_pos = total_len + qemu_ftell(f);
4535     for(;;) {
4536         if (qemu_ftell(f) >= end_pos)
4537             break;
4538         len = qemu_get_byte(f);
4539         qemu_get_buffer(f, idstr, len);
4540         idstr[len] = '\0';
4541         instance_id = qemu_get_be32(f);
4542         version_id = qemu_get_be32(f);
4543         record_len = qemu_get_be32(f);
4544 #if 0
4545         printf("idstr=%s instance=0x%x version=%d len=%d\n", 
4546                idstr, instance_id, version_id, record_len);
4547 #endif
4548         cur_pos = qemu_ftell(f);
4549         se = find_se(idstr, instance_id);
4550         if (!se) {
4551             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
4552                     instance_id, idstr);
4553         } else {
4554             ret = se->load_state(f, se->opaque, version_id);
4555             if (ret < 0) {
4556                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
4557                         instance_id, idstr);
4558             }
4559         }
4560         /* always seek to exact end of record */
4561         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4562     }
4563     ret = 0;
4564  the_end:
4565     return ret;
4566 }
4567
4568 /* device can contain snapshots */
4569 static int bdrv_can_snapshot(BlockDriverState *bs)
4570 {
4571     return (bs &&
4572             !bdrv_is_removable(bs) &&
4573             !bdrv_is_read_only(bs));
4574 }
4575
4576 /* device must be snapshots in order to have a reliable snapshot */
4577 static int bdrv_has_snapshot(BlockDriverState *bs)
4578 {
4579     return (bs &&
4580             !bdrv_is_removable(bs) &&
4581             !bdrv_is_read_only(bs));
4582 }
4583
4584 static BlockDriverState *get_bs_snapshots(void)
4585 {
4586     BlockDriverState *bs;
4587     int i;
4588
4589     if (bs_snapshots)
4590         return bs_snapshots;
4591     for(i = 0; i <= MAX_DISKS; i++) {
4592         bs = bs_table[i];
4593         if (bdrv_can_snapshot(bs))
4594             goto ok;
4595     }
4596     return NULL;
4597  ok:
4598     bs_snapshots = bs;
4599     return bs;
4600 }
4601
4602 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4603                               const char *name)
4604 {
4605     QEMUSnapshotInfo *sn_tab, *sn;
4606     int nb_sns, i, ret;
4607     
4608     ret = -ENOENT;
4609     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4610     if (nb_sns < 0)
4611         return ret;
4612     for(i = 0; i < nb_sns; i++) {
4613         sn = &sn_tab[i];
4614         if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4615             *sn_info = *sn;
4616             ret = 0;
4617             break;
4618         }
4619     }
4620     qemu_free(sn_tab);
4621     return ret;
4622 }
4623
4624 void do_savevm(const char *name)
4625 {
4626     BlockDriverState *bs, *bs1;
4627     QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4628     int must_delete, ret, i;
4629     BlockDriverInfo bdi1, *bdi = &bdi1;
4630     QEMUFile *f;
4631     int saved_vm_running;
4632 #ifdef _WIN32
4633     struct _timeb tb;
4634 #else
4635     struct timeval tv;
4636 #endif
4637
4638     bs = get_bs_snapshots();
4639     if (!bs) {
4640         term_printf("No block device can accept snapshots\n");
4641         return;
4642     }
4643
4644     /* ??? Should this occur after vm_stop?  */
4645     qemu_aio_flush();
4646
4647     saved_vm_running = vm_running;
4648     vm_stop(0);
4649     
4650     must_delete = 0;
4651     if (name) {
4652         ret = bdrv_snapshot_find(bs, old_sn, name);
4653         if (ret >= 0) {
4654             must_delete = 1;
4655         }
4656     }
4657     memset(sn, 0, sizeof(*sn));
4658     if (must_delete) {
4659         pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4660         pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4661     } else {
4662         if (name)
4663             pstrcpy(sn->name, sizeof(sn->name), name);
4664     }
4665
4666     /* fill auxiliary fields */
4667 #ifdef _WIN32
4668     _ftime(&tb);
4669     sn->date_sec = tb.time;
4670     sn->date_nsec = tb.millitm * 1000000;
4671 #else
4672     gettimeofday(&tv, NULL);
4673     sn->date_sec = tv.tv_sec;
4674     sn->date_nsec = tv.tv_usec * 1000;
4675 #endif
4676     sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4677     
4678     if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4679         term_printf("Device %s does not support VM state snapshots\n",
4680                     bdrv_get_device_name(bs));
4681         goto the_end;
4682     }
4683     
4684     /* save the VM state */
4685     f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4686     if (!f) {
4687         term_printf("Could not open VM state file\n");
4688         goto the_end;
4689     }
4690     ret = qemu_savevm_state(f);
4691     sn->vm_state_size = qemu_ftell(f);
4692     qemu_fclose(f);
4693     if (ret < 0) {
4694         term_printf("Error %d while writing VM\n", ret);
4695         goto the_end;
4696     }
4697     
4698     /* create the snapshots */
4699
4700     for(i = 0; i < MAX_DISKS; i++) {
4701         bs1 = bs_table[i];
4702         if (bdrv_has_snapshot(bs1)) {
4703             if (must_delete) {
4704                 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4705                 if (ret < 0) {
4706                     term_printf("Error while deleting snapshot on '%s'\n",
4707                                 bdrv_get_device_name(bs1));
4708                 }
4709             }
4710             ret = bdrv_snapshot_create(bs1, sn);
4711             if (ret < 0) {
4712                 term_printf("Error while creating snapshot on '%s'\n",
4713                             bdrv_get_device_name(bs1));
4714             }
4715         }
4716     }
4717
4718  the_end:
4719     if (saved_vm_running)
4720         vm_start();
4721 }
4722
4723 void do_loadvm(const char *name)
4724 {
4725     BlockDriverState *bs, *bs1;
4726     BlockDriverInfo bdi1, *bdi = &bdi1;
4727     QEMUFile *f;
4728     int i, ret;
4729     int saved_vm_running;
4730
4731     bs = get_bs_snapshots();
4732     if (!bs) {
4733         term_printf("No block device supports snapshots\n");
4734         return;
4735     }
4736     
4737     /* Flush all IO requests so they don't interfere with the new state.  */
4738     qemu_aio_flush();
4739
4740     saved_vm_running = vm_running;
4741     vm_stop(0);
4742
4743     for(i = 0; i <= MAX_DISKS; i++) {
4744         bs1 = bs_table[i];
4745         if (bdrv_has_snapshot(bs1)) {
4746             ret = bdrv_snapshot_goto(bs1, name);
4747             if (ret < 0) {
4748                 if (bs != bs1)
4749                     term_printf("Warning: ");
4750                 switch(ret) {
4751                 case -ENOTSUP:
4752                     term_printf("Snapshots not supported on device '%s'\n",
4753                                 bdrv_get_device_name(bs1));
4754                     break;
4755                 case -ENOENT:
4756                     term_printf("Could not find snapshot '%s' on device '%s'\n",
4757                                 name, bdrv_get_device_name(bs1));
4758                     break;
4759                 default:
4760                     term_printf("Error %d while activating snapshot on '%s'\n",
4761                                 ret, bdrv_get_device_name(bs1));
4762                     break;
4763                 }
4764                 /* fatal on snapshot block device */
4765                 if (bs == bs1)
4766                     goto the_end;
4767             }
4768         }
4769     }
4770
4771     if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4772         term_printf("Device %s does not support VM state snapshots\n",
4773                     bdrv_get_device_name(bs));
4774         return;
4775     }
4776     
4777     /* restore the VM state */
4778     f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4779     if (!f) {
4780         term_printf("Could not open VM state file\n");
4781         goto the_end;
4782     }
4783     ret = qemu_loadvm_state(f);
4784     qemu_fclose(f);
4785     if (ret < 0) {
4786         term_printf("Error %d while loading VM state\n", ret);
4787     }
4788  the_end:
4789     if (saved_vm_running)
4790         vm_start();
4791 }
4792
4793 void do_delvm(const char *name)
4794 {
4795     BlockDriverState *bs, *bs1;
4796     int i, ret;
4797
4798     bs = get_bs_snapshots();
4799     if (!bs) {
4800         term_printf("No block device supports snapshots\n");
4801         return;
4802     }
4803     
4804     for(i = 0; i <= MAX_DISKS; i++) {
4805         bs1 = bs_table[i];
4806         if (bdrv_has_snapshot(bs1)) {
4807             ret = bdrv_snapshot_delete(bs1, name);
4808             if (ret < 0) {
4809                 if (ret == -ENOTSUP)
4810                     term_printf("Snapshots not supported on device '%s'\n",
4811                                 bdrv_get_device_name(bs1));
4812                 else
4813                     term_printf("Error %d while deleting snapshot on '%s'\n",
4814                                 ret, bdrv_get_device_name(bs1));
4815             }
4816         }
4817     }
4818 }
4819
4820 void do_info_snapshots(void)
4821 {
4822     BlockDriverState *bs, *bs1;
4823     QEMUSnapshotInfo *sn_tab, *sn;
4824     int nb_sns, i;
4825     char buf[256];
4826
4827     bs = get_bs_snapshots();
4828     if (!bs) {
4829         term_printf("No available block device supports snapshots\n");
4830         return;
4831     }
4832     term_printf("Snapshot devices:");
4833     for(i = 0; i <= MAX_DISKS; i++) {
4834         bs1 = bs_table[i];
4835         if (bdrv_has_snapshot(bs1)) {
4836             if (bs == bs1)
4837                 term_printf(" %s", bdrv_get_device_name(bs1));
4838         }
4839     }
4840     term_printf("\n");
4841
4842     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4843     if (nb_sns < 0) {
4844         term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
4845         return;
4846     }
4847     term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
4848     term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
4849     for(i = 0; i < nb_sns; i++) {
4850         sn = &sn_tab[i];
4851         term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
4852     }
4853     qemu_free(sn_tab);
4854 }
4855
4856 /***********************************************************/
4857 /* cpu save/restore */
4858
4859 #if defined(TARGET_I386)
4860
4861 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4862 {
4863     qemu_put_be32(f, dt->selector);
4864     qemu_put_betl(f, dt->base);
4865     qemu_put_be32(f, dt->limit);
4866     qemu_put_be32(f, dt->flags);
4867 }
4868
4869 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4870 {
4871     dt->selector = qemu_get_be32(f);
4872     dt->base = qemu_get_betl(f);
4873     dt->limit = qemu_get_be32(f);
4874     dt->flags = qemu_get_be32(f);
4875 }
4876
4877 void cpu_save(QEMUFile *f, void *opaque)
4878 {
4879     CPUState *env = opaque;
4880     uint16_t fptag, fpus, fpuc, fpregs_format;
4881     uint32_t hflags;
4882     int i;
4883     
4884     for(i = 0; i < CPU_NB_REGS; i++)
4885         qemu_put_betls(f, &env->regs[i]);
4886     qemu_put_betls(f, &env->eip);
4887     qemu_put_betls(f, &env->eflags);
4888     hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4889     qemu_put_be32s(f, &hflags);
4890     
4891     /* FPU */
4892     fpuc = env->fpuc;
4893     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4894     fptag = 0;
4895     for(i = 0; i < 8; i++) {
4896         fptag |= ((!env->fptags[i]) << i);
4897     }
4898     
4899     qemu_put_be16s(f, &fpuc);
4900     qemu_put_be16s(f, &fpus);
4901     qemu_put_be16s(f, &fptag);
4902
4903 #ifdef USE_X86LDOUBLE
4904     fpregs_format = 0;
4905 #else
4906     fpregs_format = 1;
4907 #endif
4908     qemu_put_be16s(f, &fpregs_format);
4909     
4910     for(i = 0; i < 8; i++) {
4911 #ifdef USE_X86LDOUBLE
4912         {
4913             uint64_t mant;
4914             uint16_t exp;
4915             /* we save the real CPU data (in case of MMX usage only 'mant'
4916                contains the MMX register */
4917             cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4918             qemu_put_be64(f, mant);
4919             qemu_put_be16(f, exp);
4920         }
4921 #else
4922         /* if we use doubles for float emulation, we save the doubles to
4923            avoid losing information in case of MMX usage. It can give
4924            problems if the image is restored on a CPU where long
4925            doubles are used instead. */
4926         qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4927 #endif
4928     }
4929
4930     for(i = 0; i < 6; i++)
4931         cpu_put_seg(f, &env->segs[i]);
4932     cpu_put_seg(f, &env->ldt);
4933     cpu_put_seg(f, &env->tr);
4934     cpu_put_seg(f, &env->gdt);
4935     cpu_put_seg(f, &env->idt);
4936     
4937     qemu_put_be32s(f, &env->sysenter_cs);
4938     qemu_put_be32s(f, &env->sysenter_esp);
4939     qemu_put_be32s(f, &env->sysenter_eip);
4940     
4941     qemu_put_betls(f, &env->cr[0]);
4942     qemu_put_betls(f, &env->cr[2]);
4943     qemu_put_betls(f, &env->cr[3]);
4944     qemu_put_betls(f, &env->cr[4]);
4945     
4946     for(i = 0; i < 8; i++)
4947         qemu_put_betls(f, &env->dr[i]);
4948
4949     /* MMU */
4950     qemu_put_be32s(f, &env->a20_mask);
4951
4952     /* XMM */
4953     qemu_put_be32s(f, &env->mxcsr);
4954     for(i = 0; i < CPU_NB_REGS; i++) {
4955         qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4956         qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4957     }
4958
4959 #ifdef TARGET_X86_64
4960     qemu_put_be64s(f, &env->efer);
4961     qemu_put_be64s(f, &env->star);
4962     qemu_put_be64s(f, &env->lstar);
4963     qemu_put_be64s(f, &env->cstar);
4964     qemu_put_be64s(f, &env->fmask);
4965     qemu_put_be64s(f, &env->kernelgsbase);
4966 #endif
4967     qemu_put_be32s(f, &env->smbase);
4968 }
4969
4970 #ifdef USE_X86LDOUBLE
4971 /* XXX: add that in a FPU generic layer */
4972 union x86_longdouble {
4973     uint64_t mant;
4974     uint16_t exp;
4975 };
4976
4977 #define MANTD1(fp)      (fp & ((1LL << 52) - 1))
4978 #define EXPBIAS1 1023
4979 #define EXPD1(fp)       ((fp >> 52) & 0x7FF)
4980 #define SIGND1(fp)      ((fp >> 32) & 0x80000000)
4981
4982 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4983 {
4984     int e;
4985     /* mantissa */
4986     p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4987     /* exponent + sign */
4988     e = EXPD1(temp) - EXPBIAS1 + 16383;
4989     e |= SIGND1(temp) >> 16;
4990     p->exp = e;
4991 }
4992 #endif
4993
4994 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4995 {
4996     CPUState *env = opaque;
4997     int i, guess_mmx;
4998     uint32_t hflags;
4999     uint16_t fpus, fpuc, fptag, fpregs_format;
5000
5001     if (version_id != 3 && version_id != 4)
5002         return -EINVAL;
5003     for(i = 0; i < CPU_NB_REGS; i++)
5004         qemu_get_betls(f, &env->regs[i]);
5005     qemu_get_betls(f, &env->eip);
5006     qemu_get_betls(f, &env->eflags);
5007     qemu_get_be32s(f, &hflags);
5008
5009     qemu_get_be16s(f, &fpuc);
5010     qemu_get_be16s(f, &fpus);
5011     qemu_get_be16s(f, &fptag);
5012     qemu_get_be16s(f, &fpregs_format);
5013     
5014     /* NOTE: we cannot always restore the FPU state if the image come
5015        from a host with a different 'USE_X86LDOUBLE' define. We guess
5016        if we are in an MMX state to restore correctly in that case. */
5017     guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5018     for(i = 0; i < 8; i++) {
5019         uint64_t mant;
5020         uint16_t exp;
5021         
5022         switch(fpregs_format) {
5023         case 0:
5024             mant = qemu_get_be64(f);
5025             exp = qemu_get_be16(f);
5026 #ifdef USE_X86LDOUBLE
5027             env->fpregs[i].d = cpu_set_fp80(mant, exp);
5028 #else
5029             /* difficult case */
5030             if (guess_mmx)
5031                 env->fpregs[i].mmx.MMX_Q(0) = mant;
5032             else
5033                 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5034 #endif
5035             break;
5036         case 1:
5037             mant = qemu_get_be64(f);
5038 #ifdef USE_X86LDOUBLE
5039             {
5040                 union x86_longdouble *p;
5041                 /* difficult case */
5042                 p = (void *)&env->fpregs[i];
5043                 if (guess_mmx) {
5044                     p->mant = mant;
5045                     p->exp = 0xffff;
5046                 } else {
5047                     fp64_to_fp80(p, mant);
5048                 }
5049             }
5050 #else
5051             env->fpregs[i].mmx.MMX_Q(0) = mant;
5052 #endif            
5053             break;
5054         default:
5055             return -EINVAL;
5056         }
5057     }
5058
5059     env->fpuc = fpuc;
5060     /* XXX: restore FPU round state */
5061     env->fpstt = (fpus >> 11) & 7;
5062     env->fpus = fpus & ~0x3800;
5063     fptag ^= 0xff;
5064     for(i = 0; i < 8; i++) {
5065         env->fptags[i] = (fptag >> i) & 1;
5066     }
5067     
5068     for(i = 0; i < 6; i++)
5069         cpu_get_seg(f, &env->segs[i]);
5070     cpu_get_seg(f, &env->ldt);
5071     cpu_get_seg(f, &env->tr);
5072     cpu_get_seg(f, &env->gdt);
5073     cpu_get_seg(f, &env->idt);
5074     
5075     qemu_get_be32s(f, &env->sysenter_cs);
5076     qemu_get_be32s(f, &env->sysenter_esp);
5077     qemu_get_be32s(f, &env->sysenter_eip);
5078     
5079     qemu_get_betls(f, &env->cr[0]);
5080     qemu_get_betls(f, &env->cr[2]);
5081     qemu_get_betls(f, &env->cr[3]);
5082     qemu_get_betls(f, &env->cr[4]);
5083     
5084     for(i = 0; i < 8; i++)
5085         qemu_get_betls(f, &env->dr[i]);
5086
5087     /* MMU */
5088     qemu_get_be32s(f, &env->a20_mask);
5089
5090     qemu_get_be32s(f, &env->mxcsr);
5091     for(i = 0; i < CPU_NB_REGS; i++) {
5092         qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5093         qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5094     }
5095
5096 #ifdef TARGET_X86_64
5097     qemu_get_be64s(f, &env->efer);
5098     qemu_get_be64s(f, &env->star);
5099     qemu_get_be64s(f, &env->lstar);
5100     qemu_get_be64s(f, &env->cstar);
5101     qemu_get_be64s(f, &env->fmask);
5102     qemu_get_be64s(f, &env->kernelgsbase);
5103 #endif
5104     if (version_id >= 4) 
5105         qemu_get_be32s(f, &env->smbase);
5106
5107     /* XXX: compute hflags from scratch, except for CPL and IIF */
5108     env->hflags = hflags;
5109     tlb_flush(env, 1);
5110     return 0;
5111 }
5112
5113 #elif defined(TARGET_PPC)
5114 void cpu_save(QEMUFile *f, void *opaque)
5115 {
5116 }
5117
5118 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5119 {
5120     return 0;
5121 }
5122
5123 #elif defined(TARGET_MIPS)
5124 void cpu_save(QEMUFile *f, void *opaque)
5125 {
5126 }
5127
5128 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5129 {
5130     return 0;
5131 }
5132
5133 #elif defined(TARGET_SPARC)
5134 void cpu_save(QEMUFile *f, void *opaque)
5135 {
5136     CPUState *env = opaque;
5137     int i;
5138     uint32_t tmp;
5139
5140     for(i = 0; i < 8; i++)
5141         qemu_put_betls(f, &env->gregs[i]);
5142     for(i = 0; i < NWINDOWS * 16; i++)
5143         qemu_put_betls(f, &env->regbase[i]);
5144
5145     /* FPU */
5146     for(i = 0; i < TARGET_FPREGS; i++) {
5147         union {
5148             float32 f;
5149             uint32_t i;
5150         } u;
5151         u.f = env->fpr[i];
5152         qemu_put_be32(f, u.i);
5153     }
5154
5155     qemu_put_betls(f, &env->pc);
5156     qemu_put_betls(f, &env->npc);
5157     qemu_put_betls(f, &env->y);
5158     tmp = GET_PSR(env);
5159     qemu_put_be32(f, tmp);
5160     qemu_put_betls(f, &env->fsr);
5161     qemu_put_betls(f, &env->tbr);
5162 #ifndef TARGET_SPARC64
5163     qemu_put_be32s(f, &env->wim);
5164     /* MMU */
5165     for(i = 0; i < 16; i++)
5166         qemu_put_be32s(f, &env->mmuregs[i]);
5167 #endif
5168 }
5169
5170 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5171 {
5172     CPUState *env = opaque;
5173     int i;
5174     uint32_t tmp;
5175
5176     for(i = 0; i < 8; i++)
5177         qemu_get_betls(f, &env->gregs[i]);
5178     for(i = 0; i < NWINDOWS * 16; i++)
5179         qemu_get_betls(f, &env->regbase[i]);
5180
5181     /* FPU */
5182     for(i = 0; i < TARGET_FPREGS; i++) {
5183         union {
5184             float32 f;
5185             uint32_t i;
5186         } u;
5187         u.i = qemu_get_be32(f);
5188         env->fpr[i] = u.f;
5189     }
5190
5191     qemu_get_betls(f, &env->pc);
5192     qemu_get_betls(f, &env->npc);
5193     qemu_get_betls(f, &env->y);
5194     tmp = qemu_get_be32(f);
5195     env->cwp = 0; /* needed to ensure that the wrapping registers are
5196                      correctly updated */
5197     PUT_PSR(env, tmp);
5198     qemu_get_betls(f, &env->fsr);
5199     qemu_get_betls(f, &env->tbr);
5200 #ifndef TARGET_SPARC64
5201     qemu_get_be32s(f, &env->wim);
5202     /* MMU */
5203     for(i = 0; i < 16; i++)
5204         qemu_get_be32s(f, &env->mmuregs[i]);
5205 #endif
5206     tlb_flush(env, 1);
5207     return 0;
5208 }
5209
5210 #elif defined(TARGET_ARM)
5211
5212 /* ??? Need to implement these.  */
5213 void cpu_save(QEMUFile *f, void *opaque)
5214 {
5215 }
5216
5217 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5218 {
5219     return 0;
5220 }
5221
5222 #else
5223
5224 #warning No CPU save/restore functions
5225
5226 #endif
5227
5228 /***********************************************************/
5229 /* ram save/restore */
5230
5231 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5232 {
5233     int v;
5234
5235     v = qemu_get_byte(f);
5236     switch(v) {
5237     case 0:
5238         if (qemu_get_buffer(f, buf, len) != len)
5239             return -EIO;
5240         break;
5241     case 1:
5242         v = qemu_get_byte(f);
5243         memset(buf, v, len);
5244         break;
5245     default:
5246         return -EINVAL;
5247     }
5248     return 0;
5249 }
5250
5251 static int ram_load_v1(QEMUFile *f, void *opaque)
5252 {
5253     int i, ret;
5254
5255     if (qemu_get_be32(f) != phys_ram_size)
5256         return -EINVAL;
5257     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5258         ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5259         if (ret)
5260             return ret;
5261     }
5262     return 0;
5263 }
5264
5265 #define BDRV_HASH_BLOCK_SIZE 1024
5266 #define IOBUF_SIZE 4096
5267 #define RAM_CBLOCK_MAGIC 0xfabe
5268
5269 typedef struct RamCompressState {
5270     z_stream zstream;
5271     QEMUFile *f;
5272     uint8_t buf[IOBUF_SIZE];
5273 } RamCompressState;
5274
5275 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5276 {
5277     int ret;
5278     memset(s, 0, sizeof(*s));
5279     s->f = f;
5280     ret = deflateInit2(&s->zstream, 1,
5281                        Z_DEFLATED, 15, 
5282                        9, Z_DEFAULT_STRATEGY);
5283     if (ret != Z_OK)
5284         return -1;
5285     s->zstream.avail_out = IOBUF_SIZE;
5286     s->zstream.next_out = s->buf;
5287     return 0;
5288 }
5289
5290 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5291 {
5292     qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5293     qemu_put_be16(s->f, len);
5294     qemu_put_buffer(s->f, buf, len);
5295 }
5296
5297 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5298 {
5299     int ret;
5300
5301     s->zstream.avail_in = len;
5302     s->zstream.next_in = (uint8_t *)buf;
5303     while (s->zstream.avail_in > 0) {
5304         ret = deflate(&s->zstream, Z_NO_FLUSH);
5305         if (ret != Z_OK)
5306             return -1;
5307         if (s->zstream.avail_out == 0) {
5308             ram_put_cblock(s, s->buf, IOBUF_SIZE);
5309             s->zstream.avail_out = IOBUF_SIZE;
5310             s->zstream.next_out = s->buf;
5311         }
5312     }
5313     return 0;
5314 }
5315
5316 static void ram_compress_close(RamCompressState *s)
5317 {
5318     int len, ret;
5319
5320     /* compress last bytes */
5321     for(;;) {
5322         ret = deflate(&s->zstream, Z_FINISH);
5323         if (ret == Z_OK || ret == Z_STREAM_END) {
5324             len = IOBUF_SIZE - s->zstream.avail_out;
5325             if (len > 0) {
5326                 ram_put_cblock(s, s->buf, len);
5327             }
5328             s->zstream.avail_out = IOBUF_SIZE;
5329             s->zstream.next_out = s->buf;
5330             if (ret == Z_STREAM_END)
5331                 break;
5332         } else {
5333             goto fail;
5334         }
5335     }
5336 fail:
5337     deflateEnd(&s->zstream);
5338 }
5339
5340 typedef struct RamDecompressState {
5341     z_stream zstream;
5342     QEMUFile *f;
5343     uint8_t buf[IOBUF_SIZE];
5344 } RamDecompressState;
5345
5346 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5347 {
5348     int ret;
5349     memset(s, 0, sizeof(*s));
5350     s->f = f;
5351     ret = inflateInit(&s->zstream);
5352     if (ret != Z_OK)
5353         return -1;
5354     return 0;
5355 }
5356
5357 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5358 {
5359     int ret, clen;
5360
5361     s->zstream.avail_out = len;
5362     s->zstream.next_out = buf;
5363     while (s->zstream.avail_out > 0) {
5364         if (s->zstream.avail_in == 0) {
5365             if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5366                 return -1;
5367             clen = qemu_get_be16(s->f);
5368             if (clen > IOBUF_SIZE)
5369                 return -1;
5370             qemu_get_buffer(s->f, s->buf, clen);
5371             s->zstream.avail_in = clen;
5372             s->zstream.next_in = s->buf;
5373         }
5374         ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5375         if (ret != Z_OK && ret != Z_STREAM_END) {
5376             return -1;
5377         }
5378     }
5379     return 0;
5380 }
5381
5382 static void ram_decompress_close(RamDecompressState *s)
5383 {
5384     inflateEnd(&s->zstream);
5385 }
5386
5387 static void ram_save(QEMUFile *f, void *opaque)
5388 {
5389     int i;
5390     RamCompressState s1, *s = &s1;
5391     uint8_t buf[10];
5392     
5393     qemu_put_be32(f, phys_ram_size);
5394     if (ram_compress_open(s, f) < 0)
5395         return;
5396     for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5397 #if 0
5398         if (tight_savevm_enabled) {
5399             int64_t sector_num;
5400             int j;
5401
5402             /* find if the memory block is available on a virtual
5403                block device */
5404             sector_num = -1;
5405             for(j = 0; j < MAX_DISKS; j++) {
5406                 if (bs_table[j]) {
5407                     sector_num = bdrv_hash_find(bs_table[j], 
5408                                                 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5409                     if (sector_num >= 0)
5410                         break;
5411                 }
5412             }
5413             if (j == MAX_DISKS)
5414                 goto normal_compress;
5415             buf[0] = 1;
5416             buf[1] = j;
5417             cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5418             ram_compress_buf(s, buf, 10);
5419         } else 
5420 #endif
5421         {
5422             //        normal_compress:
5423             buf[0] = 0;
5424             ram_compress_buf(s, buf, 1);
5425             ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5426         }
5427     }
5428     ram_compress_close(s);
5429 }
5430
5431 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5432 {
5433     RamDecompressState s1, *s = &s1;
5434     uint8_t buf[10];
5435     int i;
5436
5437     if (version_id == 1)
5438         return ram_load_v1(f, opaque);
5439     if (version_id != 2)
5440         return -EINVAL;
5441     if (qemu_get_be32(f) != phys_ram_size)
5442         return -EINVAL;
5443     if (ram_decompress_open(s, f) < 0)
5444         return -EINVAL;
5445     for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5446         if (ram_decompress_buf(s, buf, 1) < 0) {
5447             fprintf(stderr, "Error while reading ram block header\n");
5448             goto error;
5449         }
5450         if (buf[0] == 0) {
5451             if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5452                 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5453                 goto error;
5454             }
5455         } else 
5456 #if 0
5457         if (buf[0] == 1) {
5458             int bs_index;
5459             int64_t sector_num;
5460
5461             ram_decompress_buf(s, buf + 1, 9);
5462             bs_index = buf[1];
5463             sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5464             if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5465                 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5466                 goto error;
5467             }
5468             if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i, 
5469                           BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5470                 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n", 
5471                         bs_index, sector_num);
5472                 goto error;
5473             }
5474         } else 
5475 #endif
5476         {
5477         error:
5478             printf("Error block header\n");
5479             return -EINVAL;
5480         }
5481     }
5482     ram_decompress_close(s);
5483     return 0;
5484 }
5485
5486 /***********************************************************/
5487 /* bottom halves (can be seen as timers which expire ASAP) */
5488
5489 struct QEMUBH {
5490     QEMUBHFunc *cb;
5491     void *opaque;
5492     int scheduled;
5493     QEMUBH *next;
5494 };
5495
5496 static QEMUBH *first_bh = NULL;
5497
5498 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5499 {
5500     QEMUBH *bh;
5501     bh = qemu_mallocz(sizeof(QEMUBH));
5502     if (!bh)
5503         return NULL;
5504     bh->cb = cb;
5505     bh->opaque = opaque;
5506     return bh;
5507 }
5508
5509 int qemu_bh_poll(void)
5510 {
5511     QEMUBH *bh, **pbh;
5512     int ret;
5513
5514     ret = 0;
5515     for(;;) {
5516         pbh = &first_bh;
5517         bh = *pbh;
5518         if (!bh)
5519             break;
5520         ret = 1;
5521         *pbh = bh->next;
5522         bh->scheduled = 0;
5523         bh->cb(bh->opaque);
5524     }
5525     return ret;
5526 }
5527
5528 void qemu_bh_schedule(QEMUBH *bh)
5529 {
5530     CPUState *env = cpu_single_env;
5531     if (bh->scheduled)
5532         return;
5533     bh->scheduled = 1;
5534     bh->next = first_bh;
5535     first_bh = bh;
5536
5537     /* stop the currently executing CPU to execute the BH ASAP */
5538     if (env) {
5539         cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5540     }
5541 }
5542
5543 void qemu_bh_cancel(QEMUBH *bh)
5544 {
5545     QEMUBH **pbh;
5546     if (bh->scheduled) {
5547         pbh = &first_bh;
5548         while (*pbh != bh)
5549             pbh = &(*pbh)->next;
5550         *pbh = bh->next;
5551         bh->scheduled = 0;
5552     }
5553 }
5554
5555 void qemu_bh_delete(QEMUBH *bh)
5556 {
5557     qemu_bh_cancel(bh);
5558     qemu_free(bh);
5559 }
5560
5561 /***********************************************************/
5562 /* machine registration */
5563
5564 QEMUMachine *first_machine = NULL;
5565
5566 int qemu_register_machine(QEMUMachine *m)
5567 {
5568     QEMUMachine **pm;
5569     pm = &first_machine;
5570     while (*pm != NULL)
5571         pm = &(*pm)->next;
5572     m->next = NULL;
5573     *pm = m;
5574     return 0;
5575 }
5576
5577 QEMUMachine *find_machine(const char *name)
5578 {
5579     QEMUMachine *m;
5580
5581     for(m = first_machine; m != NULL; m = m->next) {
5582         if (!strcmp(m->name, name))
5583             return m;
5584     }
5585     return NULL;
5586 }
5587
5588 /***********************************************************/
5589 /* main execution loop */
5590
5591 void gui_update(void *opaque)
5592 {
5593     display_state.dpy_refresh(&display_state);
5594     qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5595 }
5596
5597 struct vm_change_state_entry {
5598     VMChangeStateHandler *cb;
5599     void *opaque;
5600     LIST_ENTRY (vm_change_state_entry) entries;
5601 };
5602
5603 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5604
5605 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5606                                                      void *opaque)
5607 {
5608     VMChangeStateEntry *e;
5609
5610     e = qemu_mallocz(sizeof (*e));
5611     if (!e)
5612         return NULL;
5613
5614     e->cb = cb;
5615     e->opaque = opaque;
5616     LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5617     return e;
5618 }
5619
5620 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5621 {
5622     LIST_REMOVE (e, entries);
5623     qemu_free (e);
5624 }
5625
5626 static void vm_state_notify(int running)
5627 {
5628     VMChangeStateEntry *e;
5629
5630     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5631         e->cb(e->opaque, running);
5632     }
5633 }
5634
5635 /* XXX: support several handlers */
5636 static VMStopHandler *vm_stop_cb;
5637 static void *vm_stop_opaque;
5638
5639 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5640 {
5641     vm_stop_cb = cb;
5642     vm_stop_opaque = opaque;
5643     return 0;
5644 }
5645
5646 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5647 {
5648     vm_stop_cb = NULL;
5649 }
5650
5651 void vm_start(void)
5652 {
5653     if (!vm_running) {
5654         cpu_enable_ticks();
5655         vm_running = 1;
5656         vm_state_notify(1);
5657     }
5658 }
5659
5660 void vm_stop(int reason) 
5661 {
5662     if (vm_running) {
5663         cpu_disable_ticks();
5664         vm_running = 0;
5665         if (reason != 0) {
5666             if (vm_stop_cb) {
5667                 vm_stop_cb(vm_stop_opaque, reason);
5668             }
5669         }
5670         vm_state_notify(0);
5671     }
5672 }
5673
5674 /* reset/shutdown handler */
5675
5676 typedef struct QEMUResetEntry {
5677     QEMUResetHandler *func;
5678     void *opaque;
5679     struct QEMUResetEntry *next;
5680 } QEMUResetEntry;
5681
5682 static QEMUResetEntry *first_reset_entry;
5683 static int reset_requested;
5684 static int shutdown_requested;
5685 static int powerdown_requested;
5686
5687 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5688 {
5689     QEMUResetEntry **pre, *re;
5690
5691     pre = &first_reset_entry;
5692     while (*pre != NULL)
5693         pre = &(*pre)->next;
5694     re = qemu_mallocz(sizeof(QEMUResetEntry));
5695     re->func = func;
5696     re->opaque = opaque;
5697     re->next = NULL;
5698     *pre = re;
5699 }
5700
5701 void qemu_system_reset(void)
5702 {
5703     QEMUResetEntry *re;
5704
5705     /* reset all devices */
5706     for(re = first_reset_entry; re != NULL; re = re->next) {
5707         re->func(re->opaque);
5708     }
5709 }
5710
5711 void qemu_system_reset_request(void)
5712 {
5713     if (no_reboot) {
5714         shutdown_requested = 1;
5715     } else {
5716         reset_requested = 1;
5717     }
5718     if (cpu_single_env)
5719         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5720 }
5721
5722 void qemu_system_shutdown_request(void)
5723 {
5724     shutdown_requested = 1;
5725     if (cpu_single_env)
5726         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5727 }
5728
5729 void qemu_system_powerdown_request(void)
5730 {
5731     powerdown_requested = 1;
5732     if (cpu_single_env)
5733         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5734 }
5735
5736 void main_loop_wait(int timeout)
5737 {
5738     IOHandlerRecord *ioh, *ioh_next;
5739     fd_set rfds, wfds, xfds;
5740     int ret, nfds;
5741     struct timeval tv;
5742     PollingEntry *pe;
5743
5744
5745     /* XXX: need to suppress polling by better using win32 events */
5746     ret = 0;
5747     for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5748         ret |= pe->func(pe->opaque);
5749     }
5750 #ifdef _WIN32
5751     if (ret == 0 && timeout > 0) {
5752         int err;
5753         WaitObjects *w = &wait_objects;
5754         
5755         ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5756         if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5757             if (w->func[ret - WAIT_OBJECT_0])
5758                 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5759         } else if (ret == WAIT_TIMEOUT) {
5760         } else {
5761             err = GetLastError();
5762             fprintf(stderr, "Wait error %d %d\n", ret, err);
5763         }
5764     }
5765 #endif
5766     /* poll any events */
5767     /* XXX: separate device handlers from system ones */
5768     nfds = -1;
5769     FD_ZERO(&rfds);
5770     FD_ZERO(&wfds);
5771     FD_ZERO(&xfds);
5772     for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5773         if (ioh->fd_read &&
5774             (!ioh->fd_read_poll ||
5775              ioh->fd_read_poll(ioh->opaque) != 0)) {
5776             FD_SET(ioh->fd, &rfds);
5777             if (ioh->fd > nfds)
5778                 nfds = ioh->fd;
5779         }
5780         if (ioh->fd_write) {
5781             FD_SET(ioh->fd, &wfds);
5782             if (ioh->fd > nfds)
5783                 nfds = ioh->fd;
5784         }
5785     }
5786     
5787     tv.tv_sec = 0;
5788 #ifdef _WIN32
5789     tv.tv_usec = 0;
5790 #else
5791     tv.tv_usec = timeout * 1000;
5792 #endif
5793 #if defined(CONFIG_SLIRP)
5794     if (slirp_inited) {
5795         slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5796     }
5797 #endif
5798     ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5799     if (ret > 0) {
5800         /* XXX: better handling of removal */
5801         for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5802             ioh_next = ioh->next;
5803             if (FD_ISSET(ioh->fd, &rfds)) {
5804                 ioh->fd_read(ioh->opaque);
5805             }
5806             if (FD_ISSET(ioh->fd, &wfds)) {
5807                 ioh->fd_write(ioh->opaque);
5808             }
5809         }
5810     }
5811 #if defined(CONFIG_SLIRP)
5812     if (slirp_inited) {
5813         if (ret < 0) {
5814             FD_ZERO(&rfds);
5815             FD_ZERO(&wfds);
5816             FD_ZERO(&xfds);
5817         }
5818         slirp_select_poll(&rfds, &wfds, &xfds);
5819     }
5820 #endif
5821     qemu_aio_poll();
5822     qemu_bh_poll();
5823
5824     if (vm_running) {
5825         qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
5826                         qemu_get_clock(vm_clock));
5827         /* run dma transfers, if any */
5828         DMA_run();
5829     }
5830     
5831     /* real time timers */
5832     qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
5833                     qemu_get_clock(rt_clock));
5834 }
5835
5836 static CPUState *cur_cpu;
5837
5838 int main_loop(void)
5839 {
5840     int ret, timeout;
5841 #ifdef CONFIG_PROFILER
5842     int64_t ti;
5843 #endif
5844     CPUState *env;
5845
5846     cur_cpu = first_cpu;
5847     for(;;) {
5848         if (vm_running) {
5849
5850             env = cur_cpu;
5851             for(;;) {
5852                 /* get next cpu */
5853                 env = env->next_cpu;
5854                 if (!env)
5855                     env = first_cpu;
5856 #ifdef CONFIG_PROFILER
5857                 ti = profile_getclock();
5858 #endif
5859                 ret = cpu_exec(env);
5860 #ifdef CONFIG_PROFILER
5861                 qemu_time += profile_getclock() - ti;
5862 #endif
5863                 if (ret != EXCP_HALTED)
5864                     break;
5865                 /* all CPUs are halted ? */
5866                 if (env == cur_cpu) {
5867                     ret = EXCP_HLT;
5868                     break;
5869                 }
5870             }
5871             cur_cpu = env;
5872
5873             if (shutdown_requested) {
5874                 ret = EXCP_INTERRUPT;
5875                 break;
5876             }
5877             if (reset_requested) {
5878                 reset_requested = 0;
5879                 qemu_system_reset();
5880                 ret = EXCP_INTERRUPT;
5881             }
5882             if (powerdown_requested) {
5883                 powerdown_requested = 0;
5884                 qemu_system_powerdown();
5885                 ret = EXCP_INTERRUPT;
5886             }
5887             if (ret == EXCP_DEBUG) {
5888                 vm_stop(EXCP_DEBUG);
5889             }
5890             /* if hlt instruction, we wait until the next IRQ */
5891             /* XXX: use timeout computed from timers */
5892             if (ret == EXCP_HLT)
5893                 timeout = 10;
5894             else
5895                 timeout = 0;
5896         } else {
5897             timeout = 10;
5898         }
5899 #ifdef CONFIG_PROFILER
5900         ti = profile_getclock();
5901 #endif
5902         main_loop_wait(timeout);
5903 #ifdef CONFIG_PROFILER
5904         dev_time += profile_getclock() - ti;
5905 #endif
5906     }
5907     cpu_disable_ticks();
5908     return ret;
5909 }
5910
5911 void help(void)
5912 {
5913     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2006 Fabrice Bellard\n"
5914            "usage: %s [options] [disk_image]\n"
5915            "\n"
5916            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5917            "\n"
5918            "Standard options:\n"
5919            "-M machine      select emulated machine (-M ? for list)\n"
5920            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
5921            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
5922            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
5923            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5924            "-boot [a|c|d]   boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5925            "-snapshot       write to temporary files instead of disk image files\n"
5926 #ifdef CONFIG_SDL
5927            "-no-quit        disable SDL window close capability\n"
5928 #endif
5929 #ifdef TARGET_I386
5930            "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
5931 #endif
5932            "-m megs         set virtual RAM size to megs MB [default=%d]\n"
5933            "-smp n          set the number of CPUs to 'n' [default=1]\n"
5934            "-nographic      disable graphical output and redirect serial I/Os to console\n"
5935 #ifndef _WIN32
5936            "-k language     use keyboard layout (for example \"fr\" for French)\n"
5937 #endif
5938 #ifdef HAS_AUDIO
5939            "-audio-help     print list of audio drivers and their options\n"
5940            "-soundhw c1,... enable audio support\n"
5941            "                and only specified sound cards (comma separated list)\n"
5942            "                use -soundhw ? to get the list of supported cards\n"
5943            "                use -soundhw all to enable all of them\n"
5944 #endif
5945            "-localtime      set the real time clock to local time [default=utc]\n"
5946            "-full-screen    start in full screen\n"
5947 #ifdef TARGET_I386
5948            "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
5949 #endif
5950            "-usb            enable the USB driver (will be the default soon)\n"
5951            "-usbdevice name add the host or guest USB device 'name'\n"
5952 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5953            "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
5954 #endif
5955            "\n"
5956            "Network options:\n"
5957            "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5958            "                create a new Network Interface Card and connect it to VLAN 'n'\n"
5959 #ifdef CONFIG_SLIRP
5960            "-net user[,vlan=n][,hostname=host]\n"
5961            "                connect the user mode network stack to VLAN 'n' and send\n"
5962            "                hostname 'host' to DHCP clients\n"
5963 #endif
5964 #ifdef _WIN32
5965            "-net tap[,vlan=n],ifname=name\n"
5966            "                connect the host TAP network interface to VLAN 'n'\n"
5967 #else
5968            "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5969            "                connect the host TAP network interface to VLAN 'n' and use\n"
5970            "                the network script 'file' (default=%s);\n"
5971            "                use 'fd=h' to connect to an already opened TAP interface\n"
5972 #endif
5973            "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5974            "                connect the vlan 'n' to another VLAN using a socket connection\n"
5975            "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5976            "                connect the vlan 'n' to multicast maddr and port\n"
5977            "-net none       use it alone to have zero network devices; if no -net option\n"
5978            "                is provided, the default is '-net nic -net user'\n"
5979            "\n"
5980 #ifdef CONFIG_SLIRP
5981            "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
5982 #ifndef _WIN32
5983            "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
5984 #endif
5985            "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5986            "                redirect TCP or UDP connections from host to guest [-net user]\n"
5987 #endif
5988            "\n"
5989            "Linux boot specific:\n"
5990            "-kernel bzImage use 'bzImage' as kernel image\n"
5991            "-append cmdline use 'cmdline' as kernel command line\n"
5992            "-initrd file    use 'file' as initial ram disk\n"
5993            "\n"
5994            "Debug/Expert options:\n"
5995            "-monitor dev    redirect the monitor to char device 'dev'\n"
5996            "-serial dev     redirect the serial port to char device 'dev'\n"
5997            "-parallel dev   redirect the parallel port to char device 'dev'\n"
5998            "-pidfile file   Write PID to 'file'\n"
5999            "-S              freeze CPU at startup (use 'c' to start execution)\n"
6000            "-s              wait gdb connection to port %d\n"
6001            "-p port         change gdb connection port\n"
6002            "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
6003            "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
6004            "                translation (t=none or lba) (usually qemu can guess them)\n"
6005            "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
6006 #ifdef USE_KQEMU
6007            "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
6008            "-no-kqemu       disable KQEMU kernel module usage\n"
6009 #endif
6010 #ifdef USE_CODE_COPY
6011            "-no-code-copy   disable code copy acceleration\n"
6012 #endif
6013 #ifdef TARGET_I386
6014            "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
6015            "                (default is CL-GD5446 PCI VGA)\n"
6016            "-no-acpi        disable ACPI\n"
6017 #endif
6018            "-no-reboot      exit instead of rebooting\n"
6019            "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
6020            "-vnc display    start a VNC server on display\n"
6021            "\n"
6022            "During emulation, the following keys are useful:\n"
6023            "ctrl-alt-f      toggle full screen\n"
6024            "ctrl-alt-n      switch to virtual console 'n'\n"
6025            "ctrl-alt        toggle mouse and keyboard grab\n"
6026            "\n"
6027            "When using -nographic, press 'ctrl-a h' to get some help.\n"
6028            ,
6029            "qemu",
6030            DEFAULT_RAM_SIZE,
6031 #ifndef _WIN32
6032            DEFAULT_NETWORK_SCRIPT,
6033 #endif
6034            DEFAULT_GDBSTUB_PORT,
6035            "/tmp/qemu.log");
6036     exit(1);
6037 }
6038
6039 #define HAS_ARG 0x0001
6040
6041 enum {
6042     QEMU_OPTION_h,
6043
6044     QEMU_OPTION_M,
6045     QEMU_OPTION_fda,
6046     QEMU_OPTION_fdb,
6047     QEMU_OPTION_hda,
6048     QEMU_OPTION_hdb,
6049     QEMU_OPTION_hdc,
6050     QEMU_OPTION_hdd,
6051     QEMU_OPTION_cdrom,
6052     QEMU_OPTION_boot,
6053     QEMU_OPTION_snapshot,
6054 #ifdef TARGET_I386
6055     QEMU_OPTION_no_fd_bootchk,
6056 #endif
6057     QEMU_OPTION_m,
6058     QEMU_OPTION_nographic,
6059 #ifdef HAS_AUDIO
6060     QEMU_OPTION_audio_help,
6061     QEMU_OPTION_soundhw,
6062 #endif
6063
6064     QEMU_OPTION_net,
6065     QEMU_OPTION_tftp,
6066     QEMU_OPTION_smb,
6067     QEMU_OPTION_redir,
6068
6069     QEMU_OPTION_kernel,
6070     QEMU_OPTION_append,
6071     QEMU_OPTION_initrd,
6072
6073     QEMU_OPTION_S,
6074     QEMU_OPTION_s,
6075     QEMU_OPTION_p,
6076     QEMU_OPTION_d,
6077     QEMU_OPTION_hdachs,
6078     QEMU_OPTION_L,
6079     QEMU_OPTION_no_code_copy,
6080     QEMU_OPTION_k,
6081     QEMU_OPTION_localtime,
6082     QEMU_OPTION_cirrusvga,
6083     QEMU_OPTION_g,
6084     QEMU_OPTION_std_vga,
6085     QEMU_OPTION_monitor,
6086     QEMU_OPTION_serial,
6087     QEMU_OPTION_parallel,
6088     QEMU_OPTION_loadvm,
6089     QEMU_OPTION_full_screen,
6090     QEMU_OPTION_no_quit,
6091     QEMU_OPTION_pidfile,
6092     QEMU_OPTION_no_kqemu,
6093     QEMU_OPTION_kernel_kqemu,
6094     QEMU_OPTION_win2k_hack,
6095     QEMU_OPTION_usb,
6096     QEMU_OPTION_usbdevice,
6097     QEMU_OPTION_smp,
6098     QEMU_OPTION_vnc,
6099     QEMU_OPTION_no_acpi,
6100     QEMU_OPTION_no_reboot,
6101 };
6102
6103 typedef struct QEMUOption {
6104     const char *name;
6105     int flags;
6106     int index;
6107 } QEMUOption;
6108
6109 const QEMUOption qemu_options[] = {
6110     { "h", 0, QEMU_OPTION_h },
6111
6112     { "M", HAS_ARG, QEMU_OPTION_M },
6113     { "fda", HAS_ARG, QEMU_OPTION_fda },
6114     { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6115     { "hda", HAS_ARG, QEMU_OPTION_hda },
6116     { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6117     { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6118     { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6119     { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6120     { "boot", HAS_ARG, QEMU_OPTION_boot },
6121     { "snapshot", 0, QEMU_OPTION_snapshot },
6122 #ifdef TARGET_I386
6123     { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6124 #endif
6125     { "m", HAS_ARG, QEMU_OPTION_m },
6126     { "nographic", 0, QEMU_OPTION_nographic },
6127     { "k", HAS_ARG, QEMU_OPTION_k },
6128 #ifdef HAS_AUDIO
6129     { "audio-help", 0, QEMU_OPTION_audio_help },
6130     { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6131 #endif
6132
6133     { "net", HAS_ARG, QEMU_OPTION_net},
6134 #ifdef CONFIG_SLIRP
6135     { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6136 #ifndef _WIN32
6137     { "smb", HAS_ARG, QEMU_OPTION_smb },
6138 #endif
6139     { "redir", HAS_ARG, QEMU_OPTION_redir },
6140 #endif
6141
6142     { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6143     { "append", HAS_ARG, QEMU_OPTION_append },
6144     { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6145
6146     { "S", 0, QEMU_OPTION_S },
6147     { "s", 0, QEMU_OPTION_s },
6148     { "p", HAS_ARG, QEMU_OPTION_p },
6149     { "d", HAS_ARG, QEMU_OPTION_d },
6150     { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6151     { "L", HAS_ARG, QEMU_OPTION_L },
6152     { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6153 #ifdef USE_KQEMU
6154     { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6155     { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6156 #endif
6157 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6158     { "g", 1, QEMU_OPTION_g },
6159 #endif
6160     { "localtime", 0, QEMU_OPTION_localtime },
6161     { "std-vga", 0, QEMU_OPTION_std_vga },
6162     { "monitor", 1, QEMU_OPTION_monitor },
6163     { "serial", 1, QEMU_OPTION_serial },
6164     { "parallel", 1, QEMU_OPTION_parallel },
6165     { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6166     { "full-screen", 0, QEMU_OPTION_full_screen },
6167 #ifdef CONFIG_SDL
6168     { "no-quit", 0, QEMU_OPTION_no_quit },
6169 #endif
6170     { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6171     { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6172     { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6173     { "smp", HAS_ARG, QEMU_OPTION_smp },
6174     { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6175     
6176     /* temporary options */
6177     { "usb", 0, QEMU_OPTION_usb },
6178     { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6179     { "no-acpi", 0, QEMU_OPTION_no_acpi },
6180     { "no-reboot", 0, QEMU_OPTION_no_reboot },
6181     { NULL },
6182 };
6183
6184 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6185
6186 /* this stack is only used during signal handling */
6187 #define SIGNAL_STACK_SIZE 32768
6188
6189 static uint8_t *signal_stack;
6190
6191 #endif
6192
6193 /* password input */
6194
6195 static BlockDriverState *get_bdrv(int index)
6196 {
6197     BlockDriverState *bs;
6198
6199     if (index < 4) {
6200         bs = bs_table[index];
6201     } else if (index < 6) {
6202         bs = fd_table[index - 4];
6203     } else {
6204         bs = NULL;
6205     }
6206     return bs;
6207 }
6208
6209 static void read_passwords(void)
6210 {
6211     BlockDriverState *bs;
6212     int i, j;
6213     char password[256];
6214
6215     for(i = 0; i < 6; i++) {
6216         bs = get_bdrv(i);
6217         if (bs && bdrv_is_encrypted(bs)) {
6218             term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6219             for(j = 0; j < 3; j++) {
6220                 monitor_readline("Password: ", 
6221                                  1, password, sizeof(password));
6222                 if (bdrv_set_key(bs, password) == 0)
6223                     break;
6224                 term_printf("invalid password\n");
6225             }
6226         }
6227     }
6228 }
6229
6230 /* XXX: currently we cannot use simultaneously different CPUs */
6231 void register_machines(void)
6232 {
6233 #if defined(TARGET_I386)
6234     qemu_register_machine(&pc_machine);
6235     qemu_register_machine(&isapc_machine);
6236 #elif defined(TARGET_PPC)
6237     qemu_register_machine(&heathrow_machine);
6238     qemu_register_machine(&core99_machine);
6239     qemu_register_machine(&prep_machine);
6240 #elif defined(TARGET_MIPS)
6241     qemu_register_machine(&mips_machine);
6242 #elif defined(TARGET_SPARC)
6243 #ifdef TARGET_SPARC64
6244     qemu_register_machine(&sun4u_machine);
6245 #else
6246     qemu_register_machine(&sun4m_machine);
6247 #endif
6248 #elif defined(TARGET_ARM)
6249     qemu_register_machine(&integratorcp926_machine);
6250     qemu_register_machine(&integratorcp1026_machine);
6251     qemu_register_machine(&versatilepb_machine);
6252     qemu_register_machine(&versatileab_machine);
6253     qemu_register_machine(&realview_machine);
6254 #elif defined(TARGET_SH4)
6255     qemu_register_machine(&shix_machine);
6256 #else
6257 #error unsupported CPU
6258 #endif
6259 }
6260
6261 #ifdef HAS_AUDIO
6262 struct soundhw soundhw[] = {
6263 #ifdef TARGET_I386
6264     {
6265         "pcspk",
6266         "PC speaker",
6267         0,
6268         1,
6269         { .init_isa = pcspk_audio_init }
6270     },
6271 #endif
6272     {
6273         "sb16",
6274         "Creative Sound Blaster 16",
6275         0,
6276         1,
6277         { .init_isa = SB16_init }
6278     },
6279
6280 #ifdef CONFIG_ADLIB
6281     {
6282         "adlib",
6283 #ifdef HAS_YMF262
6284         "Yamaha YMF262 (OPL3)",
6285 #else
6286         "Yamaha YM3812 (OPL2)",
6287 #endif
6288         0,
6289         1,
6290         { .init_isa = Adlib_init }
6291     },
6292 #endif
6293
6294 #ifdef CONFIG_GUS
6295     {
6296         "gus",
6297         "Gravis Ultrasound GF1",
6298         0,
6299         1,
6300         { .init_isa = GUS_init }
6301     },
6302 #endif
6303
6304     {
6305         "es1370",
6306         "ENSONIQ AudioPCI ES1370",
6307         0,
6308         0,
6309         { .init_pci = es1370_init }
6310     },
6311
6312     { NULL, NULL, 0, 0, { NULL } }
6313 };
6314
6315 static void select_soundhw (const char *optarg)
6316 {
6317     struct soundhw *c;
6318
6319     if (*optarg == '?') {
6320     show_valid_cards:
6321
6322         printf ("Valid sound card names (comma separated):\n");
6323         for (c = soundhw; c->name; ++c) {
6324             printf ("%-11s %s\n", c->name, c->descr);
6325         }
6326         printf ("\n-soundhw all will enable all of the above\n");
6327         exit (*optarg != '?');
6328     }
6329     else {
6330         size_t l;
6331         const char *p;
6332         char *e;
6333         int bad_card = 0;
6334
6335         if (!strcmp (optarg, "all")) {
6336             for (c = soundhw; c->name; ++c) {
6337                 c->enabled = 1;
6338             }
6339             return;
6340         }
6341
6342         p = optarg;
6343         while (*p) {
6344             e = strchr (p, ',');
6345             l = !e ? strlen (p) : (size_t) (e - p);
6346
6347             for (c = soundhw; c->name; ++c) {
6348                 if (!strncmp (c->name, p, l)) {
6349                     c->enabled = 1;
6350                     break;
6351                 }
6352             }
6353
6354             if (!c->name) {
6355                 if (l > 80) {
6356                     fprintf (stderr,
6357                              "Unknown sound card name (too big to show)\n");
6358                 }
6359                 else {
6360                     fprintf (stderr, "Unknown sound card name `%.*s'\n",
6361                              (int) l, p);
6362                 }
6363                 bad_card = 1;
6364             }
6365             p += l + (e != NULL);
6366         }
6367
6368         if (bad_card)
6369             goto show_valid_cards;
6370     }
6371 }
6372 #endif
6373
6374 #ifdef _WIN32
6375 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6376 {
6377     exit(STATUS_CONTROL_C_EXIT);
6378     return TRUE;
6379 }
6380 #endif
6381
6382 #define MAX_NET_CLIENTS 32
6383
6384 int main(int argc, char **argv)
6385 {
6386 #ifdef CONFIG_GDBSTUB
6387     int use_gdbstub, gdbstub_port;
6388 #endif
6389     int i, cdrom_index;
6390     int snapshot, linux_boot;
6391     const char *initrd_filename;
6392     const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6393     const char *kernel_filename, *kernel_cmdline;
6394     DisplayState *ds = &display_state;
6395     int cyls, heads, secs, translation;
6396     int start_emulation = 1;
6397     char net_clients[MAX_NET_CLIENTS][256];
6398     int nb_net_clients;
6399     int optind;
6400     const char *r, *optarg;
6401     CharDriverState *monitor_hd;
6402     char monitor_device[128];
6403     char serial_devices[MAX_SERIAL_PORTS][128];
6404     int serial_device_index;
6405     char parallel_devices[MAX_PARALLEL_PORTS][128];
6406     int parallel_device_index;
6407     const char *loadvm = NULL;
6408     QEMUMachine *machine;
6409     char usb_devices[MAX_USB_CMDLINE][128];
6410     int usb_devices_index;
6411
6412     LIST_INIT (&vm_change_state_head);
6413 #ifndef _WIN32
6414     {
6415         struct sigaction act;
6416         sigfillset(&act.sa_mask);
6417         act.sa_flags = 0;
6418         act.sa_handler = SIG_IGN;
6419         sigaction(SIGPIPE, &act, NULL);
6420     }
6421 #else
6422     SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6423     /* Note: cpu_interrupt() is currently not SMP safe, so we force
6424        QEMU to run on a single CPU */
6425     {
6426         HANDLE h;
6427         DWORD mask, smask;
6428         int i;
6429         h = GetCurrentProcess();
6430         if (GetProcessAffinityMask(h, &mask, &smask)) {
6431             for(i = 0; i < 32; i++) {
6432                 if (mask & (1 << i))
6433                     break;
6434             }
6435             if (i != 32) {
6436                 mask = 1 << i;
6437                 SetProcessAffinityMask(h, mask);
6438             }
6439         }
6440     }
6441 #endif
6442
6443     register_machines();
6444     machine = first_machine;
6445     initrd_filename = NULL;
6446     for(i = 0; i < MAX_FD; i++)
6447         fd_filename[i] = NULL;
6448     for(i = 0; i < MAX_DISKS; i++)
6449         hd_filename[i] = NULL;
6450     ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6451     vga_ram_size = VGA_RAM_SIZE;
6452     bios_size = BIOS_SIZE;
6453 #ifdef CONFIG_GDBSTUB
6454     use_gdbstub = 0;
6455     gdbstub_port = DEFAULT_GDBSTUB_PORT;
6456 #endif
6457     snapshot = 0;
6458     nographic = 0;
6459     kernel_filename = NULL;
6460     kernel_cmdline = "";
6461 #ifdef TARGET_PPC
6462     cdrom_index = 1;
6463 #else
6464     cdrom_index = 2;
6465 #endif
6466     cyls = heads = secs = 0;
6467     translation = BIOS_ATA_TRANSLATION_AUTO;
6468     pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6469
6470     pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6471     for(i = 1; i < MAX_SERIAL_PORTS; i++)
6472         serial_devices[i][0] = '\0';
6473     serial_device_index = 0;
6474     
6475     pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6476     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6477         parallel_devices[i][0] = '\0';
6478     parallel_device_index = 0;
6479     
6480     usb_devices_index = 0;
6481     
6482     nb_net_clients = 0;
6483
6484     nb_nics = 0;
6485     /* default mac address of the first network interface */
6486     
6487     optind = 1;
6488     for(;;) {
6489         if (optind >= argc)
6490             break;
6491         r = argv[optind];
6492         if (r[0] != '-') {
6493             hd_filename[0] = argv[optind++];
6494         } else {
6495             const QEMUOption *popt;
6496
6497             optind++;
6498             popt = qemu_options;
6499             for(;;) {
6500                 if (!popt->name) {
6501                     fprintf(stderr, "%s: invalid option -- '%s'\n", 
6502                             argv[0], r);
6503                     exit(1);
6504                 }
6505                 if (!strcmp(popt->name, r + 1))
6506                     break;
6507                 popt++;
6508             }
6509             if (popt->flags & HAS_ARG) {
6510                 if (optind >= argc) {
6511                     fprintf(stderr, "%s: option '%s' requires an argument\n",
6512                             argv[0], r);
6513                     exit(1);
6514                 }
6515                 optarg = argv[optind++];
6516             } else {
6517                 optarg = NULL;
6518             }
6519
6520             switch(popt->index) {
6521             case QEMU_OPTION_M:
6522                 machine = find_machine(optarg);
6523                 if (!machine) {
6524                     QEMUMachine *m;
6525                     printf("Supported machines are:\n");
6526                     for(m = first_machine; m != NULL; m = m->next) {
6527                         printf("%-10s %s%s\n",
6528                                m->name, m->desc, 
6529                                m == first_machine ? " (default)" : "");
6530                     }
6531                     exit(1);
6532                 }
6533                 break;
6534             case QEMU_OPTION_initrd:
6535                 initrd_filename = optarg;
6536                 break;
6537             case QEMU_OPTION_hda:
6538             case QEMU_OPTION_hdb:
6539             case QEMU_OPTION_hdc:
6540             case QEMU_OPTION_hdd:
6541                 {
6542                     int hd_index;
6543                     hd_index = popt->index - QEMU_OPTION_hda;
6544                     hd_filename[hd_index] = optarg;
6545                     if (hd_index == cdrom_index)
6546                         cdrom_index = -1;
6547                 }
6548                 break;
6549             case QEMU_OPTION_snapshot:
6550                 snapshot = 1;
6551                 break;
6552             case QEMU_OPTION_hdachs:
6553                 {
6554                     const char *p;
6555                     p = optarg;
6556                     cyls = strtol(p, (char **)&p, 0);
6557                     if (cyls < 1 || cyls > 16383)
6558                         goto chs_fail;
6559                     if (*p != ',')
6560                         goto chs_fail;
6561                     p++;
6562                     heads = strtol(p, (char **)&p, 0);
6563                     if (heads < 1 || heads > 16)
6564                         goto chs_fail;
6565                     if (*p != ',')
6566                         goto chs_fail;
6567                     p++;
6568                     secs = strtol(p, (char **)&p, 0);
6569                     if (secs < 1 || secs > 63)
6570                         goto chs_fail;
6571                     if (*p == ',') {
6572                         p++;
6573                         if (!strcmp(p, "none"))
6574                             translation = BIOS_ATA_TRANSLATION_NONE;
6575                         else if (!strcmp(p, "lba"))
6576                             translation = BIOS_ATA_TRANSLATION_LBA;
6577                         else if (!strcmp(p, "auto"))
6578                             translation = BIOS_ATA_TRANSLATION_AUTO;
6579                         else
6580                             goto chs_fail;
6581                     } else if (*p != '\0') {
6582                     chs_fail:
6583                         fprintf(stderr, "qemu: invalid physical CHS format\n");
6584                         exit(1);
6585                     }
6586                 }
6587                 break;
6588             case QEMU_OPTION_nographic:
6589                 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
6590                 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
6591                 nographic = 1;
6592                 break;
6593             case QEMU_OPTION_kernel:
6594                 kernel_filename = optarg;
6595                 break;
6596             case QEMU_OPTION_append:
6597                 kernel_cmdline = optarg;
6598                 break;
6599             case QEMU_OPTION_cdrom:
6600                 if (cdrom_index >= 0) {
6601                     hd_filename[cdrom_index] = optarg;
6602                 }
6603                 break;
6604             case QEMU_OPTION_boot:
6605                 boot_device = optarg[0];
6606                 if (boot_device != 'a' && 
6607 #ifdef TARGET_SPARC
6608                     // Network boot
6609                     boot_device != 'n' &&
6610 #endif
6611                     boot_device != 'c' && boot_device != 'd') {
6612                     fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6613                     exit(1);
6614                 }
6615                 break;
6616             case QEMU_OPTION_fda:
6617                 fd_filename[0] = optarg;
6618                 break;
6619             case QEMU_OPTION_fdb:
6620                 fd_filename[1] = optarg;
6621                 break;
6622 #ifdef TARGET_I386
6623             case QEMU_OPTION_no_fd_bootchk:
6624                 fd_bootchk = 0;
6625                 break;
6626 #endif
6627             case QEMU_OPTION_no_code_copy:
6628                 code_copy_enabled = 0;
6629                 break;
6630             case QEMU_OPTION_net:
6631                 if (nb_net_clients >= MAX_NET_CLIENTS) {
6632                     fprintf(stderr, "qemu: too many network clients\n");
6633                     exit(1);
6634                 }
6635                 pstrcpy(net_clients[nb_net_clients],
6636                         sizeof(net_clients[0]),
6637                         optarg);
6638                 nb_net_clients++;
6639                 break;
6640 #ifdef CONFIG_SLIRP
6641             case QEMU_OPTION_tftp:
6642                 tftp_prefix = optarg;
6643                 break;
6644 #ifndef _WIN32
6645             case QEMU_OPTION_smb:
6646                 net_slirp_smb(optarg);
6647                 break;
6648 #endif
6649             case QEMU_OPTION_redir:
6650                 net_slirp_redir(optarg);                
6651                 break;
6652 #endif
6653 #ifdef HAS_AUDIO
6654             case QEMU_OPTION_audio_help:
6655                 AUD_help ();
6656                 exit (0);
6657                 break;
6658             case QEMU_OPTION_soundhw:
6659                 select_soundhw (optarg);
6660                 break;
6661 #endif
6662             case QEMU_OPTION_h:
6663                 help();
6664                 break;
6665             case QEMU_OPTION_m:
6666                 ram_size = atoi(optarg) * 1024 * 1024;
6667                 if (ram_size <= 0)
6668                     help();
6669                 if (ram_size > PHYS_RAM_MAX_SIZE) {
6670                     fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6671                             PHYS_RAM_MAX_SIZE / (1024 * 1024));
6672                     exit(1);
6673                 }
6674                 break;
6675             case QEMU_OPTION_d:
6676                 {
6677                     int mask;
6678                     CPULogItem *item;
6679                     
6680                     mask = cpu_str_to_log_mask(optarg);
6681                     if (!mask) {
6682                         printf("Log items (comma separated):\n");
6683                     for(item = cpu_log_items; item->mask != 0; item++) {
6684                         printf("%-10s %s\n", item->name, item->help);
6685                     }
6686                     exit(1);
6687                     }
6688                     cpu_set_log(mask);
6689                 }
6690                 break;
6691 #ifdef CONFIG_GDBSTUB
6692             case QEMU_OPTION_s:
6693                 use_gdbstub = 1;
6694                 break;
6695             case QEMU_OPTION_p:
6696                 gdbstub_port = atoi(optarg);
6697                 break;
6698 #endif
6699             case QEMU_OPTION_L:
6700                 bios_dir = optarg;
6701                 break;
6702             case QEMU_OPTION_S:
6703                 start_emulation = 0;
6704                 break;
6705             case QEMU_OPTION_k:
6706                 keyboard_layout = optarg;
6707                 break;
6708             case QEMU_OPTION_localtime:
6709                 rtc_utc = 0;
6710                 break;
6711             case QEMU_OPTION_cirrusvga:
6712                 cirrus_vga_enabled = 1;
6713                 break;
6714             case QEMU_OPTION_std_vga:
6715                 cirrus_vga_enabled = 0;
6716                 break;
6717             case QEMU_OPTION_g:
6718                 {
6719                     const char *p;
6720                     int w, h, depth;
6721                     p = optarg;
6722                     w = strtol(p, (char **)&p, 10);
6723                     if (w <= 0) {
6724                     graphic_error:
6725                         fprintf(stderr, "qemu: invalid resolution or depth\n");
6726                         exit(1);
6727                     }
6728                     if (*p != 'x')
6729                         goto graphic_error;
6730                     p++;
6731                     h = strtol(p, (char **)&p, 10);
6732                     if (h <= 0)
6733                         goto graphic_error;
6734                     if (*p == 'x') {
6735                         p++;
6736                         depth = strtol(p, (char **)&p, 10);
6737                         if (depth != 8 && depth != 15 && depth != 16 && 
6738                             depth != 24 && depth != 32)
6739                             goto graphic_error;
6740                     } else if (*p == '\0') {
6741                         depth = graphic_depth;
6742                     } else {
6743                         goto graphic_error;
6744                     }
6745                     
6746                     graphic_width = w;
6747                     graphic_height = h;
6748                     graphic_depth = depth;
6749                 }
6750                 break;
6751             case QEMU_OPTION_monitor:
6752                 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6753                 break;
6754             case QEMU_OPTION_serial:
6755                 if (serial_device_index >= MAX_SERIAL_PORTS) {
6756                     fprintf(stderr, "qemu: too many serial ports\n");
6757                     exit(1);
6758                 }
6759                 pstrcpy(serial_devices[serial_device_index], 
6760                         sizeof(serial_devices[0]), optarg);
6761                 serial_device_index++;
6762                 break;
6763             case QEMU_OPTION_parallel:
6764                 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6765                     fprintf(stderr, "qemu: too many parallel ports\n");
6766                     exit(1);
6767                 }
6768                 pstrcpy(parallel_devices[parallel_device_index], 
6769                         sizeof(parallel_devices[0]), optarg);
6770                 parallel_device_index++;
6771                 break;
6772             case QEMU_OPTION_loadvm:
6773                 loadvm = optarg;
6774                 break;
6775             case QEMU_OPTION_full_screen:
6776                 full_screen = 1;
6777                 break;
6778 #ifdef CONFIG_SDL
6779             case QEMU_OPTION_no_quit:
6780                 no_quit = 1;
6781                 break;
6782 #endif
6783             case QEMU_OPTION_pidfile:
6784                 create_pidfile(optarg);
6785                 break;
6786 #ifdef TARGET_I386
6787             case QEMU_OPTION_win2k_hack:
6788                 win2k_install_hack = 1;
6789                 break;
6790 #endif
6791 #ifdef USE_KQEMU
6792             case QEMU_OPTION_no_kqemu:
6793                 kqemu_allowed = 0;
6794                 break;
6795             case QEMU_OPTION_kernel_kqemu:
6796                 kqemu_allowed = 2;
6797                 break;
6798 #endif
6799             case QEMU_OPTION_usb:
6800                 usb_enabled = 1;
6801                 break;
6802             case QEMU_OPTION_usbdevice:
6803                 usb_enabled = 1;
6804                 if (usb_devices_index >= MAX_USB_CMDLINE) {
6805                     fprintf(stderr, "Too many USB devices\n");
6806                     exit(1);
6807                 }
6808                 pstrcpy(usb_devices[usb_devices_index],
6809                         sizeof(usb_devices[usb_devices_index]),
6810                         optarg);
6811                 usb_devices_index++;
6812                 break;
6813             case QEMU_OPTION_smp:
6814                 smp_cpus = atoi(optarg);
6815                 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6816                     fprintf(stderr, "Invalid number of CPUs\n");
6817                     exit(1);
6818                 }
6819                 break;
6820             case QEMU_OPTION_vnc:
6821                 vnc_display = atoi(optarg);
6822                 if (vnc_display < 0) {
6823                     fprintf(stderr, "Invalid VNC display\n");
6824                     exit(1);
6825                 }
6826                 break;
6827             case QEMU_OPTION_no_acpi:
6828                 acpi_enabled = 0;
6829                 break;
6830             case QEMU_OPTION_no_reboot:
6831                 no_reboot = 1;
6832                 break;
6833             }
6834         }
6835     }
6836
6837 #ifdef USE_KQEMU
6838     if (smp_cpus > 1)
6839         kqemu_allowed = 0;
6840 #endif
6841     linux_boot = (kernel_filename != NULL);
6842         
6843     if (!linux_boot && 
6844         hd_filename[0] == '\0' && 
6845         (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6846         fd_filename[0] == '\0')
6847         help();
6848     
6849     /* boot to cd by default if no hard disk */
6850     if (hd_filename[0] == '\0' && boot_device == 'c') {
6851         if (fd_filename[0] != '\0')
6852             boot_device = 'a';
6853         else
6854             boot_device = 'd';
6855     }
6856
6857     setvbuf(stdout, NULL, _IOLBF, 0);
6858     
6859     init_timers();
6860     init_timer_alarm();
6861     qemu_aio_init();
6862
6863 #ifdef _WIN32
6864     socket_init();
6865 #endif
6866
6867     /* init network clients */
6868     if (nb_net_clients == 0) {
6869         /* if no clients, we use a default config */
6870         pstrcpy(net_clients[0], sizeof(net_clients[0]),
6871                 "nic");
6872         pstrcpy(net_clients[1], sizeof(net_clients[0]),
6873                 "user");
6874         nb_net_clients = 2;
6875     }
6876
6877     for(i = 0;i < nb_net_clients; i++) {
6878         if (net_client_init(net_clients[i]) < 0)
6879             exit(1);
6880     }
6881
6882     /* init the memory */
6883     phys_ram_size = ram_size + vga_ram_size + bios_size;
6884
6885     phys_ram_base = qemu_vmalloc(phys_ram_size);
6886     if (!phys_ram_base) {
6887         fprintf(stderr, "Could not allocate physical memory\n");
6888         exit(1);
6889     }
6890
6891     /* we always create the cdrom drive, even if no disk is there */
6892     bdrv_init();
6893     if (cdrom_index >= 0) {
6894         bs_table[cdrom_index] = bdrv_new("cdrom");
6895         bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6896     }
6897
6898     /* open the virtual block devices */
6899     for(i = 0; i < MAX_DISKS; i++) {
6900         if (hd_filename[i]) {
6901             if (!bs_table[i]) {
6902                 char buf[64];
6903                 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6904                 bs_table[i] = bdrv_new(buf);
6905             }
6906             if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
6907                 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6908                         hd_filename[i]);
6909                 exit(1);
6910             }
6911             if (i == 0 && cyls != 0) {
6912                 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6913                 bdrv_set_translation_hint(bs_table[i], translation);
6914             }
6915         }
6916     }
6917
6918     /* we always create at least one floppy disk */
6919     fd_table[0] = bdrv_new("fda");
6920     bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6921
6922     for(i = 0; i < MAX_FD; i++) {
6923         if (fd_filename[i]) {
6924             if (!fd_table[i]) {
6925                 char buf[64];
6926                 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6927                 fd_table[i] = bdrv_new(buf);
6928                 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6929             }
6930             if (fd_filename[i] != '\0') {
6931                 if (bdrv_open(fd_table[i], fd_filename[i],
6932                               snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
6933                     fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6934                             fd_filename[i]);
6935                     exit(1);
6936                 }
6937             }
6938         }
6939     }
6940
6941     register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6942     register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
6943
6944     init_ioports();
6945
6946     /* terminal init */
6947     if (nographic) {
6948         dumb_display_init(ds);
6949     } else if (vnc_display != -1) {
6950         vnc_display_init(ds, vnc_display);
6951     } else {
6952 #if defined(CONFIG_SDL)
6953         sdl_display_init(ds, full_screen);
6954 #elif defined(CONFIG_COCOA)
6955         cocoa_display_init(ds, full_screen);
6956 #else
6957         dumb_display_init(ds);
6958 #endif
6959     }
6960
6961     monitor_hd = qemu_chr_open(monitor_device);
6962     if (!monitor_hd) {
6963         fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6964         exit(1);
6965     }
6966     monitor_init(monitor_hd, !nographic);
6967
6968     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6969         const char *devname = serial_devices[i];
6970         if (devname[0] != '\0' && strcmp(devname, "none")) {
6971             serial_hds[i] = qemu_chr_open(devname);
6972             if (!serial_hds[i]) {
6973                 fprintf(stderr, "qemu: could not open serial device '%s'\n", 
6974                         devname);
6975                 exit(1);
6976             }
6977             if (!strcmp(devname, "vc"))
6978                 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6979         }
6980     }
6981
6982     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6983         const char *devname = parallel_devices[i];
6984         if (devname[0] != '\0' && strcmp(devname, "none")) {
6985             parallel_hds[i] = qemu_chr_open(devname);
6986             if (!parallel_hds[i]) {
6987                 fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
6988                         devname);
6989                 exit(1);
6990             }
6991             if (!strcmp(devname, "vc"))
6992                 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6993         }
6994     }
6995
6996     machine->init(ram_size, vga_ram_size, boot_device,
6997                   ds, fd_filename, snapshot,
6998                   kernel_filename, kernel_cmdline, initrd_filename);
6999
7000     /* init USB devices */
7001     if (usb_enabled) {
7002         for(i = 0; i < usb_devices_index; i++) {
7003             if (usb_device_add(usb_devices[i]) < 0) {
7004                 fprintf(stderr, "Warning: could not add USB device %s\n",
7005                         usb_devices[i]);
7006             }
7007         }
7008     }
7009
7010     gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7011     qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7012
7013 #ifdef CONFIG_GDBSTUB
7014     if (use_gdbstub) {
7015         if (gdbserver_start(gdbstub_port) < 0) {
7016             fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
7017                     gdbstub_port);
7018             exit(1);
7019         } else {
7020             printf("Waiting gdb connection on port %d\n", gdbstub_port);
7021         }
7022     } else 
7023 #endif
7024     if (loadvm)
7025         do_loadvm(loadvm);
7026
7027     {
7028         /* XXX: simplify init */
7029         read_passwords();
7030         if (start_emulation) {
7031             vm_start();
7032         }
7033     }
7034
7035     main_loop();
7036     quit_timers();
7037     return 0;
7038 }