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