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