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