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