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