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