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