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