New features for QEMU text console, 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, 0);
2927     } else if (strstart(filename, "vc:", &p)) {
2928         return text_console_init(&display_state, p);
2929     } else if (!strcmp(filename, "null")) {
2930         return qemu_chr_open_null();
2931     } else 
2932     if (strstart(filename, "tcp:", &p)) {
2933         return qemu_chr_open_tcp(p, 0, 0);
2934     } else
2935     if (strstart(filename, "telnet:", &p)) {
2936         return qemu_chr_open_tcp(p, 1, 0);
2937     } else
2938     if (strstart(filename, "udp:", &p)) {
2939         return qemu_chr_open_udp(p);
2940     } else
2941     if (strstart(filename, "mon:", &p)) {
2942         CharDriverState *drv = qemu_chr_open(p);
2943         if (drv) {
2944             drv = qemu_chr_open_mux(drv);
2945             monitor_init(drv, !nographic);
2946             return drv;
2947         }
2948         printf("Unable to open driver: %s\n", p);
2949         return 0;
2950     } else
2951 #ifndef _WIN32
2952     if (strstart(filename, "unix:", &p)) {
2953         return qemu_chr_open_tcp(p, 0, 1);
2954     } else if (strstart(filename, "file:", &p)) {
2955         return qemu_chr_open_file_out(p);
2956     } else if (strstart(filename, "pipe:", &p)) {
2957         return qemu_chr_open_pipe(p);
2958     } else if (!strcmp(filename, "pty")) {
2959         return qemu_chr_open_pty();
2960     } else if (!strcmp(filename, "stdio")) {
2961         return qemu_chr_open_stdio();
2962     } else 
2963 #if defined(__linux__)
2964     if (strstart(filename, "/dev/parport", NULL)) {
2965         return qemu_chr_open_pp(filename);
2966     } else 
2967 #endif
2968 #if defined(__linux__) || defined(__sun__)
2969     if (strstart(filename, "/dev/", NULL)) {
2970         return qemu_chr_open_tty(filename);
2971     } else
2972 #endif
2973 #else /* !_WIN32 */
2974     if (strstart(filename, "COM", NULL)) {
2975         return qemu_chr_open_win(filename);
2976     } else
2977     if (strstart(filename, "pipe:", &p)) {
2978         return qemu_chr_open_win_pipe(p);
2979     } else
2980     if (strstart(filename, "con:", NULL)) {
2981         return qemu_chr_open_win_con(filename);
2982     } else
2983     if (strstart(filename, "file:", &p)) {
2984         return qemu_chr_open_win_file_out(p);
2985     }
2986 #endif
2987     {
2988         return NULL;
2989     }
2990 }
2991
2992 void qemu_chr_close(CharDriverState *chr)
2993 {
2994     if (chr->chr_close)
2995         chr->chr_close(chr);
2996 }
2997
2998 /***********************************************************/
2999 /* network device redirectors */
3000
3001 void hex_dump(FILE *f, const uint8_t *buf, int size)
3002 {
3003     int len, i, j, c;
3004
3005     for(i=0;i<size;i+=16) {
3006         len = size - i;
3007         if (len > 16)
3008             len = 16;
3009         fprintf(f, "%08x ", i);
3010         for(j=0;j<16;j++) {
3011             if (j < len)
3012                 fprintf(f, " %02x", buf[i+j]);
3013             else
3014                 fprintf(f, "   ");
3015         }
3016         fprintf(f, " ");
3017         for(j=0;j<len;j++) {
3018             c = buf[i+j];
3019             if (c < ' ' || c > '~')
3020                 c = '.';
3021             fprintf(f, "%c", c);
3022         }
3023         fprintf(f, "\n");
3024     }
3025 }
3026
3027 static int parse_macaddr(uint8_t *macaddr, const char *p)
3028 {
3029     int i;
3030     for(i = 0; i < 6; i++) {
3031         macaddr[i] = strtol(p, (char **)&p, 16);
3032         if (i == 5) {
3033             if (*p != '\0') 
3034                 return -1;
3035         } else {
3036             if (*p != ':') 
3037                 return -1;
3038             p++;
3039         }
3040     }
3041     return 0;
3042 }
3043
3044 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3045 {
3046     const char *p, *p1;
3047     int len;
3048     p = *pp;
3049     p1 = strchr(p, sep);
3050     if (!p1)
3051         return -1;
3052     len = p1 - p;
3053     p1++;
3054     if (buf_size > 0) {
3055         if (len > buf_size - 1)
3056             len = buf_size - 1;
3057         memcpy(buf, p, len);
3058         buf[len] = '\0';
3059     }
3060     *pp = p1;
3061     return 0;
3062 }
3063
3064 int parse_host_src_port(struct sockaddr_in *haddr,
3065                         struct sockaddr_in *saddr,
3066                         const char *input_str)
3067 {
3068     char *str = strdup(input_str);
3069     char *host_str = str;
3070     char *src_str;
3071     char *ptr;
3072
3073     /*
3074      * Chop off any extra arguments at the end of the string which
3075      * would start with a comma, then fill in the src port information
3076      * if it was provided else use the "any address" and "any port".
3077      */
3078     if ((ptr = strchr(str,',')))
3079         *ptr = '\0';
3080
3081     if ((src_str = strchr(input_str,'@'))) {
3082         *src_str = '\0';
3083         src_str++;
3084     }
3085
3086     if (parse_host_port(haddr, host_str) < 0)
3087         goto fail;
3088
3089     if (!src_str || *src_str == '\0')
3090         src_str = ":0";
3091
3092     if (parse_host_port(saddr, src_str) < 0)
3093         goto fail;
3094
3095     free(str);
3096     return(0);
3097
3098 fail:
3099     free(str);
3100     return -1;
3101 }
3102
3103 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3104 {
3105     char buf[512];
3106     struct hostent *he;
3107     const char *p, *r;
3108     int port;
3109
3110     p = str;
3111     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3112         return -1;
3113     saddr->sin_family = AF_INET;
3114     if (buf[0] == '\0') {
3115         saddr->sin_addr.s_addr = 0;
3116     } else {
3117         if (isdigit(buf[0])) {
3118             if (!inet_aton(buf, &saddr->sin_addr))
3119                 return -1;
3120         } else {
3121             if ((he = gethostbyname(buf)) == NULL)
3122                 return - 1;
3123             saddr->sin_addr = *(struct in_addr *)he->h_addr;
3124         }
3125     }
3126     port = strtol(p, (char **)&r, 0);
3127     if (r == p)
3128         return -1;
3129     saddr->sin_port = htons(port);
3130     return 0;
3131 }
3132
3133 #ifndef _WIN32
3134 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3135 {
3136     const char *p;
3137     int len;
3138
3139     len = MIN(108, strlen(str));
3140     p = strchr(str, ',');
3141     if (p)
3142         len = MIN(len, p - str);
3143
3144     memset(uaddr, 0, sizeof(*uaddr));
3145
3146     uaddr->sun_family = AF_UNIX;
3147     memcpy(uaddr->sun_path, str, len);
3148
3149     return 0;
3150 }
3151 #endif
3152
3153 /* find or alloc a new VLAN */
3154 VLANState *qemu_find_vlan(int id)
3155 {
3156     VLANState **pvlan, *vlan;
3157     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3158         if (vlan->id == id)
3159             return vlan;
3160     }
3161     vlan = qemu_mallocz(sizeof(VLANState));
3162     if (!vlan)
3163         return NULL;
3164     vlan->id = id;
3165     vlan->next = NULL;
3166     pvlan = &first_vlan;
3167     while (*pvlan != NULL)
3168         pvlan = &(*pvlan)->next;
3169     *pvlan = vlan;
3170     return vlan;
3171 }
3172
3173 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3174                                       IOReadHandler *fd_read,
3175                                       IOCanRWHandler *fd_can_read,
3176                                       void *opaque)
3177 {
3178     VLANClientState *vc, **pvc;
3179     vc = qemu_mallocz(sizeof(VLANClientState));
3180     if (!vc)
3181         return NULL;
3182     vc->fd_read = fd_read;
3183     vc->fd_can_read = fd_can_read;
3184     vc->opaque = opaque;
3185     vc->vlan = vlan;
3186
3187     vc->next = NULL;
3188     pvc = &vlan->first_client;
3189     while (*pvc != NULL)
3190         pvc = &(*pvc)->next;
3191     *pvc = vc;
3192     return vc;
3193 }
3194
3195 int qemu_can_send_packet(VLANClientState *vc1)
3196 {
3197     VLANState *vlan = vc1->vlan;
3198     VLANClientState *vc;
3199
3200     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3201         if (vc != vc1) {
3202             if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3203                 return 1;
3204         }
3205     }
3206     return 0;
3207 }
3208
3209 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3210 {
3211     VLANState *vlan = vc1->vlan;
3212     VLANClientState *vc;
3213
3214 #if 0
3215     printf("vlan %d send:\n", vlan->id);
3216     hex_dump(stdout, buf, size);
3217 #endif
3218     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3219         if (vc != vc1) {
3220             vc->fd_read(vc->opaque, buf, size);
3221         }
3222     }
3223 }
3224
3225 #if defined(CONFIG_SLIRP)
3226
3227 /* slirp network adapter */
3228
3229 static int slirp_inited;
3230 static VLANClientState *slirp_vc;
3231
3232 int slirp_can_output(void)
3233 {
3234     return !slirp_vc || qemu_can_send_packet(slirp_vc);
3235 }
3236
3237 void slirp_output(const uint8_t *pkt, int pkt_len)
3238 {
3239 #if 0
3240     printf("slirp output:\n");
3241     hex_dump(stdout, pkt, pkt_len);
3242 #endif
3243     if (!slirp_vc)
3244         return;
3245     qemu_send_packet(slirp_vc, pkt, pkt_len);
3246 }
3247
3248 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3249 {
3250 #if 0
3251     printf("slirp input:\n");
3252     hex_dump(stdout, buf, size);
3253 #endif
3254     slirp_input(buf, size);
3255 }
3256
3257 static int net_slirp_init(VLANState *vlan)
3258 {
3259     if (!slirp_inited) {
3260         slirp_inited = 1;
3261         slirp_init();
3262     }
3263     slirp_vc = qemu_new_vlan_client(vlan, 
3264                                     slirp_receive, NULL, NULL);
3265     snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3266     return 0;
3267 }
3268
3269 static void net_slirp_redir(const char *redir_str)
3270 {
3271     int is_udp;
3272     char buf[256], *r;
3273     const char *p;
3274     struct in_addr guest_addr;
3275     int host_port, guest_port;
3276     
3277     if (!slirp_inited) {
3278         slirp_inited = 1;
3279         slirp_init();
3280     }
3281
3282     p = redir_str;
3283     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3284         goto fail;
3285     if (!strcmp(buf, "tcp")) {
3286         is_udp = 0;
3287     } else if (!strcmp(buf, "udp")) {
3288         is_udp = 1;
3289     } else {
3290         goto fail;
3291     }
3292
3293     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3294         goto fail;
3295     host_port = strtol(buf, &r, 0);
3296     if (r == buf)
3297         goto fail;
3298
3299     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3300         goto fail;
3301     if (buf[0] == '\0') {
3302         pstrcpy(buf, sizeof(buf), "10.0.2.15");
3303     }
3304     if (!inet_aton(buf, &guest_addr))
3305         goto fail;
3306     
3307     guest_port = strtol(p, &r, 0);
3308     if (r == p)
3309         goto fail;
3310     
3311     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3312         fprintf(stderr, "qemu: could not set up redirection\n");
3313         exit(1);
3314     }
3315     return;
3316  fail:
3317     fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3318     exit(1);
3319 }
3320     
3321 #ifndef _WIN32
3322
3323 char smb_dir[1024];
3324
3325 static void smb_exit(void)
3326 {
3327     DIR *d;
3328     struct dirent *de;
3329     char filename[1024];
3330
3331     /* erase all the files in the directory */
3332     d = opendir(smb_dir);
3333     for(;;) {
3334         de = readdir(d);
3335         if (!de)
3336             break;
3337         if (strcmp(de->d_name, ".") != 0 &&
3338             strcmp(de->d_name, "..") != 0) {
3339             snprintf(filename, sizeof(filename), "%s/%s", 
3340                      smb_dir, de->d_name);
3341             unlink(filename);
3342         }
3343     }
3344     closedir(d);
3345     rmdir(smb_dir);
3346 }
3347
3348 /* automatic user mode samba server configuration */
3349 void net_slirp_smb(const char *exported_dir)
3350 {
3351     char smb_conf[1024];
3352     char smb_cmdline[1024];
3353     FILE *f;
3354
3355     if (!slirp_inited) {
3356         slirp_inited = 1;
3357         slirp_init();
3358     }
3359
3360     /* XXX: better tmp dir construction */
3361     snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3362     if (mkdir(smb_dir, 0700) < 0) {
3363         fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3364         exit(1);
3365     }
3366     snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3367     
3368     f = fopen(smb_conf, "w");
3369     if (!f) {
3370         fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3371         exit(1);
3372     }
3373     fprintf(f, 
3374             "[global]\n"
3375             "private dir=%s\n"
3376             "smb ports=0\n"
3377             "socket address=127.0.0.1\n"
3378             "pid directory=%s\n"
3379             "lock directory=%s\n"
3380             "log file=%s/log.smbd\n"
3381             "smb passwd file=%s/smbpasswd\n"
3382             "security = share\n"
3383             "[qemu]\n"
3384             "path=%s\n"
3385             "read only=no\n"
3386             "guest ok=yes\n",
3387             smb_dir,
3388             smb_dir,
3389             smb_dir,
3390             smb_dir,
3391             smb_dir,
3392             exported_dir
3393             );
3394     fclose(f);
3395     atexit(smb_exit);
3396
3397     snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3398              SMBD_COMMAND, smb_conf);
3399     
3400     slirp_add_exec(0, smb_cmdline, 4, 139);
3401 }
3402
3403 #endif /* !defined(_WIN32) */
3404
3405 #endif /* CONFIG_SLIRP */
3406
3407 #if !defined(_WIN32)
3408
3409 typedef struct TAPState {
3410     VLANClientState *vc;
3411     int fd;
3412 } TAPState;
3413
3414 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3415 {
3416     TAPState *s = opaque;
3417     int ret;
3418     for(;;) {
3419         ret = write(s->fd, buf, size);
3420         if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3421         } else {
3422             break;
3423         }
3424     }
3425 }
3426
3427 static void tap_send(void *opaque)
3428 {
3429     TAPState *s = opaque;
3430     uint8_t buf[4096];
3431     int size;
3432
3433 #ifdef __sun__
3434     struct strbuf sbuf;
3435     int f = 0;
3436     sbuf.maxlen = sizeof(buf);
3437     sbuf.buf = buf;
3438     size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3439 #else
3440     size = read(s->fd, buf, sizeof(buf));
3441 #endif
3442     if (size > 0) {
3443         qemu_send_packet(s->vc, buf, size);
3444     }
3445 }
3446
3447 /* fd support */
3448
3449 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3450 {
3451     TAPState *s;
3452
3453     s = qemu_mallocz(sizeof(TAPState));
3454     if (!s)
3455         return NULL;
3456     s->fd = fd;
3457     s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3458     qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3459     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3460     return s;
3461 }
3462
3463 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3464 static int tap_open(char *ifname, int ifname_size)
3465 {
3466     int fd;
3467     char *dev;
3468     struct stat s;
3469
3470     TFR(fd = open("/dev/tap", O_RDWR));
3471     if (fd < 0) {
3472         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3473         return -1;
3474     }
3475
3476     fstat(fd, &s);
3477     dev = devname(s.st_rdev, S_IFCHR);
3478     pstrcpy(ifname, ifname_size, dev);
3479
3480     fcntl(fd, F_SETFL, O_NONBLOCK);
3481     return fd;
3482 }
3483 #elif defined(__sun__)
3484 #define TUNNEWPPA       (('T'<<16) | 0x0001)
3485 /* 
3486  * Allocate TAP device, returns opened fd. 
3487  * Stores dev name in the first arg(must be large enough).
3488  */  
3489 int tap_alloc(char *dev)
3490 {
3491     int tap_fd, if_fd, ppa = -1;
3492     static int ip_fd = 0;
3493     char *ptr;
3494
3495     static int arp_fd = 0;
3496     int ip_muxid, arp_muxid;
3497     struct strioctl  strioc_if, strioc_ppa;
3498     int link_type = I_PLINK;;
3499     struct lifreq ifr;
3500     char actual_name[32] = "";
3501
3502     memset(&ifr, 0x0, sizeof(ifr));
3503
3504     if( *dev ){
3505        ptr = dev;       
3506        while( *ptr && !isdigit((int)*ptr) ) ptr++; 
3507        ppa = atoi(ptr);
3508     }
3509
3510     /* Check if IP device was opened */
3511     if( ip_fd )
3512        close(ip_fd);
3513
3514     TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3515     if (ip_fd < 0) {
3516        syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3517        return -1;
3518     }
3519
3520     TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3521     if (tap_fd < 0) {
3522        syslog(LOG_ERR, "Can't open /dev/tap");
3523        return -1;
3524     }
3525
3526     /* Assign a new PPA and get its unit number. */
3527     strioc_ppa.ic_cmd = TUNNEWPPA;
3528     strioc_ppa.ic_timout = 0;
3529     strioc_ppa.ic_len = sizeof(ppa);
3530     strioc_ppa.ic_dp = (char *)&ppa;
3531     if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3532        syslog (LOG_ERR, "Can't assign new interface");
3533
3534     TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3535     if (if_fd < 0) {
3536        syslog(LOG_ERR, "Can't open /dev/tap (2)");
3537        return -1;
3538     }
3539     if(ioctl(if_fd, I_PUSH, "ip") < 0){
3540        syslog(LOG_ERR, "Can't push IP module");
3541        return -1;
3542     }
3543
3544     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3545         syslog(LOG_ERR, "Can't get flags\n");
3546
3547     snprintf (actual_name, 32, "tap%d", ppa);
3548     strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3549
3550     ifr.lifr_ppa = ppa;
3551     /* Assign ppa according to the unit number returned by tun device */
3552
3553     if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3554         syslog (LOG_ERR, "Can't set PPA %d", ppa);
3555     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3556         syslog (LOG_ERR, "Can't get flags\n");
3557     /* Push arp module to if_fd */
3558     if (ioctl (if_fd, I_PUSH, "arp") < 0)
3559         syslog (LOG_ERR, "Can't push ARP module (2)");
3560
3561     /* Push arp module to ip_fd */
3562     if (ioctl (ip_fd, I_POP, NULL) < 0)
3563         syslog (LOG_ERR, "I_POP failed\n");
3564     if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3565         syslog (LOG_ERR, "Can't push ARP module (3)\n");
3566     /* Open arp_fd */
3567     TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3568     if (arp_fd < 0)
3569        syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3570
3571     /* Set ifname to arp */
3572     strioc_if.ic_cmd = SIOCSLIFNAME;
3573     strioc_if.ic_timout = 0;
3574     strioc_if.ic_len = sizeof(ifr);
3575     strioc_if.ic_dp = (char *)&ifr;
3576     if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3577         syslog (LOG_ERR, "Can't set ifname to arp\n");
3578     }
3579
3580     if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3581        syslog(LOG_ERR, "Can't link TAP device to IP");
3582        return -1;
3583     }
3584
3585     if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3586         syslog (LOG_ERR, "Can't link TAP device to ARP");
3587
3588     close (if_fd);
3589
3590     memset(&ifr, 0x0, sizeof(ifr));
3591     strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3592     ifr.lifr_ip_muxid  = ip_muxid;
3593     ifr.lifr_arp_muxid = arp_muxid;
3594
3595     if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3596     {
3597       ioctl (ip_fd, I_PUNLINK , arp_muxid);
3598       ioctl (ip_fd, I_PUNLINK, ip_muxid);
3599       syslog (LOG_ERR, "Can't set multiplexor id");
3600     }
3601
3602     sprintf(dev, "tap%d", ppa);
3603     return tap_fd;
3604 }
3605
3606 static int tap_open(char *ifname, int ifname_size)
3607 {
3608     char  dev[10]="";
3609     int fd;
3610     if( (fd = tap_alloc(dev)) < 0 ){
3611        fprintf(stderr, "Cannot allocate TAP device\n");
3612        return -1;
3613     }
3614     pstrcpy(ifname, ifname_size, dev);
3615     fcntl(fd, F_SETFL, O_NONBLOCK);
3616     return fd;
3617 }
3618 #else
3619 static int tap_open(char *ifname, int ifname_size)
3620 {
3621     struct ifreq ifr;
3622     int fd, ret;
3623     
3624     TFR(fd = open("/dev/net/tun", O_RDWR));
3625     if (fd < 0) {
3626         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3627         return -1;
3628     }
3629     memset(&ifr, 0, sizeof(ifr));
3630     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3631     if (ifname[0] != '\0')
3632         pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3633     else
3634         pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3635     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3636     if (ret != 0) {
3637         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3638         close(fd);
3639         return -1;
3640     }
3641     pstrcpy(ifname, ifname_size, ifr.ifr_name);
3642     fcntl(fd, F_SETFL, O_NONBLOCK);
3643     return fd;
3644 }
3645 #endif
3646
3647 static int net_tap_init(VLANState *vlan, const char *ifname1,
3648                         const char *setup_script)
3649 {
3650     TAPState *s;
3651     int pid, status, fd;
3652     char *args[3];
3653     char **parg;
3654     char ifname[128];
3655
3656     if (ifname1 != NULL)
3657         pstrcpy(ifname, sizeof(ifname), ifname1);
3658     else
3659         ifname[0] = '\0';
3660     TFR(fd = tap_open(ifname, sizeof(ifname)));
3661     if (fd < 0)
3662         return -1;
3663
3664     if (!setup_script || !strcmp(setup_script, "no"))
3665         setup_script = "";
3666     if (setup_script[0] != '\0') {
3667         /* try to launch network init script */
3668         pid = fork();
3669         if (pid >= 0) {
3670             if (pid == 0) {
3671                 int open_max = sysconf (_SC_OPEN_MAX), i;
3672                 for (i = 0; i < open_max; i++)
3673                     if (i != STDIN_FILENO &&
3674                         i != STDOUT_FILENO &&
3675                         i != STDERR_FILENO &&
3676                         i != fd)
3677                         close(i);
3678
3679                 parg = args;
3680                 *parg++ = (char *)setup_script;
3681                 *parg++ = ifname;
3682                 *parg++ = NULL;
3683                 execv(setup_script, args);
3684                 _exit(1);
3685             }
3686             while (waitpid(pid, &status, 0) != pid);
3687             if (!WIFEXITED(status) ||
3688                 WEXITSTATUS(status) != 0) {
3689                 fprintf(stderr, "%s: could not launch network script\n",
3690                         setup_script);
3691                 return -1;
3692             }
3693         }
3694     }
3695     s = net_tap_fd_init(vlan, fd);
3696     if (!s)
3697         return -1;
3698     snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3699              "tap: ifname=%s setup_script=%s", ifname, setup_script);
3700     return 0;
3701 }
3702
3703 #endif /* !_WIN32 */
3704
3705 /* network connection */
3706 typedef struct NetSocketState {
3707     VLANClientState *vc;
3708     int fd;
3709     int state; /* 0 = getting length, 1 = getting data */
3710     int index;
3711     int packet_len;
3712     uint8_t buf[4096];
3713     struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3714 } NetSocketState;
3715
3716 typedef struct NetSocketListenState {
3717     VLANState *vlan;
3718     int fd;
3719 } NetSocketListenState;
3720
3721 /* XXX: we consider we can send the whole packet without blocking */
3722 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3723 {
3724     NetSocketState *s = opaque;
3725     uint32_t len;
3726     len = htonl(size);
3727
3728     send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3729     send_all(s->fd, buf, size);
3730 }
3731
3732 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3733 {
3734     NetSocketState *s = opaque;
3735     sendto(s->fd, buf, size, 0, 
3736            (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3737 }
3738
3739 static void net_socket_send(void *opaque)
3740 {
3741     NetSocketState *s = opaque;
3742     int l, size, err;
3743     uint8_t buf1[4096];
3744     const uint8_t *buf;
3745
3746     size = recv(s->fd, buf1, sizeof(buf1), 0);
3747     if (size < 0) {
3748         err = socket_error();
3749         if (err != EWOULDBLOCK) 
3750             goto eoc;
3751     } else if (size == 0) {
3752         /* end of connection */
3753     eoc:
3754         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3755         closesocket(s->fd);
3756         return;
3757     }
3758     buf = buf1;
3759     while (size > 0) {
3760         /* reassemble a packet from the network */
3761         switch(s->state) {
3762         case 0:
3763             l = 4 - s->index;
3764             if (l > size)
3765                 l = size;
3766             memcpy(s->buf + s->index, buf, l);
3767             buf += l;
3768             size -= l;
3769             s->index += l;
3770             if (s->index == 4) {
3771                 /* got length */
3772                 s->packet_len = ntohl(*(uint32_t *)s->buf);
3773                 s->index = 0;
3774                 s->state = 1;
3775             }
3776             break;
3777         case 1:
3778             l = s->packet_len - s->index;
3779             if (l > size)
3780                 l = size;
3781             memcpy(s->buf + s->index, buf, l);
3782             s->index += l;
3783             buf += l;
3784             size -= l;
3785             if (s->index >= s->packet_len) {
3786                 qemu_send_packet(s->vc, s->buf, s->packet_len);
3787                 s->index = 0;
3788                 s->state = 0;
3789             }
3790             break;
3791         }
3792     }
3793 }
3794
3795 static void net_socket_send_dgram(void *opaque)
3796 {
3797     NetSocketState *s = opaque;
3798     int size;
3799
3800     size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3801     if (size < 0) 
3802         return;
3803     if (size == 0) {
3804         /* end of connection */
3805         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3806         return;
3807     }
3808     qemu_send_packet(s->vc, s->buf, size);
3809 }
3810
3811 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3812 {
3813     struct ip_mreq imr;
3814     int fd;
3815     int val, ret;
3816     if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3817         fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3818                 inet_ntoa(mcastaddr->sin_addr), 
3819                 (int)ntohl(mcastaddr->sin_addr.s_addr));
3820         return -1;
3821
3822     }
3823     fd = socket(PF_INET, SOCK_DGRAM, 0);
3824     if (fd < 0) {
3825         perror("socket(PF_INET, SOCK_DGRAM)");
3826         return -1;
3827     }
3828
3829     val = 1;
3830     ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3831                    (const char *)&val, sizeof(val));
3832     if (ret < 0) {
3833         perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3834         goto fail;
3835     }
3836
3837     ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3838     if (ret < 0) {
3839         perror("bind");
3840         goto fail;
3841     }
3842     
3843     /* Add host to multicast group */
3844     imr.imr_multiaddr = mcastaddr->sin_addr;
3845     imr.imr_interface.s_addr = htonl(INADDR_ANY);
3846
3847     ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3848                      (const char *)&imr, sizeof(struct ip_mreq));
3849     if (ret < 0) {
3850         perror("setsockopt(IP_ADD_MEMBERSHIP)");
3851         goto fail;
3852     }
3853
3854     /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3855     val = 1;
3856     ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3857                    (const char *)&val, sizeof(val));
3858     if (ret < 0) {
3859         perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3860         goto fail;
3861     }
3862
3863     socket_set_nonblock(fd);
3864     return fd;
3865 fail:
3866     if (fd >= 0) 
3867         closesocket(fd);
3868     return -1;
3869 }
3870
3871 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3872                                           int is_connected)
3873 {
3874     struct sockaddr_in saddr;
3875     int newfd;
3876     socklen_t saddr_len;
3877     NetSocketState *s;
3878
3879     /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3880      * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3881      * by ONLY ONE process: we must "clone" this dgram socket --jjo
3882      */
3883
3884     if (is_connected) {
3885         if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3886             /* must be bound */
3887             if (saddr.sin_addr.s_addr==0) {
3888                 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3889                         fd);
3890                 return NULL;
3891             }
3892             /* clone dgram socket */
3893             newfd = net_socket_mcast_create(&saddr);
3894             if (newfd < 0) {
3895                 /* error already reported by net_socket_mcast_create() */
3896                 close(fd);
3897                 return NULL;
3898             }
3899             /* clone newfd to fd, close newfd */
3900             dup2(newfd, fd);
3901             close(newfd);
3902         
3903         } else {
3904             fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3905                     fd, strerror(errno));
3906             return NULL;
3907         }
3908     }
3909
3910     s = qemu_mallocz(sizeof(NetSocketState));
3911     if (!s)
3912         return NULL;
3913     s->fd = fd;
3914
3915     s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3916     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3917
3918     /* mcast: save bound address as dst */
3919     if (is_connected) s->dgram_dst=saddr;
3920
3921     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3922             "socket: fd=%d (%s mcast=%s:%d)", 
3923             fd, is_connected? "cloned" : "",
3924             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3925     return s;
3926 }
3927
3928 static void net_socket_connect(void *opaque)
3929 {
3930     NetSocketState *s = opaque;
3931     qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3932 }
3933
3934 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3935                                           int is_connected)
3936 {
3937     NetSocketState *s;
3938     s = qemu_mallocz(sizeof(NetSocketState));
3939     if (!s)
3940         return NULL;
3941     s->fd = fd;
3942     s->vc = qemu_new_vlan_client(vlan, 
3943                                  net_socket_receive, NULL, s);
3944     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3945              "socket: fd=%d", fd);
3946     if (is_connected) {
3947         net_socket_connect(s);
3948     } else {
3949         qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3950     }
3951     return s;
3952 }
3953
3954 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3955                                           int is_connected)
3956 {
3957     int so_type=-1, optlen=sizeof(so_type);
3958
3959     if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3960         fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3961         return NULL;
3962     }
3963     switch(so_type) {
3964     case SOCK_DGRAM:
3965         return net_socket_fd_init_dgram(vlan, fd, is_connected);
3966     case SOCK_STREAM:
3967         return net_socket_fd_init_stream(vlan, fd, is_connected);
3968     default:
3969         /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3970         fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3971         return net_socket_fd_init_stream(vlan, fd, is_connected);
3972     }
3973     return NULL;
3974 }
3975
3976 static void net_socket_accept(void *opaque)
3977 {
3978     NetSocketListenState *s = opaque;    
3979     NetSocketState *s1;
3980     struct sockaddr_in saddr;
3981     socklen_t len;
3982     int fd;
3983
3984     for(;;) {
3985         len = sizeof(saddr);
3986         fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3987         if (fd < 0 && errno != EINTR) {
3988             return;
3989         } else if (fd >= 0) {
3990             break;
3991         }
3992     }
3993     s1 = net_socket_fd_init(s->vlan, fd, 1); 
3994     if (!s1) {
3995         closesocket(fd);
3996     } else {
3997         snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3998                  "socket: connection from %s:%d", 
3999                  inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4000     }
4001 }
4002
4003 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4004 {
4005     NetSocketListenState *s;
4006     int fd, val, ret;
4007     struct sockaddr_in saddr;
4008
4009     if (parse_host_port(&saddr, host_str) < 0)
4010         return -1;
4011     
4012     s = qemu_mallocz(sizeof(NetSocketListenState));
4013     if (!s)
4014         return -1;
4015
4016     fd = socket(PF_INET, SOCK_STREAM, 0);
4017     if (fd < 0) {
4018         perror("socket");
4019         return -1;
4020     }
4021     socket_set_nonblock(fd);
4022
4023     /* allow fast reuse */
4024     val = 1;
4025     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4026     
4027     ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4028     if (ret < 0) {
4029         perror("bind");
4030         return -1;
4031     }
4032     ret = listen(fd, 0);
4033     if (ret < 0) {
4034         perror("listen");
4035         return -1;
4036     }
4037     s->vlan = vlan;
4038     s->fd = fd;
4039     qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4040     return 0;
4041 }
4042
4043 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4044 {
4045     NetSocketState *s;
4046     int fd, connected, ret, err;
4047     struct sockaddr_in saddr;
4048
4049     if (parse_host_port(&saddr, host_str) < 0)
4050         return -1;
4051
4052     fd = socket(PF_INET, SOCK_STREAM, 0);
4053     if (fd < 0) {
4054         perror("socket");
4055         return -1;
4056     }
4057     socket_set_nonblock(fd);
4058
4059     connected = 0;
4060     for(;;) {
4061         ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4062         if (ret < 0) {
4063             err = socket_error();
4064             if (err == EINTR || err == EWOULDBLOCK) {
4065             } else if (err == EINPROGRESS) {
4066                 break;
4067 #ifdef _WIN32
4068             } else if (err == WSAEALREADY) {
4069                 break;
4070 #endif
4071             } else {
4072                 perror("connect");
4073                 closesocket(fd);
4074                 return -1;
4075             }
4076         } else {
4077             connected = 1;
4078             break;
4079         }
4080     }
4081     s = net_socket_fd_init(vlan, fd, connected);
4082     if (!s)
4083         return -1;
4084     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4085              "socket: connect to %s:%d", 
4086              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4087     return 0;
4088 }
4089
4090 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4091 {
4092     NetSocketState *s;
4093     int fd;
4094     struct sockaddr_in saddr;
4095
4096     if (parse_host_port(&saddr, host_str) < 0)
4097         return -1;
4098
4099
4100     fd = net_socket_mcast_create(&saddr);
4101     if (fd < 0)
4102         return -1;
4103
4104     s = net_socket_fd_init(vlan, fd, 0);
4105     if (!s)
4106         return -1;
4107
4108     s->dgram_dst = saddr;
4109     
4110     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4111              "socket: mcast=%s:%d", 
4112              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4113     return 0;
4114
4115 }
4116
4117 static int get_param_value(char *buf, int buf_size,
4118                            const char *tag, const char *str)
4119 {
4120     const char *p;
4121     char *q;
4122     char option[128];
4123
4124     p = str;
4125     for(;;) {
4126         q = option;
4127         while (*p != '\0' && *p != '=') {
4128             if ((q - option) < sizeof(option) - 1)
4129                 *q++ = *p;
4130             p++;
4131         }
4132         *q = '\0';
4133         if (*p != '=')
4134             break;
4135         p++;
4136         if (!strcmp(tag, option)) {
4137             q = buf;
4138             while (*p != '\0' && *p != ',') {
4139                 if ((q - buf) < buf_size - 1)
4140                     *q++ = *p;
4141                 p++;
4142             }
4143             *q = '\0';
4144             return q - buf;
4145         } else {
4146             while (*p != '\0' && *p != ',') {
4147                 p++;
4148             }
4149         }
4150         if (*p != ',')
4151             break;
4152         p++;
4153     }
4154     return 0;
4155 }
4156
4157 static int net_client_init(const char *str)
4158 {
4159     const char *p;
4160     char *q;
4161     char device[64];
4162     char buf[1024];
4163     int vlan_id, ret;
4164     VLANState *vlan;
4165
4166     p = str;
4167     q = device;
4168     while (*p != '\0' && *p != ',') {
4169         if ((q - device) < sizeof(device) - 1)
4170             *q++ = *p;
4171         p++;
4172     }
4173     *q = '\0';
4174     if (*p == ',')
4175         p++;
4176     vlan_id = 0;
4177     if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4178         vlan_id = strtol(buf, NULL, 0);
4179     }
4180     vlan = qemu_find_vlan(vlan_id);
4181     if (!vlan) {
4182         fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4183         return -1;
4184     }
4185     if (!strcmp(device, "nic")) {
4186         NICInfo *nd;
4187         uint8_t *macaddr;
4188
4189         if (nb_nics >= MAX_NICS) {
4190             fprintf(stderr, "Too Many NICs\n");
4191             return -1;
4192         }
4193         nd = &nd_table[nb_nics];
4194         macaddr = nd->macaddr;
4195         macaddr[0] = 0x52;
4196         macaddr[1] = 0x54;
4197         macaddr[2] = 0x00;
4198         macaddr[3] = 0x12;
4199         macaddr[4] = 0x34;
4200         macaddr[5] = 0x56 + nb_nics;
4201
4202         if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4203             if (parse_macaddr(macaddr, buf) < 0) {
4204                 fprintf(stderr, "invalid syntax for ethernet address\n");
4205                 return -1;
4206             }
4207         }
4208         if (get_param_value(buf, sizeof(buf), "model", p)) {
4209             nd->model = strdup(buf);
4210         }
4211         nd->vlan = vlan;
4212         nb_nics++;
4213         vlan->nb_guest_devs++;
4214         ret = 0;
4215     } else
4216     if (!strcmp(device, "none")) {
4217         /* does nothing. It is needed to signal that no network cards
4218            are wanted */
4219         ret = 0;
4220     } else
4221 #ifdef CONFIG_SLIRP
4222     if (!strcmp(device, "user")) {
4223         if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4224             pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4225         }
4226         vlan->nb_host_devs++;
4227         ret = net_slirp_init(vlan);
4228     } else
4229 #endif
4230 #ifdef _WIN32
4231     if (!strcmp(device, "tap")) {
4232         char ifname[64];
4233         if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4234             fprintf(stderr, "tap: no interface name\n");
4235             return -1;
4236         }
4237         vlan->nb_host_devs++;
4238         ret = tap_win32_init(vlan, ifname);
4239     } else
4240 #else
4241     if (!strcmp(device, "tap")) {
4242         char ifname[64];
4243         char setup_script[1024];
4244         int fd;
4245         vlan->nb_host_devs++;
4246         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4247             fd = strtol(buf, NULL, 0);
4248             ret = -1;
4249             if (net_tap_fd_init(vlan, fd))
4250                 ret = 0;
4251         } else {
4252             if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4253                 ifname[0] = '\0';
4254             }
4255             if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4256                 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4257             }
4258             ret = net_tap_init(vlan, ifname, setup_script);
4259         }
4260     } else
4261 #endif
4262     if (!strcmp(device, "socket")) {
4263         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4264             int fd;
4265             fd = strtol(buf, NULL, 0);
4266             ret = -1;
4267             if (net_socket_fd_init(vlan, fd, 1))
4268                 ret = 0;
4269         } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4270             ret = net_socket_listen_init(vlan, buf);
4271         } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4272             ret = net_socket_connect_init(vlan, buf);
4273         } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4274             ret = net_socket_mcast_init(vlan, buf);
4275         } else {
4276             fprintf(stderr, "Unknown socket options: %s\n", p);
4277             return -1;
4278         }
4279         vlan->nb_host_devs++;
4280     } else
4281     {
4282         fprintf(stderr, "Unknown network device: %s\n", device);
4283         return -1;
4284     }
4285     if (ret < 0) {
4286         fprintf(stderr, "Could not initialize device '%s'\n", device);
4287     }
4288     
4289     return ret;
4290 }
4291
4292 void do_info_network(void)
4293 {
4294     VLANState *vlan;
4295     VLANClientState *vc;
4296
4297     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4298         term_printf("VLAN %d devices:\n", vlan->id);
4299         for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4300             term_printf("  %s\n", vc->info_str);
4301     }
4302 }
4303
4304 /***********************************************************/
4305 /* USB devices */
4306
4307 static USBPort *used_usb_ports;
4308 static USBPort *free_usb_ports;
4309
4310 /* ??? Maybe change this to register a hub to keep track of the topology.  */
4311 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4312                             usb_attachfn attach)
4313 {
4314     port->opaque = opaque;
4315     port->index = index;
4316     port->attach = attach;
4317     port->next = free_usb_ports;
4318     free_usb_ports = port;
4319 }
4320
4321 static int usb_device_add(const char *devname)
4322 {
4323     const char *p;
4324     USBDevice *dev;
4325     USBPort *port;
4326
4327     if (!free_usb_ports)
4328         return -1;
4329
4330     if (strstart(devname, "host:", &p)) {
4331         dev = usb_host_device_open(p);
4332     } else if (!strcmp(devname, "mouse")) {
4333         dev = usb_mouse_init();
4334     } else if (!strcmp(devname, "tablet")) {
4335         dev = usb_tablet_init();
4336     } else if (!strcmp(devname, "keyboard")) {
4337         dev = usb_keyboard_init();
4338     } else if (strstart(devname, "disk:", &p)) {
4339         dev = usb_msd_init(p);
4340     } else if (!strcmp(devname, "wacom-tablet")) {
4341         dev = usb_wacom_init();
4342     } else {
4343         return -1;
4344     }
4345     if (!dev)
4346         return -1;
4347
4348     /* Find a USB port to add the device to.  */
4349     port = free_usb_ports;
4350     if (!port->next) {
4351         USBDevice *hub;
4352
4353         /* Create a new hub and chain it on.  */
4354         free_usb_ports = NULL;
4355         port->next = used_usb_ports;
4356         used_usb_ports = port;
4357
4358         hub = usb_hub_init(VM_USB_HUB_SIZE);
4359         usb_attach(port, hub);
4360         port = free_usb_ports;
4361     }
4362
4363     free_usb_ports = port->next;
4364     port->next = used_usb_ports;
4365     used_usb_ports = port;
4366     usb_attach(port, dev);
4367     return 0;
4368 }
4369
4370 static int usb_device_del(const char *devname)
4371 {
4372     USBPort *port;
4373     USBPort **lastp;
4374     USBDevice *dev;
4375     int bus_num, addr;
4376     const char *p;
4377
4378     if (!used_usb_ports)
4379         return -1;
4380
4381     p = strchr(devname, '.');
4382     if (!p) 
4383         return -1;
4384     bus_num = strtoul(devname, NULL, 0);
4385     addr = strtoul(p + 1, NULL, 0);
4386     if (bus_num != 0)
4387         return -1;
4388
4389     lastp = &used_usb_ports;
4390     port = used_usb_ports;
4391     while (port && port->dev->addr != addr) {
4392         lastp = &port->next;
4393         port = port->next;
4394     }
4395
4396     if (!port)
4397         return -1;
4398
4399     dev = port->dev;
4400     *lastp = port->next;
4401     usb_attach(port, NULL);
4402     dev->handle_destroy(dev);
4403     port->next = free_usb_ports;
4404     free_usb_ports = port;
4405     return 0;
4406 }
4407
4408 void do_usb_add(const char *devname)
4409 {
4410     int ret;
4411     ret = usb_device_add(devname);
4412     if (ret < 0) 
4413         term_printf("Could not add USB device '%s'\n", devname);
4414 }
4415
4416 void do_usb_del(const char *devname)
4417 {
4418     int ret;
4419     ret = usb_device_del(devname);
4420     if (ret < 0) 
4421         term_printf("Could not remove USB device '%s'\n", devname);
4422 }
4423
4424 void usb_info(void)
4425 {
4426     USBDevice *dev;
4427     USBPort *port;
4428     const char *speed_str;
4429
4430     if (!usb_enabled) {
4431         term_printf("USB support not enabled\n");
4432         return;
4433     }
4434
4435     for (port = used_usb_ports; port; port = port->next) {
4436         dev = port->dev;
4437         if (!dev)
4438             continue;
4439         switch(dev->speed) {
4440         case USB_SPEED_LOW: 
4441             speed_str = "1.5"; 
4442             break;
4443         case USB_SPEED_FULL: 
4444             speed_str = "12"; 
4445             break;
4446         case USB_SPEED_HIGH: 
4447             speed_str = "480"; 
4448             break;
4449         default:
4450             speed_str = "?"; 
4451             break;
4452         }
4453         term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
4454                     0, dev->addr, speed_str, dev->devname);
4455     }
4456 }
4457
4458 /***********************************************************/
4459 /* PCMCIA/Cardbus */
4460
4461 static struct pcmcia_socket_entry_s {
4462     struct pcmcia_socket_s *socket;
4463     struct pcmcia_socket_entry_s *next;
4464 } *pcmcia_sockets = 0;
4465
4466 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4467 {
4468     struct pcmcia_socket_entry_s *entry;
4469
4470     entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4471     entry->socket = socket;
4472     entry->next = pcmcia_sockets;
4473     pcmcia_sockets = entry;
4474 }
4475
4476 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4477 {
4478     struct pcmcia_socket_entry_s *entry, **ptr;
4479
4480     ptr = &pcmcia_sockets;
4481     for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4482         if (entry->socket == socket) {
4483             *ptr = entry->next;
4484             qemu_free(entry);
4485         }
4486 }
4487
4488 void pcmcia_info(void)
4489 {
4490     struct pcmcia_socket_entry_s *iter;
4491     if (!pcmcia_sockets)
4492         term_printf("No PCMCIA sockets\n");
4493
4494     for (iter = pcmcia_sockets; iter; iter = iter->next)
4495         term_printf("%s: %s\n", iter->socket->slot_string,
4496                     iter->socket->attached ? iter->socket->card_string :
4497                     "Empty");
4498 }
4499
4500 /***********************************************************/
4501 /* dumb display */
4502
4503 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4504 {
4505 }
4506
4507 static void dumb_resize(DisplayState *ds, int w, int h)
4508 {
4509 }
4510
4511 static void dumb_refresh(DisplayState *ds)
4512 {
4513 #if defined(CONFIG_SDL)
4514     vga_hw_update();
4515 #endif
4516 }
4517
4518 static void dumb_display_init(DisplayState *ds)
4519 {
4520     ds->data = NULL;
4521     ds->linesize = 0;
4522     ds->depth = 0;
4523     ds->dpy_update = dumb_update;
4524     ds->dpy_resize = dumb_resize;
4525     ds->dpy_refresh = dumb_refresh;
4526 }
4527
4528 /***********************************************************/
4529 /* I/O handling */
4530
4531 #define MAX_IO_HANDLERS 64
4532
4533 typedef struct IOHandlerRecord {
4534     int fd;
4535     IOCanRWHandler *fd_read_poll;
4536     IOHandler *fd_read;
4537     IOHandler *fd_write;
4538     int deleted;
4539     void *opaque;
4540     /* temporary data */
4541     struct pollfd *ufd;
4542     struct IOHandlerRecord *next;
4543 } IOHandlerRecord;
4544
4545 static IOHandlerRecord *first_io_handler;
4546
4547 /* XXX: fd_read_poll should be suppressed, but an API change is
4548    necessary in the character devices to suppress fd_can_read(). */
4549 int qemu_set_fd_handler2(int fd, 
4550                          IOCanRWHandler *fd_read_poll, 
4551                          IOHandler *fd_read, 
4552                          IOHandler *fd_write, 
4553                          void *opaque)
4554 {
4555     IOHandlerRecord **pioh, *ioh;
4556
4557     if (!fd_read && !fd_write) {
4558         pioh = &first_io_handler;
4559         for(;;) {
4560             ioh = *pioh;
4561             if (ioh == NULL)
4562                 break;
4563             if (ioh->fd == fd) {
4564                 ioh->deleted = 1;
4565                 break;
4566             }
4567             pioh = &ioh->next;
4568         }
4569     } else {
4570         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4571             if (ioh->fd == fd)
4572                 goto found;
4573         }
4574         ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4575         if (!ioh)
4576             return -1;
4577         ioh->next = first_io_handler;
4578         first_io_handler = ioh;
4579     found:
4580         ioh->fd = fd;
4581         ioh->fd_read_poll = fd_read_poll;
4582         ioh->fd_read = fd_read;
4583         ioh->fd_write = fd_write;
4584         ioh->opaque = opaque;
4585         ioh->deleted = 0;
4586     }
4587     return 0;
4588 }
4589
4590 int qemu_set_fd_handler(int fd, 
4591                         IOHandler *fd_read, 
4592                         IOHandler *fd_write, 
4593                         void *opaque)
4594 {
4595     return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4596 }
4597
4598 /***********************************************************/
4599 /* Polling handling */
4600
4601 typedef struct PollingEntry {
4602     PollingFunc *func;
4603     void *opaque;
4604     struct PollingEntry *next;
4605 } PollingEntry;
4606
4607 static PollingEntry *first_polling_entry;
4608
4609 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4610 {
4611     PollingEntry **ppe, *pe;
4612     pe = qemu_mallocz(sizeof(PollingEntry));
4613     if (!pe)
4614         return -1;
4615     pe->func = func;
4616     pe->opaque = opaque;
4617     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4618     *ppe = pe;
4619     return 0;
4620 }
4621
4622 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4623 {
4624     PollingEntry **ppe, *pe;
4625     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4626         pe = *ppe;
4627         if (pe->func == func && pe->opaque == opaque) {
4628             *ppe = pe->next;
4629             qemu_free(pe);
4630             break;
4631         }
4632     }
4633 }
4634
4635 #ifdef _WIN32
4636 /***********************************************************/
4637 /* Wait objects support */
4638 typedef struct WaitObjects {
4639     int num;
4640     HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4641     WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4642     void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4643 } WaitObjects;
4644
4645 static WaitObjects wait_objects = {0};
4646     
4647 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4648 {
4649     WaitObjects *w = &wait_objects;
4650
4651     if (w->num >= MAXIMUM_WAIT_OBJECTS)
4652         return -1;
4653     w->events[w->num] = handle;
4654     w->func[w->num] = func;
4655     w->opaque[w->num] = opaque;
4656     w->num++;
4657     return 0;
4658 }
4659
4660 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4661 {
4662     int i, found;
4663     WaitObjects *w = &wait_objects;
4664
4665     found = 0;
4666     for (i = 0; i < w->num; i++) {
4667         if (w->events[i] == handle)
4668             found = 1;
4669         if (found) {
4670             w->events[i] = w->events[i + 1];
4671             w->func[i] = w->func[i + 1];
4672             w->opaque[i] = w->opaque[i + 1];
4673         }            
4674     }
4675     if (found)
4676         w->num--;
4677 }
4678 #endif
4679
4680 /***********************************************************/
4681 /* savevm/loadvm support */
4682
4683 #define IO_BUF_SIZE 32768
4684
4685 struct QEMUFile {
4686     FILE *outfile;
4687     BlockDriverState *bs;
4688     int is_file;
4689     int is_writable;
4690     int64_t base_offset;
4691     int64_t buf_offset; /* start of buffer when writing, end of buffer
4692                            when reading */
4693     int buf_index;
4694     int buf_size; /* 0 when writing */
4695     uint8_t buf[IO_BUF_SIZE];
4696 };
4697
4698 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4699 {
4700     QEMUFile *f;
4701
4702     f = qemu_mallocz(sizeof(QEMUFile));
4703     if (!f)
4704         return NULL;
4705     if (!strcmp(mode, "wb")) {
4706         f->is_writable = 1;
4707     } else if (!strcmp(mode, "rb")) {
4708         f->is_writable = 0;
4709     } else {
4710         goto fail;
4711     }
4712     f->outfile = fopen(filename, mode);
4713     if (!f->outfile)
4714         goto fail;
4715     f->is_file = 1;
4716     return f;
4717  fail:
4718     if (f->outfile)
4719         fclose(f->outfile);
4720     qemu_free(f);
4721     return NULL;
4722 }
4723
4724 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4725 {
4726     QEMUFile *f;
4727
4728     f = qemu_mallocz(sizeof(QEMUFile));
4729     if (!f)
4730         return NULL;
4731     f->is_file = 0;
4732     f->bs = bs;
4733     f->is_writable = is_writable;
4734     f->base_offset = offset;
4735     return f;
4736 }
4737
4738 void qemu_fflush(QEMUFile *f)
4739 {
4740     if (!f->is_writable)
4741         return;
4742     if (f->buf_index > 0) {
4743         if (f->is_file) {
4744             fseek(f->outfile, f->buf_offset, SEEK_SET);
4745             fwrite(f->buf, 1, f->buf_index, f->outfile);
4746         } else {
4747             bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4748                         f->buf, f->buf_index);
4749         }
4750         f->buf_offset += f->buf_index;
4751         f->buf_index = 0;
4752     }
4753 }
4754
4755 static void qemu_fill_buffer(QEMUFile *f)
4756 {
4757     int len;
4758
4759     if (f->is_writable)
4760         return;
4761     if (f->is_file) {
4762         fseek(f->outfile, f->buf_offset, SEEK_SET);
4763         len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4764         if (len < 0)
4765             len = 0;
4766     } else {
4767         len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4768                          f->buf, IO_BUF_SIZE);
4769         if (len < 0)
4770             len = 0;
4771     }
4772     f->buf_index = 0;
4773     f->buf_size = len;
4774     f->buf_offset += len;
4775 }
4776
4777 void qemu_fclose(QEMUFile *f)
4778 {
4779     if (f->is_writable)
4780         qemu_fflush(f);
4781     if (f->is_file) {
4782         fclose(f->outfile);
4783     }
4784     qemu_free(f);
4785 }
4786
4787 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4788 {
4789     int l;
4790     while (size > 0) {
4791         l = IO_BUF_SIZE - f->buf_index;
4792         if (l > size)
4793             l = size;
4794         memcpy(f->buf + f->buf_index, buf, l);
4795         f->buf_index += l;
4796         buf += l;
4797         size -= l;
4798         if (f->buf_index >= IO_BUF_SIZE)
4799             qemu_fflush(f);
4800     }
4801 }
4802
4803 void qemu_put_byte(QEMUFile *f, int v)
4804 {
4805     f->buf[f->buf_index++] = v;
4806     if (f->buf_index >= IO_BUF_SIZE)
4807         qemu_fflush(f);
4808 }
4809
4810 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4811 {
4812     int size, l;
4813
4814     size = size1;
4815     while (size > 0) {
4816         l = f->buf_size - f->buf_index;
4817         if (l == 0) {
4818             qemu_fill_buffer(f);
4819             l = f->buf_size - f->buf_index;
4820             if (l == 0)
4821                 break;
4822         }
4823         if (l > size)
4824             l = size;
4825         memcpy(buf, f->buf + f->buf_index, l);
4826         f->buf_index += l;
4827         buf += l;
4828         size -= l;
4829     }
4830     return size1 - size;
4831 }
4832
4833 int qemu_get_byte(QEMUFile *f)
4834 {
4835     if (f->buf_index >= f->buf_size) {
4836         qemu_fill_buffer(f);
4837         if (f->buf_index >= f->buf_size)
4838             return 0;
4839     }
4840     return f->buf[f->buf_index++];
4841 }
4842
4843 int64_t qemu_ftell(QEMUFile *f)
4844 {
4845     return f->buf_offset - f->buf_size + f->buf_index;
4846 }
4847
4848 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4849 {
4850     if (whence == SEEK_SET) {
4851         /* nothing to do */
4852     } else if (whence == SEEK_CUR) {
4853         pos += qemu_ftell(f);
4854     } else {
4855         /* SEEK_END not supported */
4856         return -1;
4857     }
4858     if (f->is_writable) {
4859         qemu_fflush(f);
4860         f->buf_offset = pos;
4861     } else {
4862         f->buf_offset = pos;
4863         f->buf_index = 0;
4864         f->buf_size = 0;
4865     }
4866     return pos;
4867 }
4868
4869 void qemu_put_be16(QEMUFile *f, unsigned int v)
4870 {
4871     qemu_put_byte(f, v >> 8);
4872     qemu_put_byte(f, v);
4873 }
4874
4875 void qemu_put_be32(QEMUFile *f, unsigned int v)
4876 {
4877     qemu_put_byte(f, v >> 24);
4878     qemu_put_byte(f, v >> 16);
4879     qemu_put_byte(f, v >> 8);
4880     qemu_put_byte(f, v);
4881 }
4882
4883 void qemu_put_be64(QEMUFile *f, uint64_t v)
4884 {
4885     qemu_put_be32(f, v >> 32);
4886     qemu_put_be32(f, v);
4887 }
4888
4889 unsigned int qemu_get_be16(QEMUFile *f)
4890 {
4891     unsigned int v;
4892     v = qemu_get_byte(f) << 8;
4893     v |= qemu_get_byte(f);
4894     return v;
4895 }
4896
4897 unsigned int qemu_get_be32(QEMUFile *f)
4898 {
4899     unsigned int v;
4900     v = qemu_get_byte(f) << 24;
4901     v |= qemu_get_byte(f) << 16;
4902     v |= qemu_get_byte(f) << 8;
4903     v |= qemu_get_byte(f);
4904     return v;
4905 }
4906
4907 uint64_t qemu_get_be64(QEMUFile *f)
4908 {
4909     uint64_t v;
4910     v = (uint64_t)qemu_get_be32(f) << 32;
4911     v |= qemu_get_be32(f);
4912     return v;
4913 }
4914
4915 typedef struct SaveStateEntry {
4916     char idstr[256];
4917     int instance_id;
4918     int version_id;
4919     SaveStateHandler *save_state;
4920     LoadStateHandler *load_state;
4921     void *opaque;
4922     struct SaveStateEntry *next;
4923 } SaveStateEntry;
4924
4925 static SaveStateEntry *first_se;
4926
4927 int register_savevm(const char *idstr, 
4928                     int instance_id, 
4929                     int version_id,
4930                     SaveStateHandler *save_state,
4931                     LoadStateHandler *load_state,
4932                     void *opaque)
4933 {
4934     SaveStateEntry *se, **pse;
4935
4936     se = qemu_malloc(sizeof(SaveStateEntry));
4937     if (!se)
4938         return -1;
4939     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4940     se->instance_id = instance_id;
4941     se->version_id = version_id;
4942     se->save_state = save_state;
4943     se->load_state = load_state;
4944     se->opaque = opaque;
4945     se->next = NULL;
4946
4947     /* add at the end of list */
4948     pse = &first_se;
4949     while (*pse != NULL)
4950         pse = &(*pse)->next;
4951     *pse = se;
4952     return 0;
4953 }
4954
4955 #define QEMU_VM_FILE_MAGIC   0x5145564d
4956 #define QEMU_VM_FILE_VERSION 0x00000002
4957
4958 int qemu_savevm_state(QEMUFile *f)
4959 {
4960     SaveStateEntry *se;
4961     int len, ret;
4962     int64_t cur_pos, len_pos, total_len_pos;
4963
4964     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4965     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4966     total_len_pos = qemu_ftell(f);
4967     qemu_put_be64(f, 0); /* total size */
4968
4969     for(se = first_se; se != NULL; se = se->next) {
4970         /* ID string */
4971         len = strlen(se->idstr);
4972         qemu_put_byte(f, len);
4973         qemu_put_buffer(f, se->idstr, len);
4974
4975         qemu_put_be32(f, se->instance_id);
4976         qemu_put_be32(f, se->version_id);
4977
4978         /* record size: filled later */
4979         len_pos = qemu_ftell(f);
4980         qemu_put_be32(f, 0);
4981         
4982         se->save_state(f, se->opaque);
4983
4984         /* fill record size */
4985         cur_pos = qemu_ftell(f);
4986         len = cur_pos - len_pos - 4;
4987         qemu_fseek(f, len_pos, SEEK_SET);
4988         qemu_put_be32(f, len);
4989         qemu_fseek(f, cur_pos, SEEK_SET);
4990     }
4991     cur_pos = qemu_ftell(f);
4992     qemu_fseek(f, total_len_pos, SEEK_SET);
4993     qemu_put_be64(f, cur_pos - total_len_pos - 8);
4994     qemu_fseek(f, cur_pos, SEEK_SET);
4995
4996     ret = 0;
4997     return ret;
4998 }
4999
5000 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5001 {
5002     SaveStateEntry *se;
5003
5004     for(se = first_se; se != NULL; se = se->next) {
5005         if (!strcmp(se->idstr, idstr) && 
5006             instance_id == se->instance_id)
5007             return se;
5008     }
5009     return NULL;
5010 }
5011
5012 int qemu_loadvm_state(QEMUFile *f)
5013 {
5014     SaveStateEntry *se;
5015     int len, ret, instance_id, record_len, version_id;
5016     int64_t total_len, end_pos, cur_pos;
5017     unsigned int v;
5018     char idstr[256];
5019     
5020     v = qemu_get_be32(f);
5021     if (v != QEMU_VM_FILE_MAGIC)
5022         goto fail;
5023     v = qemu_get_be32(f);
5024     if (v != QEMU_VM_FILE_VERSION) {
5025     fail:
5026         ret = -1;
5027         goto the_end;
5028     }
5029     total_len = qemu_get_be64(f);
5030     end_pos = total_len + qemu_ftell(f);
5031     for(;;) {
5032         if (qemu_ftell(f) >= end_pos)
5033             break;
5034         len = qemu_get_byte(f);
5035         qemu_get_buffer(f, idstr, len);
5036         idstr[len] = '\0';
5037         instance_id = qemu_get_be32(f);
5038         version_id = qemu_get_be32(f);
5039         record_len = qemu_get_be32(f);
5040 #if 0
5041         printf("idstr=%s instance=0x%x version=%d len=%d\n", 
5042                idstr, instance_id, version_id, record_len);
5043 #endif
5044         cur_pos = qemu_ftell(f);
5045         se = find_se(idstr, instance_id);
5046         if (!se) {
5047             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
5048                     instance_id, idstr);
5049         } else {
5050             ret = se->load_state(f, se->opaque, version_id);
5051             if (ret < 0) {
5052                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
5053                         instance_id, idstr);
5054             }
5055         }
5056         /* always seek to exact end of record */
5057         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5058     }
5059     ret = 0;
5060  the_end:
5061     return ret;
5062 }
5063
5064 /* device can contain snapshots */
5065 static int bdrv_can_snapshot(BlockDriverState *bs)
5066 {
5067     return (bs &&
5068             !bdrv_is_removable(bs) &&
5069             !bdrv_is_read_only(bs));
5070 }
5071
5072 /* device must be snapshots in order to have a reliable snapshot */
5073 static int bdrv_has_snapshot(BlockDriverState *bs)
5074 {
5075     return (bs &&
5076             !bdrv_is_removable(bs) &&
5077             !bdrv_is_read_only(bs));
5078 }
5079
5080 static BlockDriverState *get_bs_snapshots(void)
5081 {
5082     BlockDriverState *bs;
5083     int i;
5084
5085     if (bs_snapshots)
5086         return bs_snapshots;
5087     for(i = 0; i <= MAX_DISKS; i++) {
5088         bs = bs_table[i];
5089         if (bdrv_can_snapshot(bs))
5090             goto ok;
5091     }
5092     return NULL;
5093  ok:
5094     bs_snapshots = bs;
5095     return bs;
5096 }
5097
5098 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5099                               const char *name)
5100 {
5101     QEMUSnapshotInfo *sn_tab, *sn;
5102     int nb_sns, i, ret;
5103     
5104     ret = -ENOENT;
5105     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5106     if (nb_sns < 0)
5107         return ret;
5108     for(i = 0; i < nb_sns; i++) {
5109         sn = &sn_tab[i];
5110         if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5111             *sn_info = *sn;
5112             ret = 0;
5113             break;
5114         }
5115     }
5116     qemu_free(sn_tab);
5117     return ret;
5118 }
5119
5120 void do_savevm(const char *name)
5121 {
5122     BlockDriverState *bs, *bs1;
5123     QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5124     int must_delete, ret, i;
5125     BlockDriverInfo bdi1, *bdi = &bdi1;
5126     QEMUFile *f;
5127     int saved_vm_running;
5128 #ifdef _WIN32
5129     struct _timeb tb;
5130 #else
5131     struct timeval tv;
5132 #endif
5133
5134     bs = get_bs_snapshots();
5135     if (!bs) {
5136         term_printf("No block device can accept snapshots\n");
5137         return;
5138     }
5139
5140     /* ??? Should this occur after vm_stop?  */
5141     qemu_aio_flush();
5142
5143     saved_vm_running = vm_running;
5144     vm_stop(0);
5145     
5146     must_delete = 0;
5147     if (name) {
5148         ret = bdrv_snapshot_find(bs, old_sn, name);
5149         if (ret >= 0) {
5150             must_delete = 1;
5151         }
5152     }
5153     memset(sn, 0, sizeof(*sn));
5154     if (must_delete) {
5155         pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5156         pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5157     } else {
5158         if (name)
5159             pstrcpy(sn->name, sizeof(sn->name), name);
5160     }
5161
5162     /* fill auxiliary fields */
5163 #ifdef _WIN32
5164     _ftime(&tb);
5165     sn->date_sec = tb.time;
5166     sn->date_nsec = tb.millitm * 1000000;
5167 #else
5168     gettimeofday(&tv, NULL);
5169     sn->date_sec = tv.tv_sec;
5170     sn->date_nsec = tv.tv_usec * 1000;
5171 #endif
5172     sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5173     
5174     if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5175         term_printf("Device %s does not support VM state snapshots\n",
5176                     bdrv_get_device_name(bs));
5177         goto the_end;
5178     }
5179     
5180     /* save the VM state */
5181     f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5182     if (!f) {
5183         term_printf("Could not open VM state file\n");
5184         goto the_end;
5185     }
5186     ret = qemu_savevm_state(f);
5187     sn->vm_state_size = qemu_ftell(f);
5188     qemu_fclose(f);
5189     if (ret < 0) {
5190         term_printf("Error %d while writing VM\n", ret);
5191         goto the_end;
5192     }
5193     
5194     /* create the snapshots */
5195
5196     for(i = 0; i < MAX_DISKS; i++) {
5197         bs1 = bs_table[i];
5198         if (bdrv_has_snapshot(bs1)) {
5199             if (must_delete) {
5200                 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5201                 if (ret < 0) {
5202                     term_printf("Error while deleting snapshot on '%s'\n",
5203                                 bdrv_get_device_name(bs1));
5204                 }
5205             }
5206             ret = bdrv_snapshot_create(bs1, sn);
5207             if (ret < 0) {
5208                 term_printf("Error while creating snapshot on '%s'\n",
5209                             bdrv_get_device_name(bs1));
5210             }
5211         }
5212     }
5213
5214  the_end:
5215     if (saved_vm_running)
5216         vm_start();
5217 }
5218
5219 void do_loadvm(const char *name)
5220 {
5221     BlockDriverState *bs, *bs1;
5222     BlockDriverInfo bdi1, *bdi = &bdi1;
5223     QEMUFile *f;
5224     int i, ret;
5225     int saved_vm_running;
5226
5227     bs = get_bs_snapshots();
5228     if (!bs) {
5229         term_printf("No block device supports snapshots\n");
5230         return;
5231     }
5232     
5233     /* Flush all IO requests so they don't interfere with the new state.  */
5234     qemu_aio_flush();
5235
5236     saved_vm_running = vm_running;
5237     vm_stop(0);
5238
5239     for(i = 0; i <= MAX_DISKS; i++) {
5240         bs1 = bs_table[i];
5241         if (bdrv_has_snapshot(bs1)) {
5242             ret = bdrv_snapshot_goto(bs1, name);
5243             if (ret < 0) {
5244                 if (bs != bs1)
5245                     term_printf("Warning: ");
5246                 switch(ret) {
5247                 case -ENOTSUP:
5248                     term_printf("Snapshots not supported on device '%s'\n",
5249                                 bdrv_get_device_name(bs1));
5250                     break;
5251                 case -ENOENT:
5252                     term_printf("Could not find snapshot '%s' on device '%s'\n",
5253                                 name, bdrv_get_device_name(bs1));
5254                     break;
5255                 default:
5256                     term_printf("Error %d while activating snapshot on '%s'\n",
5257                                 ret, bdrv_get_device_name(bs1));
5258                     break;
5259                 }
5260                 /* fatal on snapshot block device */
5261                 if (bs == bs1)
5262                     goto the_end;
5263             }
5264         }
5265     }
5266
5267     if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5268         term_printf("Device %s does not support VM state snapshots\n",
5269                     bdrv_get_device_name(bs));
5270         return;
5271     }
5272     
5273     /* restore the VM state */
5274     f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5275     if (!f) {
5276         term_printf("Could not open VM state file\n");
5277         goto the_end;
5278     }
5279     ret = qemu_loadvm_state(f);
5280     qemu_fclose(f);
5281     if (ret < 0) {
5282         term_printf("Error %d while loading VM state\n", ret);
5283     }
5284  the_end:
5285     if (saved_vm_running)
5286         vm_start();
5287 }
5288
5289 void do_delvm(const char *name)
5290 {
5291     BlockDriverState *bs, *bs1;
5292     int i, ret;
5293
5294     bs = get_bs_snapshots();
5295     if (!bs) {
5296         term_printf("No block device supports snapshots\n");
5297         return;
5298     }
5299     
5300     for(i = 0; i <= MAX_DISKS; i++) {
5301         bs1 = bs_table[i];
5302         if (bdrv_has_snapshot(bs1)) {
5303             ret = bdrv_snapshot_delete(bs1, name);
5304             if (ret < 0) {
5305                 if (ret == -ENOTSUP)
5306                     term_printf("Snapshots not supported on device '%s'\n",
5307                                 bdrv_get_device_name(bs1));
5308                 else
5309                     term_printf("Error %d while deleting snapshot on '%s'\n",
5310                                 ret, bdrv_get_device_name(bs1));
5311             }
5312         }
5313     }
5314 }
5315
5316 void do_info_snapshots(void)
5317 {
5318     BlockDriverState *bs, *bs1;
5319     QEMUSnapshotInfo *sn_tab, *sn;
5320     int nb_sns, i;
5321     char buf[256];
5322
5323     bs = get_bs_snapshots();
5324     if (!bs) {
5325         term_printf("No available block device supports snapshots\n");
5326         return;
5327     }
5328     term_printf("Snapshot devices:");
5329     for(i = 0; i <= MAX_DISKS; i++) {
5330         bs1 = bs_table[i];
5331         if (bdrv_has_snapshot(bs1)) {
5332             if (bs == bs1)
5333                 term_printf(" %s", bdrv_get_device_name(bs1));
5334         }
5335     }
5336     term_printf("\n");
5337
5338     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5339     if (nb_sns < 0) {
5340         term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5341         return;
5342     }
5343     term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5344     term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5345     for(i = 0; i < nb_sns; i++) {
5346         sn = &sn_tab[i];
5347         term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5348     }
5349     qemu_free(sn_tab);
5350 }
5351
5352 /***********************************************************/
5353 /* cpu save/restore */
5354
5355 #if defined(TARGET_I386)
5356
5357 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5358 {
5359     qemu_put_be32(f, dt->selector);
5360     qemu_put_betl(f, dt->base);
5361     qemu_put_be32(f, dt->limit);
5362     qemu_put_be32(f, dt->flags);
5363 }
5364
5365 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5366 {
5367     dt->selector = qemu_get_be32(f);
5368     dt->base = qemu_get_betl(f);
5369     dt->limit = qemu_get_be32(f);
5370     dt->flags = qemu_get_be32(f);
5371 }
5372
5373 void cpu_save(QEMUFile *f, void *opaque)
5374 {
5375     CPUState *env = opaque;
5376     uint16_t fptag, fpus, fpuc, fpregs_format;
5377     uint32_t hflags;
5378     int i;
5379     
5380     for(i = 0; i < CPU_NB_REGS; i++)
5381         qemu_put_betls(f, &env->regs[i]);
5382     qemu_put_betls(f, &env->eip);
5383     qemu_put_betls(f, &env->eflags);
5384     hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5385     qemu_put_be32s(f, &hflags);
5386     
5387     /* FPU */
5388     fpuc = env->fpuc;
5389     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5390     fptag = 0;
5391     for(i = 0; i < 8; i++) {
5392         fptag |= ((!env->fptags[i]) << i);
5393     }
5394     
5395     qemu_put_be16s(f, &fpuc);
5396     qemu_put_be16s(f, &fpus);
5397     qemu_put_be16s(f, &fptag);
5398
5399 #ifdef USE_X86LDOUBLE
5400     fpregs_format = 0;
5401 #else
5402     fpregs_format = 1;
5403 #endif
5404     qemu_put_be16s(f, &fpregs_format);
5405     
5406     for(i = 0; i < 8; i++) {
5407 #ifdef USE_X86LDOUBLE
5408         {
5409             uint64_t mant;
5410             uint16_t exp;
5411             /* we save the real CPU data (in case of MMX usage only 'mant'
5412                contains the MMX register */
5413             cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5414             qemu_put_be64(f, mant);
5415             qemu_put_be16(f, exp);
5416         }
5417 #else
5418         /* if we use doubles for float emulation, we save the doubles to
5419            avoid losing information in case of MMX usage. It can give
5420            problems if the image is restored on a CPU where long
5421            doubles are used instead. */
5422         qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5423 #endif
5424     }
5425
5426     for(i = 0; i < 6; i++)
5427         cpu_put_seg(f, &env->segs[i]);
5428     cpu_put_seg(f, &env->ldt);
5429     cpu_put_seg(f, &env->tr);
5430     cpu_put_seg(f, &env->gdt);
5431     cpu_put_seg(f, &env->idt);
5432     
5433     qemu_put_be32s(f, &env->sysenter_cs);
5434     qemu_put_be32s(f, &env->sysenter_esp);
5435     qemu_put_be32s(f, &env->sysenter_eip);
5436     
5437     qemu_put_betls(f, &env->cr[0]);
5438     qemu_put_betls(f, &env->cr[2]);
5439     qemu_put_betls(f, &env->cr[3]);
5440     qemu_put_betls(f, &env->cr[4]);
5441     
5442     for(i = 0; i < 8; i++)
5443         qemu_put_betls(f, &env->dr[i]);
5444
5445     /* MMU */
5446     qemu_put_be32s(f, &env->a20_mask);
5447
5448     /* XMM */
5449     qemu_put_be32s(f, &env->mxcsr);
5450     for(i = 0; i < CPU_NB_REGS; i++) {
5451         qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5452         qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5453     }
5454
5455 #ifdef TARGET_X86_64
5456     qemu_put_be64s(f, &env->efer);
5457     qemu_put_be64s(f, &env->star);
5458     qemu_put_be64s(f, &env->lstar);
5459     qemu_put_be64s(f, &env->cstar);
5460     qemu_put_be64s(f, &env->fmask);
5461     qemu_put_be64s(f, &env->kernelgsbase);
5462 #endif
5463     qemu_put_be32s(f, &env->smbase);
5464 }
5465
5466 #ifdef USE_X86LDOUBLE
5467 /* XXX: add that in a FPU generic layer */
5468 union x86_longdouble {
5469     uint64_t mant;
5470     uint16_t exp;
5471 };
5472
5473 #define MANTD1(fp)      (fp & ((1LL << 52) - 1))
5474 #define EXPBIAS1 1023
5475 #define EXPD1(fp)       ((fp >> 52) & 0x7FF)
5476 #define SIGND1(fp)      ((fp >> 32) & 0x80000000)
5477
5478 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5479 {
5480     int e;
5481     /* mantissa */
5482     p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5483     /* exponent + sign */
5484     e = EXPD1(temp) - EXPBIAS1 + 16383;
5485     e |= SIGND1(temp) >> 16;
5486     p->exp = e;
5487 }
5488 #endif
5489
5490 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5491 {
5492     CPUState *env = opaque;
5493     int i, guess_mmx;
5494     uint32_t hflags;
5495     uint16_t fpus, fpuc, fptag, fpregs_format;
5496
5497     if (version_id != 3 && version_id != 4)
5498         return -EINVAL;
5499     for(i = 0; i < CPU_NB_REGS; i++)
5500         qemu_get_betls(f, &env->regs[i]);
5501     qemu_get_betls(f, &env->eip);
5502     qemu_get_betls(f, &env->eflags);
5503     qemu_get_be32s(f, &hflags);
5504
5505     qemu_get_be16s(f, &fpuc);
5506     qemu_get_be16s(f, &fpus);
5507     qemu_get_be16s(f, &fptag);
5508     qemu_get_be16s(f, &fpregs_format);
5509     
5510     /* NOTE: we cannot always restore the FPU state if the image come
5511        from a host with a different 'USE_X86LDOUBLE' define. We guess
5512        if we are in an MMX state to restore correctly in that case. */
5513     guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5514     for(i = 0; i < 8; i++) {
5515         uint64_t mant;
5516         uint16_t exp;
5517         
5518         switch(fpregs_format) {
5519         case 0:
5520             mant = qemu_get_be64(f);
5521             exp = qemu_get_be16(f);
5522 #ifdef USE_X86LDOUBLE
5523             env->fpregs[i].d = cpu_set_fp80(mant, exp);
5524 #else
5525             /* difficult case */
5526             if (guess_mmx)
5527                 env->fpregs[i].mmx.MMX_Q(0) = mant;
5528             else
5529                 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5530 #endif
5531             break;
5532         case 1:
5533             mant = qemu_get_be64(f);
5534 #ifdef USE_X86LDOUBLE
5535             {
5536                 union x86_longdouble *p;
5537                 /* difficult case */
5538                 p = (void *)&env->fpregs[i];
5539                 if (guess_mmx) {
5540                     p->mant = mant;
5541                     p->exp = 0xffff;
5542                 } else {
5543                     fp64_to_fp80(p, mant);
5544                 }
5545             }
5546 #else
5547             env->fpregs[i].mmx.MMX_Q(0) = mant;
5548 #endif            
5549             break;
5550         default:
5551             return -EINVAL;
5552         }
5553     }
5554
5555     env->fpuc = fpuc;
5556     /* XXX: restore FPU round state */
5557     env->fpstt = (fpus >> 11) & 7;
5558     env->fpus = fpus & ~0x3800;
5559     fptag ^= 0xff;
5560     for(i = 0; i < 8; i++) {
5561         env->fptags[i] = (fptag >> i) & 1;
5562     }
5563     
5564     for(i = 0; i < 6; i++)
5565         cpu_get_seg(f, &env->segs[i]);
5566     cpu_get_seg(f, &env->ldt);
5567     cpu_get_seg(f, &env->tr);
5568     cpu_get_seg(f, &env->gdt);
5569     cpu_get_seg(f, &env->idt);
5570     
5571     qemu_get_be32s(f, &env->sysenter_cs);
5572     qemu_get_be32s(f, &env->sysenter_esp);
5573     qemu_get_be32s(f, &env->sysenter_eip);
5574     
5575     qemu_get_betls(f, &env->cr[0]);
5576     qemu_get_betls(f, &env->cr[2]);
5577     qemu_get_betls(f, &env->cr[3]);
5578     qemu_get_betls(f, &env->cr[4]);
5579     
5580     for(i = 0; i < 8; i++)
5581         qemu_get_betls(f, &env->dr[i]);
5582
5583     /* MMU */
5584     qemu_get_be32s(f, &env->a20_mask);
5585
5586     qemu_get_be32s(f, &env->mxcsr);
5587     for(i = 0; i < CPU_NB_REGS; i++) {
5588         qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5589         qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5590     }
5591
5592 #ifdef TARGET_X86_64
5593     qemu_get_be64s(f, &env->efer);
5594     qemu_get_be64s(f, &env->star);
5595     qemu_get_be64s(f, &env->lstar);
5596     qemu_get_be64s(f, &env->cstar);
5597     qemu_get_be64s(f, &env->fmask);
5598     qemu_get_be64s(f, &env->kernelgsbase);
5599 #endif
5600     if (version_id >= 4) 
5601         qemu_get_be32s(f, &env->smbase);
5602
5603     /* XXX: compute hflags from scratch, except for CPL and IIF */
5604     env->hflags = hflags;
5605     tlb_flush(env, 1);
5606     return 0;
5607 }
5608
5609 #elif defined(TARGET_PPC)
5610 void cpu_save(QEMUFile *f, void *opaque)
5611 {
5612 }
5613
5614 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5615 {
5616     return 0;
5617 }
5618
5619 #elif defined(TARGET_MIPS)
5620 void cpu_save(QEMUFile *f, void *opaque)
5621 {
5622 }
5623
5624 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5625 {
5626     return 0;
5627 }
5628
5629 #elif defined(TARGET_SPARC)
5630 void cpu_save(QEMUFile *f, void *opaque)
5631 {
5632     CPUState *env = opaque;
5633     int i;
5634     uint32_t tmp;
5635
5636     for(i = 0; i < 8; i++)
5637         qemu_put_betls(f, &env->gregs[i]);
5638     for(i = 0; i < NWINDOWS * 16; i++)
5639         qemu_put_betls(f, &env->regbase[i]);
5640
5641     /* FPU */
5642     for(i = 0; i < TARGET_FPREGS; i++) {
5643         union {
5644             float32 f;
5645             uint32_t i;
5646         } u;
5647         u.f = env->fpr[i];
5648         qemu_put_be32(f, u.i);
5649     }
5650
5651     qemu_put_betls(f, &env->pc);
5652     qemu_put_betls(f, &env->npc);
5653     qemu_put_betls(f, &env->y);
5654     tmp = GET_PSR(env);
5655     qemu_put_be32(f, tmp);
5656     qemu_put_betls(f, &env->fsr);
5657     qemu_put_betls(f, &env->tbr);
5658 #ifndef TARGET_SPARC64
5659     qemu_put_be32s(f, &env->wim);
5660     /* MMU */
5661     for(i = 0; i < 16; i++)
5662         qemu_put_be32s(f, &env->mmuregs[i]);
5663 #endif
5664 }
5665
5666 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5667 {
5668     CPUState *env = opaque;
5669     int i;
5670     uint32_t tmp;
5671
5672     for(i = 0; i < 8; i++)
5673         qemu_get_betls(f, &env->gregs[i]);
5674     for(i = 0; i < NWINDOWS * 16; i++)
5675         qemu_get_betls(f, &env->regbase[i]);
5676
5677     /* FPU */
5678     for(i = 0; i < TARGET_FPREGS; i++) {
5679         union {
5680             float32 f;
5681             uint32_t i;
5682         } u;
5683         u.i = qemu_get_be32(f);
5684         env->fpr[i] = u.f;
5685     }
5686
5687     qemu_get_betls(f, &env->pc);
5688     qemu_get_betls(f, &env->npc);
5689     qemu_get_betls(f, &env->y);
5690     tmp = qemu_get_be32(f);
5691     env->cwp = 0; /* needed to ensure that the wrapping registers are
5692                      correctly updated */
5693     PUT_PSR(env, tmp);
5694     qemu_get_betls(f, &env->fsr);
5695     qemu_get_betls(f, &env->tbr);
5696 #ifndef TARGET_SPARC64
5697     qemu_get_be32s(f, &env->wim);
5698     /* MMU */
5699     for(i = 0; i < 16; i++)
5700         qemu_get_be32s(f, &env->mmuregs[i]);
5701 #endif
5702     tlb_flush(env, 1);
5703     return 0;
5704 }
5705
5706 #elif defined(TARGET_ARM)
5707
5708 void cpu_save(QEMUFile *f, void *opaque)
5709 {
5710     int i;
5711     CPUARMState *env = (CPUARMState *)opaque;
5712
5713     for (i = 0; i < 16; i++) {
5714         qemu_put_be32(f, env->regs[i]);
5715     }
5716     qemu_put_be32(f, cpsr_read(env));
5717     qemu_put_be32(f, env->spsr);
5718     for (i = 0; i < 6; i++) {
5719         qemu_put_be32(f, env->banked_spsr[i]);
5720         qemu_put_be32(f, env->banked_r13[i]);
5721         qemu_put_be32(f, env->banked_r14[i]);
5722     }
5723     for (i = 0; i < 5; i++) {
5724         qemu_put_be32(f, env->usr_regs[i]);
5725         qemu_put_be32(f, env->fiq_regs[i]);
5726     }
5727     qemu_put_be32(f, env->cp15.c0_cpuid);
5728     qemu_put_be32(f, env->cp15.c0_cachetype);
5729     qemu_put_be32(f, env->cp15.c1_sys);
5730     qemu_put_be32(f, env->cp15.c1_coproc);
5731     qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
5732     qemu_put_be32(f, env->cp15.c2_base);
5733     qemu_put_be32(f, env->cp15.c2_data);
5734     qemu_put_be32(f, env->cp15.c2_insn);
5735     qemu_put_be32(f, env->cp15.c3);
5736     qemu_put_be32(f, env->cp15.c5_insn);
5737     qemu_put_be32(f, env->cp15.c5_data);
5738     for (i = 0; i < 8; i++) {
5739         qemu_put_be32(f, env->cp15.c6_region[i]);
5740     }
5741     qemu_put_be32(f, env->cp15.c6_insn);
5742     qemu_put_be32(f, env->cp15.c6_data);
5743     qemu_put_be32(f, env->cp15.c9_insn);
5744     qemu_put_be32(f, env->cp15.c9_data);
5745     qemu_put_be32(f, env->cp15.c13_fcse);
5746     qemu_put_be32(f, env->cp15.c13_context);
5747     qemu_put_be32(f, env->cp15.c15_cpar);
5748
5749     qemu_put_be32(f, env->features);
5750
5751     if (arm_feature(env, ARM_FEATURE_VFP)) {
5752         for (i = 0;  i < 16; i++) {
5753             CPU_DoubleU u;
5754             u.d = env->vfp.regs[i];
5755             qemu_put_be32(f, u.l.upper);
5756             qemu_put_be32(f, u.l.lower);
5757         }
5758         for (i = 0; i < 16; i++) {
5759             qemu_put_be32(f, env->vfp.xregs[i]);
5760         }
5761
5762         /* TODO: Should use proper FPSCR access functions.  */
5763         qemu_put_be32(f, env->vfp.vec_len);
5764         qemu_put_be32(f, env->vfp.vec_stride);
5765     }
5766
5767     if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5768         for (i = 0; i < 16; i++) {
5769             qemu_put_be64(f, env->iwmmxt.regs[i]);
5770         }
5771         for (i = 0; i < 16; i++) {
5772             qemu_put_be32(f, env->iwmmxt.cregs[i]);
5773         }
5774     }
5775 }
5776
5777 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5778 {
5779     CPUARMState *env = (CPUARMState *)opaque;
5780     int i;
5781
5782     if (version_id != 0)
5783         return -EINVAL;
5784
5785     for (i = 0; i < 16; i++) {
5786         env->regs[i] = qemu_get_be32(f);
5787     }
5788     cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5789     env->spsr = qemu_get_be32(f);
5790     for (i = 0; i < 6; i++) {
5791         env->banked_spsr[i] = qemu_get_be32(f);
5792         env->banked_r13[i] = qemu_get_be32(f);
5793         env->banked_r14[i] = qemu_get_be32(f);
5794     }
5795     for (i = 0; i < 5; i++) {
5796         env->usr_regs[i] = qemu_get_be32(f);
5797         env->fiq_regs[i] = qemu_get_be32(f);
5798     }
5799     env->cp15.c0_cpuid = qemu_get_be32(f);
5800     env->cp15.c0_cachetype = qemu_get_be32(f);
5801     env->cp15.c1_sys = qemu_get_be32(f);
5802     env->cp15.c1_coproc = qemu_get_be32(f);
5803     env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
5804     env->cp15.c2_base = qemu_get_be32(f);
5805     env->cp15.c2_data = qemu_get_be32(f);
5806     env->cp15.c2_insn = qemu_get_be32(f);
5807     env->cp15.c3 = qemu_get_be32(f);
5808     env->cp15.c5_insn = qemu_get_be32(f);
5809     env->cp15.c5_data = qemu_get_be32(f);
5810     for (i = 0; i < 8; i++) {
5811         env->cp15.c6_region[i] = qemu_get_be32(f);
5812     }
5813     env->cp15.c6_insn = qemu_get_be32(f);
5814     env->cp15.c6_data = qemu_get_be32(f);
5815     env->cp15.c9_insn = qemu_get_be32(f);
5816     env->cp15.c9_data = qemu_get_be32(f);
5817     env->cp15.c13_fcse = qemu_get_be32(f);
5818     env->cp15.c13_context = qemu_get_be32(f);
5819     env->cp15.c15_cpar = qemu_get_be32(f);
5820
5821     env->features = qemu_get_be32(f);
5822
5823     if (arm_feature(env, ARM_FEATURE_VFP)) {
5824         for (i = 0;  i < 16; i++) {
5825             CPU_DoubleU u;
5826             u.l.upper = qemu_get_be32(f);
5827             u.l.lower = qemu_get_be32(f);
5828             env->vfp.regs[i] = u.d;
5829         }
5830         for (i = 0; i < 16; i++) {
5831             env->vfp.xregs[i] = qemu_get_be32(f);
5832         }
5833
5834         /* TODO: Should use proper FPSCR access functions.  */
5835         env->vfp.vec_len = qemu_get_be32(f);
5836         env->vfp.vec_stride = qemu_get_be32(f);
5837     }
5838
5839     if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5840         for (i = 0; i < 16; i++) {
5841             env->iwmmxt.regs[i] = qemu_get_be64(f);
5842         }
5843         for (i = 0; i < 16; i++) {
5844             env->iwmmxt.cregs[i] = qemu_get_be32(f);
5845         }
5846     }
5847
5848     return 0;
5849 }
5850
5851 #else
5852
5853 #warning No CPU save/restore functions
5854
5855 #endif
5856
5857 /***********************************************************/
5858 /* ram save/restore */
5859
5860 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5861 {
5862     int v;
5863
5864     v = qemu_get_byte(f);
5865     switch(v) {
5866     case 0:
5867         if (qemu_get_buffer(f, buf, len) != len)
5868             return -EIO;
5869         break;
5870     case 1:
5871         v = qemu_get_byte(f);
5872         memset(buf, v, len);
5873         break;
5874     default:
5875         return -EINVAL;
5876     }
5877     return 0;
5878 }
5879
5880 static int ram_load_v1(QEMUFile *f, void *opaque)
5881 {
5882     int i, ret;
5883
5884     if (qemu_get_be32(f) != phys_ram_size)
5885         return -EINVAL;
5886     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5887         ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5888         if (ret)
5889             return ret;
5890     }
5891     return 0;
5892 }
5893
5894 #define BDRV_HASH_BLOCK_SIZE 1024
5895 #define IOBUF_SIZE 4096
5896 #define RAM_CBLOCK_MAGIC 0xfabe
5897
5898 typedef struct RamCompressState {
5899     z_stream zstream;
5900     QEMUFile *f;
5901     uint8_t buf[IOBUF_SIZE];
5902 } RamCompressState;
5903
5904 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5905 {
5906     int ret;
5907     memset(s, 0, sizeof(*s));
5908     s->f = f;
5909     ret = deflateInit2(&s->zstream, 1,
5910                        Z_DEFLATED, 15, 
5911                        9, Z_DEFAULT_STRATEGY);
5912     if (ret != Z_OK)
5913         return -1;
5914     s->zstream.avail_out = IOBUF_SIZE;
5915     s->zstream.next_out = s->buf;
5916     return 0;
5917 }
5918
5919 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5920 {
5921     qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5922     qemu_put_be16(s->f, len);
5923     qemu_put_buffer(s->f, buf, len);
5924 }
5925
5926 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5927 {
5928     int ret;
5929
5930     s->zstream.avail_in = len;
5931     s->zstream.next_in = (uint8_t *)buf;
5932     while (s->zstream.avail_in > 0) {
5933         ret = deflate(&s->zstream, Z_NO_FLUSH);
5934         if (ret != Z_OK)
5935             return -1;
5936         if (s->zstream.avail_out == 0) {
5937             ram_put_cblock(s, s->buf, IOBUF_SIZE);
5938             s->zstream.avail_out = IOBUF_SIZE;
5939             s->zstream.next_out = s->buf;
5940         }
5941     }
5942     return 0;
5943 }
5944
5945 static void ram_compress_close(RamCompressState *s)
5946 {
5947     int len, ret;
5948
5949     /* compress last bytes */
5950     for(;;) {
5951         ret = deflate(&s->zstream, Z_FINISH);
5952         if (ret == Z_OK || ret == Z_STREAM_END) {
5953             len = IOBUF_SIZE - s->zstream.avail_out;
5954             if (len > 0) {
5955                 ram_put_cblock(s, s->buf, len);
5956             }
5957             s->zstream.avail_out = IOBUF_SIZE;
5958             s->zstream.next_out = s->buf;
5959             if (ret == Z_STREAM_END)
5960                 break;
5961         } else {
5962             goto fail;
5963         }
5964     }
5965 fail:
5966     deflateEnd(&s->zstream);
5967 }
5968
5969 typedef struct RamDecompressState {
5970     z_stream zstream;
5971     QEMUFile *f;
5972     uint8_t buf[IOBUF_SIZE];
5973 } RamDecompressState;
5974
5975 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5976 {
5977     int ret;
5978     memset(s, 0, sizeof(*s));
5979     s->f = f;
5980     ret = inflateInit(&s->zstream);
5981     if (ret != Z_OK)
5982         return -1;
5983     return 0;
5984 }
5985
5986 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5987 {
5988     int ret, clen;
5989
5990     s->zstream.avail_out = len;
5991     s->zstream.next_out = buf;
5992     while (s->zstream.avail_out > 0) {
5993         if (s->zstream.avail_in == 0) {
5994             if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5995                 return -1;
5996             clen = qemu_get_be16(s->f);
5997             if (clen > IOBUF_SIZE)
5998                 return -1;
5999             qemu_get_buffer(s->f, s->buf, clen);
6000             s->zstream.avail_in = clen;
6001             s->zstream.next_in = s->buf;
6002         }
6003         ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6004         if (ret != Z_OK && ret != Z_STREAM_END) {
6005             return -1;
6006         }
6007     }
6008     return 0;
6009 }
6010
6011 static void ram_decompress_close(RamDecompressState *s)
6012 {
6013     inflateEnd(&s->zstream);
6014 }
6015
6016 static void ram_save(QEMUFile *f, void *opaque)
6017 {
6018     int i;
6019     RamCompressState s1, *s = &s1;
6020     uint8_t buf[10];
6021     
6022     qemu_put_be32(f, phys_ram_size);
6023     if (ram_compress_open(s, f) < 0)
6024         return;
6025     for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6026 #if 0
6027         if (tight_savevm_enabled) {
6028             int64_t sector_num;
6029             int j;
6030
6031             /* find if the memory block is available on a virtual
6032                block device */
6033             sector_num = -1;
6034             for(j = 0; j < MAX_DISKS; j++) {
6035                 if (bs_table[j]) {
6036                     sector_num = bdrv_hash_find(bs_table[j], 
6037                                                 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6038                     if (sector_num >= 0)
6039                         break;
6040                 }
6041             }
6042             if (j == MAX_DISKS)
6043                 goto normal_compress;
6044             buf[0] = 1;
6045             buf[1] = j;
6046             cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6047             ram_compress_buf(s, buf, 10);
6048         } else 
6049 #endif
6050         {
6051             //        normal_compress:
6052             buf[0] = 0;
6053             ram_compress_buf(s, buf, 1);
6054             ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6055         }
6056     }
6057     ram_compress_close(s);
6058 }
6059
6060 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6061 {
6062     RamDecompressState s1, *s = &s1;
6063     uint8_t buf[10];
6064     int i;
6065
6066     if (version_id == 1)
6067         return ram_load_v1(f, opaque);
6068     if (version_id != 2)
6069         return -EINVAL;
6070     if (qemu_get_be32(f) != phys_ram_size)
6071         return -EINVAL;
6072     if (ram_decompress_open(s, f) < 0)
6073         return -EINVAL;
6074     for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6075         if (ram_decompress_buf(s, buf, 1) < 0) {
6076             fprintf(stderr, "Error while reading ram block header\n");
6077             goto error;
6078         }
6079         if (buf[0] == 0) {
6080             if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6081                 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6082                 goto error;
6083             }
6084         } else 
6085 #if 0
6086         if (buf[0] == 1) {
6087             int bs_index;
6088             int64_t sector_num;
6089
6090             ram_decompress_buf(s, buf + 1, 9);
6091             bs_index = buf[1];
6092             sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6093             if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6094                 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6095                 goto error;
6096             }
6097             if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i, 
6098                           BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6099                 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n", 
6100                         bs_index, sector_num);
6101                 goto error;
6102             }
6103         } else 
6104 #endif
6105         {
6106         error:
6107             printf("Error block header\n");
6108             return -EINVAL;
6109         }
6110     }
6111     ram_decompress_close(s);
6112     return 0;
6113 }
6114
6115 /***********************************************************/
6116 /* bottom halves (can be seen as timers which expire ASAP) */
6117
6118 struct QEMUBH {
6119     QEMUBHFunc *cb;
6120     void *opaque;
6121     int scheduled;
6122     QEMUBH *next;
6123 };
6124
6125 static QEMUBH *first_bh = NULL;
6126
6127 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6128 {
6129     QEMUBH *bh;
6130     bh = qemu_mallocz(sizeof(QEMUBH));
6131     if (!bh)
6132         return NULL;
6133     bh->cb = cb;
6134     bh->opaque = opaque;
6135     return bh;
6136 }
6137
6138 int qemu_bh_poll(void)
6139 {
6140     QEMUBH *bh, **pbh;
6141     int ret;
6142
6143     ret = 0;
6144     for(;;) {
6145         pbh = &first_bh;
6146         bh = *pbh;
6147         if (!bh)
6148             break;
6149         ret = 1;
6150         *pbh = bh->next;
6151         bh->scheduled = 0;
6152         bh->cb(bh->opaque);
6153     }
6154     return ret;
6155 }
6156
6157 void qemu_bh_schedule(QEMUBH *bh)
6158 {
6159     CPUState *env = cpu_single_env;
6160     if (bh->scheduled)
6161         return;
6162     bh->scheduled = 1;
6163     bh->next = first_bh;
6164     first_bh = bh;
6165
6166     /* stop the currently executing CPU to execute the BH ASAP */
6167     if (env) {
6168         cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6169     }
6170 }
6171
6172 void qemu_bh_cancel(QEMUBH *bh)
6173 {
6174     QEMUBH **pbh;
6175     if (bh->scheduled) {
6176         pbh = &first_bh;
6177         while (*pbh != bh)
6178             pbh = &(*pbh)->next;
6179         *pbh = bh->next;
6180         bh->scheduled = 0;
6181     }
6182 }
6183
6184 void qemu_bh_delete(QEMUBH *bh)
6185 {
6186     qemu_bh_cancel(bh);
6187     qemu_free(bh);
6188 }
6189
6190 /***********************************************************/
6191 /* machine registration */
6192
6193 QEMUMachine *first_machine = NULL;
6194
6195 int qemu_register_machine(QEMUMachine *m)
6196 {
6197     QEMUMachine **pm;
6198     pm = &first_machine;
6199     while (*pm != NULL)
6200         pm = &(*pm)->next;
6201     m->next = NULL;
6202     *pm = m;
6203     return 0;
6204 }
6205
6206 QEMUMachine *find_machine(const char *name)
6207 {
6208     QEMUMachine *m;
6209
6210     for(m = first_machine; m != NULL; m = m->next) {
6211         if (!strcmp(m->name, name))
6212             return m;
6213     }
6214     return NULL;
6215 }
6216
6217 /***********************************************************/
6218 /* main execution loop */
6219
6220 void gui_update(void *opaque)
6221 {
6222     DisplayState *ds = opaque;
6223     ds->dpy_refresh(ds);
6224     qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6225 }
6226
6227 struct vm_change_state_entry {
6228     VMChangeStateHandler *cb;
6229     void *opaque;
6230     LIST_ENTRY (vm_change_state_entry) entries;
6231 };
6232
6233 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6234
6235 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6236                                                      void *opaque)
6237 {
6238     VMChangeStateEntry *e;
6239
6240     e = qemu_mallocz(sizeof (*e));
6241     if (!e)
6242         return NULL;
6243
6244     e->cb = cb;
6245     e->opaque = opaque;
6246     LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6247     return e;
6248 }
6249
6250 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6251 {
6252     LIST_REMOVE (e, entries);
6253     qemu_free (e);
6254 }
6255
6256 static void vm_state_notify(int running)
6257 {
6258     VMChangeStateEntry *e;
6259
6260     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6261         e->cb(e->opaque, running);
6262     }
6263 }
6264
6265 /* XXX: support several handlers */
6266 static VMStopHandler *vm_stop_cb;
6267 static void *vm_stop_opaque;
6268
6269 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6270 {
6271     vm_stop_cb = cb;
6272     vm_stop_opaque = opaque;
6273     return 0;
6274 }
6275
6276 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6277 {
6278     vm_stop_cb = NULL;
6279 }
6280
6281 void vm_start(void)
6282 {
6283     if (!vm_running) {
6284         cpu_enable_ticks();
6285         vm_running = 1;
6286         vm_state_notify(1);
6287     }
6288 }
6289
6290 void vm_stop(int reason) 
6291 {
6292     if (vm_running) {
6293         cpu_disable_ticks();
6294         vm_running = 0;
6295         if (reason != 0) {
6296             if (vm_stop_cb) {
6297                 vm_stop_cb(vm_stop_opaque, reason);
6298             }
6299         }
6300         vm_state_notify(0);
6301     }
6302 }
6303
6304 /* reset/shutdown handler */
6305
6306 typedef struct QEMUResetEntry {
6307     QEMUResetHandler *func;
6308     void *opaque;
6309     struct QEMUResetEntry *next;
6310 } QEMUResetEntry;
6311
6312 static QEMUResetEntry *first_reset_entry;
6313 static int reset_requested;
6314 static int shutdown_requested;
6315 static int powerdown_requested;
6316
6317 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6318 {
6319     QEMUResetEntry **pre, *re;
6320
6321     pre = &first_reset_entry;
6322     while (*pre != NULL)
6323         pre = &(*pre)->next;
6324     re = qemu_mallocz(sizeof(QEMUResetEntry));
6325     re->func = func;
6326     re->opaque = opaque;
6327     re->next = NULL;
6328     *pre = re;
6329 }
6330
6331 static void qemu_system_reset(void)
6332 {
6333     QEMUResetEntry *re;
6334
6335     /* reset all devices */
6336     for(re = first_reset_entry; re != NULL; re = re->next) {
6337         re->func(re->opaque);
6338     }
6339 }
6340
6341 void qemu_system_reset_request(void)
6342 {
6343     if (no_reboot) {
6344         shutdown_requested = 1;
6345     } else {
6346         reset_requested = 1;
6347     }
6348     if (cpu_single_env)
6349         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6350 }
6351
6352 void qemu_system_shutdown_request(void)
6353 {
6354     shutdown_requested = 1;
6355     if (cpu_single_env)
6356         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6357 }
6358
6359 void qemu_system_powerdown_request(void)
6360 {
6361     powerdown_requested = 1;
6362     if (cpu_single_env)
6363         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6364 }
6365
6366 void main_loop_wait(int timeout)
6367 {
6368     IOHandlerRecord *ioh;
6369     fd_set rfds, wfds, xfds;
6370     int ret, nfds;
6371 #ifdef _WIN32
6372     int ret2, i;
6373 #endif
6374     struct timeval tv;
6375     PollingEntry *pe;
6376
6377
6378     /* XXX: need to suppress polling by better using win32 events */
6379     ret = 0;
6380     for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6381         ret |= pe->func(pe->opaque);
6382     }
6383 #ifdef _WIN32
6384     if (ret == 0) {
6385         int err;
6386         WaitObjects *w = &wait_objects;
6387         
6388         ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6389         if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6390             if (w->func[ret - WAIT_OBJECT_0])
6391                 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6392                 
6393             /* Check for additional signaled events */ 
6394             for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6395                                 
6396                 /* Check if event is signaled */
6397                 ret2 = WaitForSingleObject(w->events[i], 0);
6398                 if(ret2 == WAIT_OBJECT_0) {
6399                     if (w->func[i])
6400                         w->func[i](w->opaque[i]);
6401                 } else if (ret2 == WAIT_TIMEOUT) {
6402                 } else {
6403                     err = GetLastError();
6404                     fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6405                 }                
6406             }                 
6407         } else if (ret == WAIT_TIMEOUT) {
6408         } else {
6409             err = GetLastError();
6410             fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6411         }
6412     }
6413 #endif
6414     /* poll any events */
6415     /* XXX: separate device handlers from system ones */
6416     nfds = -1;
6417     FD_ZERO(&rfds);
6418     FD_ZERO(&wfds);
6419     FD_ZERO(&xfds);
6420     for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6421         if (ioh->deleted)
6422             continue;
6423         if (ioh->fd_read &&
6424             (!ioh->fd_read_poll ||
6425              ioh->fd_read_poll(ioh->opaque) != 0)) {
6426             FD_SET(ioh->fd, &rfds);
6427             if (ioh->fd > nfds)
6428                 nfds = ioh->fd;
6429         }
6430         if (ioh->fd_write) {
6431             FD_SET(ioh->fd, &wfds);
6432             if (ioh->fd > nfds)
6433                 nfds = ioh->fd;
6434         }
6435     }
6436     
6437     tv.tv_sec = 0;
6438 #ifdef _WIN32
6439     tv.tv_usec = 0;
6440 #else
6441     tv.tv_usec = timeout * 1000;
6442 #endif
6443 #if defined(CONFIG_SLIRP)
6444     if (slirp_inited) {
6445         slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6446     }
6447 #endif
6448     ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6449     if (ret > 0) {
6450         IOHandlerRecord **pioh;
6451
6452         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6453             if (ioh->deleted)
6454                 continue;
6455             if (FD_ISSET(ioh->fd, &rfds)) {
6456                 ioh->fd_read(ioh->opaque);
6457             }
6458             if (FD_ISSET(ioh->fd, &wfds)) {
6459                 ioh->fd_write(ioh->opaque);
6460             }
6461         }
6462
6463         /* remove deleted IO handlers */
6464         pioh = &first_io_handler;
6465         while (*pioh) {
6466             ioh = *pioh;
6467             if (ioh->deleted) {
6468                 *pioh = ioh->next;
6469                 qemu_free(ioh);
6470             } else 
6471                 pioh = &ioh->next;
6472         }
6473     }
6474 #if defined(CONFIG_SLIRP)
6475     if (slirp_inited) {
6476         if (ret < 0) {
6477             FD_ZERO(&rfds);
6478             FD_ZERO(&wfds);
6479             FD_ZERO(&xfds);
6480         }
6481         slirp_select_poll(&rfds, &wfds, &xfds);
6482     }
6483 #endif
6484     qemu_aio_poll();
6485
6486     if (vm_running) {
6487         qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
6488                         qemu_get_clock(vm_clock));
6489         /* run dma transfers, if any */
6490         DMA_run();
6491     }
6492
6493     /* real time timers */
6494     qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
6495                     qemu_get_clock(rt_clock));
6496
6497     /* Check bottom-halves last in case any of the earlier events triggered
6498        them.  */
6499     qemu_bh_poll();
6500     
6501 }
6502
6503 static CPUState *cur_cpu;
6504
6505 int main_loop(void)
6506 {
6507     int ret, timeout;
6508 #ifdef CONFIG_PROFILER
6509     int64_t ti;
6510 #endif
6511     CPUState *env;
6512
6513     cur_cpu = first_cpu;
6514     for(;;) {
6515         if (vm_running) {
6516
6517             env = cur_cpu;
6518             for(;;) {
6519                 /* get next cpu */
6520                 env = env->next_cpu;
6521                 if (!env)
6522                     env = first_cpu;
6523 #ifdef CONFIG_PROFILER
6524                 ti = profile_getclock();
6525 #endif
6526                 ret = cpu_exec(env);
6527 #ifdef CONFIG_PROFILER
6528                 qemu_time += profile_getclock() - ti;
6529 #endif
6530                 if (ret == EXCP_HLT) {
6531                     /* Give the next CPU a chance to run.  */
6532                     cur_cpu = env;
6533                     continue;
6534                 }
6535                 if (ret != EXCP_HALTED)
6536                     break;
6537                 /* all CPUs are halted ? */
6538                 if (env == cur_cpu)
6539                     break;
6540             }
6541             cur_cpu = env;
6542
6543             if (shutdown_requested) {
6544                 ret = EXCP_INTERRUPT;
6545                 break;
6546             }
6547             if (reset_requested) {
6548                 reset_requested = 0;
6549                 qemu_system_reset();
6550                 ret = EXCP_INTERRUPT;
6551             }
6552             if (powerdown_requested) {
6553                 powerdown_requested = 0;
6554                 qemu_system_powerdown();
6555                 ret = EXCP_INTERRUPT;
6556             }
6557             if (ret == EXCP_DEBUG) {
6558                 vm_stop(EXCP_DEBUG);
6559             }
6560             /* If all cpus are halted then wait until the next IRQ */
6561             /* XXX: use timeout computed from timers */
6562             if (ret == EXCP_HALTED)
6563                 timeout = 10;
6564             else
6565                 timeout = 0;
6566         } else {
6567             timeout = 10;
6568         }
6569 #ifdef CONFIG_PROFILER
6570         ti = profile_getclock();
6571 #endif
6572         main_loop_wait(timeout);
6573 #ifdef CONFIG_PROFILER
6574         dev_time += profile_getclock() - ti;
6575 #endif
6576     }
6577     cpu_disable_ticks();
6578     return ret;
6579 }
6580
6581 static void help(int exitcode)
6582 {
6583     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6584            "usage: %s [options] [disk_image]\n"
6585            "\n"
6586            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6587            "\n"
6588            "Standard options:\n"
6589            "-M machine      select emulated machine (-M ? for list)\n"
6590            "-cpu cpu        select CPU (-cpu ? for list)\n"
6591            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
6592            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
6593            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
6594            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6595            "-mtdblock file  use 'file' as on-board Flash memory image\n"
6596            "-sd file        use 'file' as SecureDigital card image\n"
6597            "-pflash file    use 'file' as a parallel flash image\n"
6598            "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6599            "-snapshot       write to temporary files instead of disk image files\n"
6600 #ifdef CONFIG_SDL
6601            "-no-frame       open SDL window without a frame and window decorations\n"
6602            "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6603            "-no-quit        disable SDL window close capability\n"
6604 #endif
6605 #ifdef TARGET_I386
6606            "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
6607 #endif
6608            "-m megs         set virtual RAM size to megs MB [default=%d]\n"
6609            "-smp n          set the number of CPUs to 'n' [default=1]\n"
6610            "-nographic      disable graphical output and redirect serial I/Os to console\n"
6611            "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
6612 #ifndef _WIN32
6613            "-k language     use keyboard layout (for example \"fr\" for French)\n"
6614 #endif
6615 #ifdef HAS_AUDIO
6616            "-audio-help     print list of audio drivers and their options\n"
6617            "-soundhw c1,... enable audio support\n"
6618            "                and only specified sound cards (comma separated list)\n"
6619            "                use -soundhw ? to get the list of supported cards\n"
6620            "                use -soundhw all to enable all of them\n"
6621 #endif
6622            "-localtime      set the real time clock to local time [default=utc]\n"
6623            "-full-screen    start in full screen\n"
6624 #ifdef TARGET_I386
6625            "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
6626 #endif
6627            "-usb            enable the USB driver (will be the default soon)\n"
6628            "-usbdevice name add the host or guest USB device 'name'\n"
6629 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6630            "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
6631 #endif
6632            "-name string    set the name of the guest\n"
6633            "\n"
6634            "Network options:\n"
6635            "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6636            "                create a new Network Interface Card and connect it to VLAN 'n'\n"
6637 #ifdef CONFIG_SLIRP
6638            "-net user[,vlan=n][,hostname=host]\n"
6639            "                connect the user mode network stack to VLAN 'n' and send\n"
6640            "                hostname 'host' to DHCP clients\n"
6641 #endif
6642 #ifdef _WIN32
6643            "-net tap[,vlan=n],ifname=name\n"
6644            "                connect the host TAP network interface to VLAN 'n'\n"
6645 #else
6646            "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6647            "                connect the host TAP network interface to VLAN 'n' and use\n"
6648            "                the network script 'file' (default=%s);\n"
6649            "                use 'script=no' to disable script execution;\n"
6650            "                use 'fd=h' to connect to an already opened TAP interface\n"
6651 #endif
6652            "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6653            "                connect the vlan 'n' to another VLAN using a socket connection\n"
6654            "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6655            "                connect the vlan 'n' to multicast maddr and port\n"
6656            "-net none       use it alone to have zero network devices; if no -net option\n"
6657            "                is provided, the default is '-net nic -net user'\n"
6658            "\n"
6659 #ifdef CONFIG_SLIRP
6660            "-tftp dir       allow tftp access to files in dir [-net user]\n"
6661            "-bootp file     advertise file in BOOTP replies\n"
6662 #ifndef _WIN32
6663            "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
6664 #endif
6665            "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6666            "                redirect TCP or UDP connections from host to guest [-net user]\n"
6667 #endif
6668            "\n"
6669            "Linux boot specific:\n"
6670            "-kernel bzImage use 'bzImage' as kernel image\n"
6671            "-append cmdline use 'cmdline' as kernel command line\n"
6672            "-initrd file    use 'file' as initial ram disk\n"
6673            "\n"
6674            "Debug/Expert options:\n"
6675            "-monitor dev    redirect the monitor to char device 'dev'\n"
6676            "-serial dev     redirect the serial port to char device 'dev'\n"
6677            "-parallel dev   redirect the parallel port to char device 'dev'\n"
6678            "-pidfile file   Write PID to 'file'\n"
6679            "-S              freeze CPU at startup (use 'c' to start execution)\n"
6680            "-s              wait gdb connection to port\n"
6681            "-p port         set gdb connection port [default=%s]\n"
6682            "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
6683            "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
6684            "                translation (t=none or lba) (usually qemu can guess them)\n"
6685            "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
6686 #ifdef USE_KQEMU
6687            "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
6688            "-no-kqemu       disable KQEMU kernel module usage\n"
6689 #endif
6690 #ifdef USE_CODE_COPY
6691            "-no-code-copy   disable code copy acceleration\n"
6692 #endif
6693 #ifdef TARGET_I386
6694            "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
6695            "                (default is CL-GD5446 PCI VGA)\n"
6696            "-no-acpi        disable ACPI\n"
6697 #endif
6698            "-no-reboot      exit instead of rebooting\n"
6699            "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
6700            "-vnc display    start a VNC server on display\n"
6701 #ifndef _WIN32
6702            "-daemonize      daemonize QEMU after initializing\n"
6703 #endif
6704            "-option-rom rom load a file, rom, into the option ROM space\n"
6705 #ifdef TARGET_SPARC
6706            "-prom-env variable=value  set OpenBIOS nvram variables\n"
6707 #endif
6708            "\n"
6709            "During emulation, the following keys are useful:\n"
6710            "ctrl-alt-f      toggle full screen\n"
6711            "ctrl-alt-n      switch to virtual console 'n'\n"
6712            "ctrl-alt        toggle mouse and keyboard grab\n"
6713            "\n"
6714            "When using -nographic, press 'ctrl-a h' to get some help.\n"
6715            ,
6716            "qemu",
6717            DEFAULT_RAM_SIZE,
6718 #ifndef _WIN32
6719            DEFAULT_NETWORK_SCRIPT,
6720 #endif
6721            DEFAULT_GDBSTUB_PORT,
6722            "/tmp/qemu.log");
6723     exit(exitcode);
6724 }
6725
6726 #define HAS_ARG 0x0001
6727
6728 enum {
6729     QEMU_OPTION_h,
6730
6731     QEMU_OPTION_M,
6732     QEMU_OPTION_cpu,
6733     QEMU_OPTION_fda,
6734     QEMU_OPTION_fdb,
6735     QEMU_OPTION_hda,
6736     QEMU_OPTION_hdb,
6737     QEMU_OPTION_hdc,
6738     QEMU_OPTION_hdd,
6739     QEMU_OPTION_cdrom,
6740     QEMU_OPTION_mtdblock,
6741     QEMU_OPTION_sd,
6742     QEMU_OPTION_pflash,
6743     QEMU_OPTION_boot,
6744     QEMU_OPTION_snapshot,
6745 #ifdef TARGET_I386
6746     QEMU_OPTION_no_fd_bootchk,
6747 #endif
6748     QEMU_OPTION_m,
6749     QEMU_OPTION_nographic,
6750     QEMU_OPTION_portrait,
6751 #ifdef HAS_AUDIO
6752     QEMU_OPTION_audio_help,
6753     QEMU_OPTION_soundhw,
6754 #endif
6755
6756     QEMU_OPTION_net,
6757     QEMU_OPTION_tftp,
6758     QEMU_OPTION_bootp,
6759     QEMU_OPTION_smb,
6760     QEMU_OPTION_redir,
6761
6762     QEMU_OPTION_kernel,
6763     QEMU_OPTION_append,
6764     QEMU_OPTION_initrd,
6765
6766     QEMU_OPTION_S,
6767     QEMU_OPTION_s,
6768     QEMU_OPTION_p,
6769     QEMU_OPTION_d,
6770     QEMU_OPTION_hdachs,
6771     QEMU_OPTION_L,
6772     QEMU_OPTION_no_code_copy,
6773     QEMU_OPTION_k,
6774     QEMU_OPTION_localtime,
6775     QEMU_OPTION_cirrusvga,
6776     QEMU_OPTION_vmsvga,
6777     QEMU_OPTION_g,
6778     QEMU_OPTION_std_vga,
6779     QEMU_OPTION_echr,
6780     QEMU_OPTION_monitor,
6781     QEMU_OPTION_serial,
6782     QEMU_OPTION_parallel,
6783     QEMU_OPTION_loadvm,
6784     QEMU_OPTION_full_screen,
6785     QEMU_OPTION_no_frame,
6786     QEMU_OPTION_alt_grab,
6787     QEMU_OPTION_no_quit,
6788     QEMU_OPTION_pidfile,
6789     QEMU_OPTION_no_kqemu,
6790     QEMU_OPTION_kernel_kqemu,
6791     QEMU_OPTION_win2k_hack,
6792     QEMU_OPTION_usb,
6793     QEMU_OPTION_usbdevice,
6794     QEMU_OPTION_smp,
6795     QEMU_OPTION_vnc,
6796     QEMU_OPTION_no_acpi,
6797     QEMU_OPTION_no_reboot,
6798     QEMU_OPTION_show_cursor,
6799     QEMU_OPTION_daemonize,
6800     QEMU_OPTION_option_rom,
6801     QEMU_OPTION_semihosting,
6802     QEMU_OPTION_name,
6803     QEMU_OPTION_prom_env,
6804 };
6805
6806 typedef struct QEMUOption {
6807     const char *name;
6808     int flags;
6809     int index;
6810 } QEMUOption;
6811
6812 const QEMUOption qemu_options[] = {
6813     { "h", 0, QEMU_OPTION_h },
6814     { "help", 0, QEMU_OPTION_h },
6815
6816     { "M", HAS_ARG, QEMU_OPTION_M },
6817     { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6818     { "fda", HAS_ARG, QEMU_OPTION_fda },
6819     { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6820     { "hda", HAS_ARG, QEMU_OPTION_hda },
6821     { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6822     { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6823     { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6824     { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6825     { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6826     { "sd", HAS_ARG, QEMU_OPTION_sd },
6827     { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6828     { "boot", HAS_ARG, QEMU_OPTION_boot },
6829     { "snapshot", 0, QEMU_OPTION_snapshot },
6830 #ifdef TARGET_I386
6831     { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6832 #endif
6833     { "m", HAS_ARG, QEMU_OPTION_m },
6834     { "nographic", 0, QEMU_OPTION_nographic },
6835     { "portrait", 0, QEMU_OPTION_portrait },
6836     { "k", HAS_ARG, QEMU_OPTION_k },
6837 #ifdef HAS_AUDIO
6838     { "audio-help", 0, QEMU_OPTION_audio_help },
6839     { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6840 #endif
6841
6842     { "net", HAS_ARG, QEMU_OPTION_net},
6843 #ifdef CONFIG_SLIRP
6844     { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6845     { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6846 #ifndef _WIN32
6847     { "smb", HAS_ARG, QEMU_OPTION_smb },
6848 #endif
6849     { "redir", HAS_ARG, QEMU_OPTION_redir },
6850 #endif
6851
6852     { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6853     { "append", HAS_ARG, QEMU_OPTION_append },
6854     { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6855
6856     { "S", 0, QEMU_OPTION_S },
6857     { "s", 0, QEMU_OPTION_s },
6858     { "p", HAS_ARG, QEMU_OPTION_p },
6859     { "d", HAS_ARG, QEMU_OPTION_d },
6860     { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6861     { "L", HAS_ARG, QEMU_OPTION_L },
6862     { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6863 #ifdef USE_KQEMU
6864     { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6865     { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6866 #endif
6867 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6868     { "g", 1, QEMU_OPTION_g },
6869 #endif
6870     { "localtime", 0, QEMU_OPTION_localtime },
6871     { "std-vga", 0, QEMU_OPTION_std_vga },
6872     { "echr", HAS_ARG, QEMU_OPTION_echr },
6873     { "monitor", HAS_ARG, QEMU_OPTION_monitor },
6874     { "serial", HAS_ARG, QEMU_OPTION_serial },
6875     { "parallel", HAS_ARG, QEMU_OPTION_parallel },
6876     { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6877     { "full-screen", 0, QEMU_OPTION_full_screen },
6878 #ifdef CONFIG_SDL
6879     { "no-frame", 0, QEMU_OPTION_no_frame },
6880     { "alt-grab", 0, QEMU_OPTION_alt_grab },
6881     { "no-quit", 0, QEMU_OPTION_no_quit },
6882 #endif
6883     { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6884     { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6885     { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6886     { "smp", HAS_ARG, QEMU_OPTION_smp },
6887     { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6888
6889     /* temporary options */
6890     { "usb", 0, QEMU_OPTION_usb },
6891     { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6892     { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6893     { "no-acpi", 0, QEMU_OPTION_no_acpi },
6894     { "no-reboot", 0, QEMU_OPTION_no_reboot },
6895     { "show-cursor", 0, QEMU_OPTION_show_cursor },
6896     { "daemonize", 0, QEMU_OPTION_daemonize },
6897     { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6898 #if defined(TARGET_ARM) || defined(TARGET_M68K)
6899     { "semihosting", 0, QEMU_OPTION_semihosting },
6900 #endif
6901     { "name", HAS_ARG, QEMU_OPTION_name },
6902 #if defined(TARGET_SPARC)
6903     { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6904 #endif
6905     { NULL },
6906 };
6907
6908 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6909
6910 /* this stack is only used during signal handling */
6911 #define SIGNAL_STACK_SIZE 32768
6912
6913 static uint8_t *signal_stack;
6914
6915 #endif
6916
6917 /* password input */
6918
6919 int qemu_key_check(BlockDriverState *bs, const char *name)
6920 {
6921     char password[256];
6922     int i;
6923
6924     if (!bdrv_is_encrypted(bs))
6925         return 0;
6926
6927     term_printf("%s is encrypted.\n", name);
6928     for(i = 0; i < 3; i++) {
6929         monitor_readline("Password: ", 1, password, sizeof(password));
6930         if (bdrv_set_key(bs, password) == 0)
6931             return 0;
6932         term_printf("invalid password\n");
6933     }
6934     return -EPERM;
6935 }
6936
6937 static BlockDriverState *get_bdrv(int index)
6938 {
6939     BlockDriverState *bs;
6940
6941     if (index < 4) {
6942         bs = bs_table[index];
6943     } else if (index < 6) {
6944         bs = fd_table[index - 4];
6945     } else {
6946         bs = NULL;
6947     }
6948     return bs;
6949 }
6950
6951 static void read_passwords(void)
6952 {
6953     BlockDriverState *bs;
6954     int i;
6955
6956     for(i = 0; i < 6; i++) {
6957         bs = get_bdrv(i);
6958         if (bs)
6959             qemu_key_check(bs, bdrv_get_device_name(bs));
6960     }
6961 }
6962
6963 /* XXX: currently we cannot use simultaneously different CPUs */
6964 void register_machines(void)
6965 {
6966 #if defined(TARGET_I386)
6967     qemu_register_machine(&pc_machine);
6968     qemu_register_machine(&isapc_machine);
6969 #elif defined(TARGET_PPC)
6970     qemu_register_machine(&heathrow_machine);
6971     qemu_register_machine(&core99_machine);
6972     qemu_register_machine(&prep_machine);
6973     qemu_register_machine(&ref405ep_machine);
6974     qemu_register_machine(&taihu_machine);
6975 #elif defined(TARGET_MIPS)
6976     qemu_register_machine(&mips_machine);
6977     qemu_register_machine(&mips_malta_machine);
6978     qemu_register_machine(&mips_pica61_machine);
6979 #elif defined(TARGET_SPARC)
6980 #ifdef TARGET_SPARC64
6981     qemu_register_machine(&sun4u_machine);
6982 #else
6983     qemu_register_machine(&ss5_machine);
6984     qemu_register_machine(&ss10_machine);
6985 #endif
6986 #elif defined(TARGET_ARM)
6987     qemu_register_machine(&integratorcp_machine);
6988     qemu_register_machine(&versatilepb_machine);
6989     qemu_register_machine(&versatileab_machine);
6990     qemu_register_machine(&realview_machine);
6991     qemu_register_machine(&akitapda_machine);
6992     qemu_register_machine(&spitzpda_machine);
6993     qemu_register_machine(&borzoipda_machine);
6994     qemu_register_machine(&terrierpda_machine);
6995 #elif defined(TARGET_SH4)
6996     qemu_register_machine(&shix_machine);
6997 #elif defined(TARGET_ALPHA)
6998     /* XXX: TODO */
6999 #elif defined(TARGET_M68K)
7000     qemu_register_machine(&mcf5208evb_machine);
7001     qemu_register_machine(&an5206_machine);
7002 #else
7003 #error unsupported CPU
7004 #endif
7005 }
7006
7007 #ifdef HAS_AUDIO
7008 struct soundhw soundhw[] = {
7009 #ifdef HAS_AUDIO_CHOICE
7010 #ifdef TARGET_I386
7011     {
7012         "pcspk",
7013         "PC speaker",
7014         0,
7015         1,
7016         { .init_isa = pcspk_audio_init }
7017     },
7018 #endif
7019     {
7020         "sb16",
7021         "Creative Sound Blaster 16",
7022         0,
7023         1,
7024         { .init_isa = SB16_init }
7025     },
7026
7027 #ifdef CONFIG_ADLIB
7028     {
7029         "adlib",
7030 #ifdef HAS_YMF262
7031         "Yamaha YMF262 (OPL3)",
7032 #else
7033         "Yamaha YM3812 (OPL2)",
7034 #endif
7035         0,
7036         1,
7037         { .init_isa = Adlib_init }
7038     },
7039 #endif
7040
7041 #ifdef CONFIG_GUS
7042     {
7043         "gus",
7044         "Gravis Ultrasound GF1",
7045         0,
7046         1,
7047         { .init_isa = GUS_init }
7048     },
7049 #endif
7050
7051     {
7052         "es1370",
7053         "ENSONIQ AudioPCI ES1370",
7054         0,
7055         0,
7056         { .init_pci = es1370_init }
7057     },
7058 #endif
7059
7060     { NULL, NULL, 0, 0, { NULL } }
7061 };
7062
7063 static void select_soundhw (const char *optarg)
7064 {
7065     struct soundhw *c;
7066
7067     if (*optarg == '?') {
7068     show_valid_cards:
7069
7070         printf ("Valid sound card names (comma separated):\n");
7071         for (c = soundhw; c->name; ++c) {
7072             printf ("%-11s %s\n", c->name, c->descr);
7073         }
7074         printf ("\n-soundhw all will enable all of the above\n");
7075         exit (*optarg != '?');
7076     }
7077     else {
7078         size_t l;
7079         const char *p;
7080         char *e;
7081         int bad_card = 0;
7082
7083         if (!strcmp (optarg, "all")) {
7084             for (c = soundhw; c->name; ++c) {
7085                 c->enabled = 1;
7086             }
7087             return;
7088         }
7089
7090         p = optarg;
7091         while (*p) {
7092             e = strchr (p, ',');
7093             l = !e ? strlen (p) : (size_t) (e - p);
7094
7095             for (c = soundhw; c->name; ++c) {
7096                 if (!strncmp (c->name, p, l)) {
7097                     c->enabled = 1;
7098                     break;
7099                 }
7100             }
7101
7102             if (!c->name) {
7103                 if (l > 80) {
7104                     fprintf (stderr,
7105                              "Unknown sound card name (too big to show)\n");
7106                 }
7107                 else {
7108                     fprintf (stderr, "Unknown sound card name `%.*s'\n",
7109                              (int) l, p);
7110                 }
7111                 bad_card = 1;
7112             }
7113             p += l + (e != NULL);
7114         }
7115
7116         if (bad_card)
7117             goto show_valid_cards;
7118     }
7119 }
7120 #endif
7121
7122 #ifdef _WIN32
7123 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7124 {
7125     exit(STATUS_CONTROL_C_EXIT);
7126     return TRUE;
7127 }
7128 #endif
7129
7130 #define MAX_NET_CLIENTS 32
7131
7132 int main(int argc, char **argv)
7133 {
7134 #ifdef CONFIG_GDBSTUB
7135     int use_gdbstub;
7136     const char *gdbstub_port;
7137 #endif
7138     int i, cdrom_index, pflash_index;
7139     int snapshot, linux_boot;
7140     const char *initrd_filename;
7141     const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7142     const char *pflash_filename[MAX_PFLASH];
7143     const char *sd_filename;
7144     const char *mtd_filename;
7145     const char *kernel_filename, *kernel_cmdline;
7146     DisplayState *ds = &display_state;
7147     int cyls, heads, secs, translation;
7148     char net_clients[MAX_NET_CLIENTS][256];
7149     int nb_net_clients;
7150     int optind;
7151     const char *r, *optarg;
7152     CharDriverState *monitor_hd;
7153     char monitor_device[128];
7154     char serial_devices[MAX_SERIAL_PORTS][128];
7155     int serial_device_index;
7156     char parallel_devices[MAX_PARALLEL_PORTS][128];
7157     int parallel_device_index;
7158     const char *loadvm = NULL;
7159     QEMUMachine *machine;
7160     const char *cpu_model;
7161     char usb_devices[MAX_USB_CMDLINE][128];
7162     int usb_devices_index;
7163     int fds[2];
7164     const char *pid_file = NULL;
7165     VLANState *vlan;
7166
7167     LIST_INIT (&vm_change_state_head);
7168 #ifndef _WIN32
7169     {
7170         struct sigaction act;
7171         sigfillset(&act.sa_mask);
7172         act.sa_flags = 0;
7173         act.sa_handler = SIG_IGN;
7174         sigaction(SIGPIPE, &act, NULL);
7175     }
7176 #else
7177     SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7178     /* Note: cpu_interrupt() is currently not SMP safe, so we force
7179        QEMU to run on a single CPU */
7180     {
7181         HANDLE h;
7182         DWORD mask, smask;
7183         int i;
7184         h = GetCurrentProcess();
7185         if (GetProcessAffinityMask(h, &mask, &smask)) {
7186             for(i = 0; i < 32; i++) {
7187                 if (mask & (1 << i))
7188                     break;
7189             }
7190             if (i != 32) {
7191                 mask = 1 << i;
7192                 SetProcessAffinityMask(h, mask);
7193             }
7194         }
7195     }
7196 #endif
7197
7198     register_machines();
7199     machine = first_machine;
7200     cpu_model = NULL;
7201     initrd_filename = NULL;
7202     for(i = 0; i < MAX_FD; i++)
7203         fd_filename[i] = NULL;
7204     for(i = 0; i < MAX_DISKS; i++)
7205         hd_filename[i] = NULL;
7206     for(i = 0; i < MAX_PFLASH; i++)
7207         pflash_filename[i] = NULL;
7208     pflash_index = 0;
7209     sd_filename = NULL;
7210     mtd_filename = NULL;
7211     ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7212     vga_ram_size = VGA_RAM_SIZE;
7213 #ifdef CONFIG_GDBSTUB
7214     use_gdbstub = 0;
7215     gdbstub_port = DEFAULT_GDBSTUB_PORT;
7216 #endif
7217     snapshot = 0;
7218     nographic = 0;
7219     kernel_filename = NULL;
7220     kernel_cmdline = "";
7221 #ifdef TARGET_PPC
7222     cdrom_index = 1;
7223 #else
7224     cdrom_index = 2;
7225 #endif
7226     cyls = heads = secs = 0;
7227     translation = BIOS_ATA_TRANSLATION_AUTO;
7228     pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7229
7230     pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7231     for(i = 1; i < MAX_SERIAL_PORTS; i++)
7232         serial_devices[i][0] = '\0';
7233     serial_device_index = 0;
7234     
7235     pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7236     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7237         parallel_devices[i][0] = '\0';
7238     parallel_device_index = 0;
7239     
7240     usb_devices_index = 0;
7241     
7242     nb_net_clients = 0;
7243
7244     nb_nics = 0;
7245     /* default mac address of the first network interface */
7246     
7247     optind = 1;
7248     for(;;) {
7249         if (optind >= argc)
7250             break;
7251         r = argv[optind];
7252         if (r[0] != '-') {
7253             hd_filename[0] = argv[optind++];
7254         } else {
7255             const QEMUOption *popt;
7256
7257             optind++;
7258             /* Treat --foo the same as -foo.  */
7259             if (r[1] == '-')
7260                 r++;
7261             popt = qemu_options;
7262             for(;;) {
7263                 if (!popt->name) {
7264                     fprintf(stderr, "%s: invalid option -- '%s'\n", 
7265                             argv[0], r);
7266                     exit(1);
7267                 }
7268                 if (!strcmp(popt->name, r + 1))
7269                     break;
7270                 popt++;
7271             }
7272             if (popt->flags & HAS_ARG) {
7273                 if (optind >= argc) {
7274                     fprintf(stderr, "%s: option '%s' requires an argument\n",
7275                             argv[0], r);
7276                     exit(1);
7277                 }
7278                 optarg = argv[optind++];
7279             } else {
7280                 optarg = NULL;
7281             }
7282
7283             switch(popt->index) {
7284             case QEMU_OPTION_M:
7285                 machine = find_machine(optarg);
7286                 if (!machine) {
7287                     QEMUMachine *m;
7288                     printf("Supported machines are:\n");
7289                     for(m = first_machine; m != NULL; m = m->next) {
7290                         printf("%-10s %s%s\n",
7291                                m->name, m->desc, 
7292                                m == first_machine ? " (default)" : "");
7293                     }
7294                     exit(*optarg != '?');
7295                 }
7296                 break;
7297             case QEMU_OPTION_cpu:
7298                 /* hw initialization will check this */
7299                 if (*optarg == '?') {
7300 #if defined(TARGET_PPC)
7301                     ppc_cpu_list(stdout, &fprintf);
7302 #elif defined(TARGET_ARM)
7303                     arm_cpu_list();
7304 #elif defined(TARGET_MIPS)
7305                     mips_cpu_list(stdout, &fprintf);
7306 #elif defined(TARGET_SPARC)
7307                     sparc_cpu_list(stdout, &fprintf);
7308 #endif
7309                     exit(0);
7310                 } else {
7311                     cpu_model = optarg;
7312                 }
7313                 break;
7314             case QEMU_OPTION_initrd:
7315                 initrd_filename = optarg;
7316                 break;
7317             case QEMU_OPTION_hda:
7318             case QEMU_OPTION_hdb:
7319             case QEMU_OPTION_hdc:
7320             case QEMU_OPTION_hdd:
7321                 {
7322                     int hd_index;
7323                     hd_index = popt->index - QEMU_OPTION_hda;
7324                     hd_filename[hd_index] = optarg;
7325                     if (hd_index == cdrom_index)
7326                         cdrom_index = -1;
7327                 }
7328                 break;
7329             case QEMU_OPTION_mtdblock:
7330                 mtd_filename = optarg;
7331                 break;
7332             case QEMU_OPTION_sd:
7333                 sd_filename = optarg;
7334                 break;
7335             case QEMU_OPTION_pflash:
7336                 if (pflash_index >= MAX_PFLASH) {
7337                     fprintf(stderr, "qemu: too many parallel flash images\n");
7338                     exit(1);
7339                 }
7340                 pflash_filename[pflash_index++] = optarg;
7341                 break;
7342             case QEMU_OPTION_snapshot:
7343                 snapshot = 1;
7344                 break;
7345             case QEMU_OPTION_hdachs:
7346                 {
7347                     const char *p;
7348                     p = optarg;
7349                     cyls = strtol(p, (char **)&p, 0);
7350                     if (cyls < 1 || cyls > 16383)
7351                         goto chs_fail;
7352                     if (*p != ',')
7353                         goto chs_fail;
7354                     p++;
7355                     heads = strtol(p, (char **)&p, 0);
7356                     if (heads < 1 || heads > 16)
7357                         goto chs_fail;
7358                     if (*p != ',')
7359                         goto chs_fail;
7360                     p++;
7361                     secs = strtol(p, (char **)&p, 0);
7362                     if (secs < 1 || secs > 63)
7363                         goto chs_fail;
7364                     if (*p == ',') {
7365                         p++;
7366                         if (!strcmp(p, "none"))
7367                             translation = BIOS_ATA_TRANSLATION_NONE;
7368                         else if (!strcmp(p, "lba"))
7369                             translation = BIOS_ATA_TRANSLATION_LBA;
7370                         else if (!strcmp(p, "auto"))
7371                             translation = BIOS_ATA_TRANSLATION_AUTO;
7372                         else
7373                             goto chs_fail;
7374                     } else if (*p != '\0') {
7375                     chs_fail:
7376                         fprintf(stderr, "qemu: invalid physical CHS format\n");
7377                         exit(1);
7378                     }
7379                 }
7380                 break;
7381             case QEMU_OPTION_nographic:
7382                 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7383                 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7384                 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7385                 nographic = 1;
7386                 break;
7387             case QEMU_OPTION_portrait:
7388                 graphic_rotate = 1;
7389                 break;
7390             case QEMU_OPTION_kernel:
7391                 kernel_filename = optarg;
7392                 break;
7393             case QEMU_OPTION_append:
7394                 kernel_cmdline = optarg;
7395                 break;
7396             case QEMU_OPTION_cdrom:
7397                 if (cdrom_index >= 0) {
7398                     hd_filename[cdrom_index] = optarg;
7399                 }
7400                 break;
7401             case QEMU_OPTION_boot:
7402                 boot_device = optarg[0];
7403                 if (boot_device != 'a' && 
7404 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7405                     // Network boot
7406                     boot_device != 'n' &&
7407 #endif
7408                     boot_device != 'c' && boot_device != 'd') {
7409                     fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7410                     exit(1);
7411                 }
7412                 break;
7413             case QEMU_OPTION_fda:
7414                 fd_filename[0] = optarg;
7415                 break;
7416             case QEMU_OPTION_fdb:
7417                 fd_filename[1] = optarg;
7418                 break;
7419 #ifdef TARGET_I386
7420             case QEMU_OPTION_no_fd_bootchk:
7421                 fd_bootchk = 0;
7422                 break;
7423 #endif
7424             case QEMU_OPTION_no_code_copy:
7425                 code_copy_enabled = 0;
7426                 break;
7427             case QEMU_OPTION_net:
7428                 if (nb_net_clients >= MAX_NET_CLIENTS) {
7429                     fprintf(stderr, "qemu: too many network clients\n");
7430                     exit(1);
7431                 }
7432                 pstrcpy(net_clients[nb_net_clients],
7433                         sizeof(net_clients[0]),
7434                         optarg);
7435                 nb_net_clients++;
7436                 break;
7437 #ifdef CONFIG_SLIRP
7438             case QEMU_OPTION_tftp:
7439                 tftp_prefix = optarg;
7440                 break;
7441             case QEMU_OPTION_bootp:
7442                 bootp_filename = optarg;
7443                 break;
7444 #ifndef _WIN32
7445             case QEMU_OPTION_smb:
7446                 net_slirp_smb(optarg);
7447                 break;
7448 #endif
7449             case QEMU_OPTION_redir:
7450                 net_slirp_redir(optarg);                
7451                 break;
7452 #endif
7453 #ifdef HAS_AUDIO
7454             case QEMU_OPTION_audio_help:
7455                 AUD_help ();
7456                 exit (0);
7457                 break;
7458             case QEMU_OPTION_soundhw:
7459                 select_soundhw (optarg);
7460                 break;
7461 #endif
7462             case QEMU_OPTION_h:
7463                 help(0);
7464                 break;
7465             case QEMU_OPTION_m:
7466                 ram_size = atoi(optarg) * 1024 * 1024;
7467                 if (ram_size <= 0)
7468                     help(1);
7469                 if (ram_size > PHYS_RAM_MAX_SIZE) {
7470                     fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7471                             PHYS_RAM_MAX_SIZE / (1024 * 1024));
7472                     exit(1);
7473                 }
7474                 break;
7475             case QEMU_OPTION_d:
7476                 {
7477                     int mask;
7478                     CPULogItem *item;
7479                     
7480                     mask = cpu_str_to_log_mask(optarg);
7481                     if (!mask) {
7482                         printf("Log items (comma separated):\n");
7483                     for(item = cpu_log_items; item->mask != 0; item++) {
7484                         printf("%-10s %s\n", item->name, item->help);
7485                     }
7486                     exit(1);
7487                     }
7488                     cpu_set_log(mask);
7489                 }
7490                 break;
7491 #ifdef CONFIG_GDBSTUB
7492             case QEMU_OPTION_s:
7493                 use_gdbstub = 1;
7494                 break;
7495             case QEMU_OPTION_p:
7496                 gdbstub_port = optarg;
7497                 break;
7498 #endif
7499             case QEMU_OPTION_L:
7500                 bios_dir = optarg;
7501                 break;
7502             case QEMU_OPTION_S:
7503                 autostart = 0;
7504                 break;
7505             case QEMU_OPTION_k:
7506                 keyboard_layout = optarg;
7507                 break;
7508             case QEMU_OPTION_localtime:
7509                 rtc_utc = 0;
7510                 break;
7511             case QEMU_OPTION_cirrusvga:
7512                 cirrus_vga_enabled = 1;
7513                 vmsvga_enabled = 0;
7514                 break;
7515             case QEMU_OPTION_vmsvga:
7516                 cirrus_vga_enabled = 0;
7517                 vmsvga_enabled = 1;
7518                 break;
7519             case QEMU_OPTION_std_vga:
7520                 cirrus_vga_enabled = 0;
7521                 vmsvga_enabled = 0;
7522                 break;
7523             case QEMU_OPTION_g:
7524                 {
7525                     const char *p;
7526                     int w, h, depth;
7527                     p = optarg;
7528                     w = strtol(p, (char **)&p, 10);
7529                     if (w <= 0) {
7530                     graphic_error:
7531                         fprintf(stderr, "qemu: invalid resolution or depth\n");
7532                         exit(1);
7533                     }
7534                     if (*p != 'x')
7535                         goto graphic_error;
7536                     p++;
7537                     h = strtol(p, (char **)&p, 10);
7538                     if (h <= 0)
7539                         goto graphic_error;
7540                     if (*p == 'x') {
7541                         p++;
7542                         depth = strtol(p, (char **)&p, 10);
7543                         if (depth != 8 && depth != 15 && depth != 16 && 
7544                             depth != 24 && depth != 32)
7545                             goto graphic_error;
7546                     } else if (*p == '\0') {
7547                         depth = graphic_depth;
7548                     } else {
7549                         goto graphic_error;
7550                     }
7551                     
7552                     graphic_width = w;
7553                     graphic_height = h;
7554                     graphic_depth = depth;
7555                 }
7556                 break;
7557             case QEMU_OPTION_echr:
7558                 {
7559                     char *r;
7560                     term_escape_char = strtol(optarg, &r, 0);
7561                     if (r == optarg)
7562                         printf("Bad argument to echr\n");
7563                     break;
7564                 }
7565             case QEMU_OPTION_monitor:
7566                 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7567                 break;
7568             case QEMU_OPTION_serial:
7569                 if (serial_device_index >= MAX_SERIAL_PORTS) {
7570                     fprintf(stderr, "qemu: too many serial ports\n");
7571                     exit(1);
7572                 }
7573                 pstrcpy(serial_devices[serial_device_index], 
7574                         sizeof(serial_devices[0]), optarg);
7575                 serial_device_index++;
7576                 break;
7577             case QEMU_OPTION_parallel:
7578                 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7579                     fprintf(stderr, "qemu: too many parallel ports\n");
7580                     exit(1);
7581                 }
7582                 pstrcpy(parallel_devices[parallel_device_index], 
7583                         sizeof(parallel_devices[0]), optarg);
7584                 parallel_device_index++;
7585                 break;
7586             case QEMU_OPTION_loadvm:
7587                 loadvm = optarg;
7588                 break;
7589             case QEMU_OPTION_full_screen:
7590                 full_screen = 1;
7591                 break;
7592 #ifdef CONFIG_SDL
7593             case QEMU_OPTION_no_frame:
7594                 no_frame = 1;
7595                 break;
7596             case QEMU_OPTION_alt_grab:
7597                 alt_grab = 1;
7598                 break;
7599             case QEMU_OPTION_no_quit:
7600                 no_quit = 1;
7601                 break;
7602 #endif
7603             case QEMU_OPTION_pidfile:
7604                 pid_file = optarg;
7605                 break;
7606 #ifdef TARGET_I386
7607             case QEMU_OPTION_win2k_hack:
7608                 win2k_install_hack = 1;
7609                 break;
7610 #endif
7611 #ifdef USE_KQEMU
7612             case QEMU_OPTION_no_kqemu:
7613                 kqemu_allowed = 0;
7614                 break;
7615             case QEMU_OPTION_kernel_kqemu:
7616                 kqemu_allowed = 2;
7617                 break;
7618 #endif
7619             case QEMU_OPTION_usb:
7620                 usb_enabled = 1;
7621                 break;
7622             case QEMU_OPTION_usbdevice:
7623                 usb_enabled = 1;
7624                 if (usb_devices_index >= MAX_USB_CMDLINE) {
7625                     fprintf(stderr, "Too many USB devices\n");
7626                     exit(1);
7627                 }
7628                 pstrcpy(usb_devices[usb_devices_index],
7629                         sizeof(usb_devices[usb_devices_index]),
7630                         optarg);
7631                 usb_devices_index++;
7632                 break;
7633             case QEMU_OPTION_smp:
7634                 smp_cpus = atoi(optarg);
7635                 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7636                     fprintf(stderr, "Invalid number of CPUs\n");
7637                     exit(1);
7638                 }
7639                 break;
7640             case QEMU_OPTION_vnc:
7641                 vnc_display = optarg;
7642                 break;
7643             case QEMU_OPTION_no_acpi:
7644                 acpi_enabled = 0;
7645                 break;
7646             case QEMU_OPTION_no_reboot:
7647                 no_reboot = 1;
7648                 break;
7649             case QEMU_OPTION_show_cursor:
7650                 cursor_hide = 0;
7651                 break;
7652             case QEMU_OPTION_daemonize:
7653                 daemonize = 1;
7654                 break;
7655             case QEMU_OPTION_option_rom:
7656                 if (nb_option_roms >= MAX_OPTION_ROMS) {
7657                     fprintf(stderr, "Too many option ROMs\n");
7658                     exit(1);
7659                 }
7660                 option_rom[nb_option_roms] = optarg;
7661                 nb_option_roms++;
7662                 break;
7663             case QEMU_OPTION_semihosting:
7664                 semihosting_enabled = 1;
7665                 break;
7666             case QEMU_OPTION_name:
7667                 qemu_name = optarg;
7668                 break;
7669 #ifdef TARGET_SPARC
7670             case QEMU_OPTION_prom_env:
7671                 if (nb_prom_envs >= MAX_PROM_ENVS) {
7672                     fprintf(stderr, "Too many prom variables\n");
7673                     exit(1);
7674                 }
7675                 prom_envs[nb_prom_envs] = optarg;
7676                 nb_prom_envs++;
7677                 break;
7678 #endif
7679             }
7680         }
7681     }
7682
7683 #ifndef _WIN32
7684     if (daemonize && !nographic && vnc_display == NULL) {
7685         fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7686         daemonize = 0;
7687     }
7688
7689     if (daemonize) {
7690         pid_t pid;
7691
7692         if (pipe(fds) == -1)
7693             exit(1);
7694
7695         pid = fork();
7696         if (pid > 0) {
7697             uint8_t status;
7698             ssize_t len;
7699
7700             close(fds[1]);
7701
7702         again:
7703             len = read(fds[0], &status, 1);
7704             if (len == -1 && (errno == EINTR))
7705                 goto again;
7706
7707             if (len != 1)
7708                 exit(1);
7709             else if (status == 1) {
7710                 fprintf(stderr, "Could not acquire pidfile\n");
7711                 exit(1);
7712             } else
7713                 exit(0);
7714         } else if (pid < 0)
7715             exit(1);
7716
7717         setsid();
7718
7719         pid = fork();
7720         if (pid > 0)
7721             exit(0);
7722         else if (pid < 0)
7723             exit(1);
7724
7725         umask(027);
7726         chdir("/");
7727
7728         signal(SIGTSTP, SIG_IGN);
7729         signal(SIGTTOU, SIG_IGN);
7730         signal(SIGTTIN, SIG_IGN);
7731     }
7732 #endif
7733
7734     if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7735         if (daemonize) {
7736             uint8_t status = 1;
7737             write(fds[1], &status, 1);
7738         } else
7739             fprintf(stderr, "Could not acquire pid file\n");
7740         exit(1);
7741     }
7742
7743 #ifdef USE_KQEMU
7744     if (smp_cpus > 1)
7745         kqemu_allowed = 0;
7746 #endif
7747     linux_boot = (kernel_filename != NULL);
7748
7749     if (!linux_boot &&
7750         boot_device != 'n' &&
7751         hd_filename[0] == '\0' && 
7752         (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7753         fd_filename[0] == '\0')
7754         help(1);
7755
7756     /* boot to floppy or the default cd if no hard disk defined yet */
7757     if (hd_filename[0] == '\0' && boot_device == 'c') {
7758         if (fd_filename[0] != '\0')
7759             boot_device = 'a';
7760         else
7761             boot_device = 'd';
7762     }
7763
7764     setvbuf(stdout, NULL, _IOLBF, 0);
7765     
7766     init_timers();
7767     init_timer_alarm();
7768     qemu_aio_init();
7769
7770 #ifdef _WIN32
7771     socket_init();
7772 #endif
7773
7774     /* init network clients */
7775     if (nb_net_clients == 0) {
7776         /* if no clients, we use a default config */
7777         pstrcpy(net_clients[0], sizeof(net_clients[0]),
7778                 "nic");
7779         pstrcpy(net_clients[1], sizeof(net_clients[0]),
7780                 "user");
7781         nb_net_clients = 2;
7782     }
7783
7784     for(i = 0;i < nb_net_clients; i++) {
7785         if (net_client_init(net_clients[i]) < 0)
7786             exit(1);
7787     }
7788     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7789         if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7790             continue;
7791         if (vlan->nb_guest_devs == 0) {
7792             fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7793             exit(1);
7794         }
7795         if (vlan->nb_host_devs == 0)
7796             fprintf(stderr,
7797                     "Warning: vlan %d is not connected to host network\n",
7798                     vlan->id);
7799     }
7800
7801 #ifdef TARGET_I386
7802     if (boot_device == 'n') {
7803         for (i = 0; i < nb_nics; i++) {
7804             const char *model = nd_table[i].model;
7805             char buf[1024];
7806             if (model == NULL)
7807                 model = "ne2k_pci";
7808             snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7809             if (get_image_size(buf) > 0) {
7810                 option_rom[nb_option_roms] = strdup(buf);
7811                 nb_option_roms++;
7812                 break;
7813             }
7814         }
7815         if (i == nb_nics) {
7816             fprintf(stderr, "No valid PXE rom found for network device\n");
7817             exit(1);
7818         }
7819         boot_device = 'c'; /* to prevent confusion by the BIOS */
7820     }
7821 #endif
7822
7823     /* init the memory */
7824     phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7825
7826     phys_ram_base = qemu_vmalloc(phys_ram_size);
7827     if (!phys_ram_base) {
7828         fprintf(stderr, "Could not allocate physical memory\n");
7829         exit(1);
7830     }
7831
7832     /* we always create the cdrom drive, even if no disk is there */
7833     bdrv_init();
7834     if (cdrom_index >= 0) {
7835         bs_table[cdrom_index] = bdrv_new("cdrom");
7836         bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7837     }
7838
7839     /* open the virtual block devices */
7840     for(i = 0; i < MAX_DISKS; i++) {
7841         if (hd_filename[i]) {
7842             if (!bs_table[i]) {
7843                 char buf[64];
7844                 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7845                 bs_table[i] = bdrv_new(buf);
7846             }
7847             if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7848                 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7849                         hd_filename[i]);
7850                 exit(1);
7851             }
7852             if (i == 0 && cyls != 0) {
7853                 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7854                 bdrv_set_translation_hint(bs_table[i], translation);
7855             }
7856         }
7857     }
7858
7859     /* we always create at least one floppy disk */
7860     fd_table[0] = bdrv_new("fda");
7861     bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7862
7863     for(i = 0; i < MAX_FD; i++) {
7864         if (fd_filename[i]) {
7865             if (!fd_table[i]) {
7866                 char buf[64];
7867                 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7868                 fd_table[i] = bdrv_new(buf);
7869                 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7870             }
7871             if (fd_filename[i][0] != '\0') {
7872                 if (bdrv_open(fd_table[i], fd_filename[i],
7873                               snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7874                     fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7875                             fd_filename[i]);
7876                     exit(1);
7877                 }
7878             }
7879         }
7880     }
7881
7882     /* Open the virtual parallel flash block devices */
7883     for(i = 0; i < MAX_PFLASH; i++) {
7884         if (pflash_filename[i]) {
7885             if (!pflash_table[i]) {
7886                 char buf[64];
7887                 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7888                 pflash_table[i] = bdrv_new(buf);
7889             }
7890             if (bdrv_open(pflash_table[i], pflash_filename[i],
7891                           snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7892                 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7893                         pflash_filename[i]);
7894                 exit(1);
7895             }
7896         }
7897     }
7898
7899     sd_bdrv = bdrv_new ("sd");
7900     /* FIXME: This isn't really a floppy, but it's a reasonable
7901        approximation.  */
7902     bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7903     if (sd_filename) {
7904         if (bdrv_open(sd_bdrv, sd_filename,
7905                       snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7906             fprintf(stderr, "qemu: could not open SD card image %s\n",
7907                     sd_filename);
7908         } else
7909             qemu_key_check(sd_bdrv, sd_filename);
7910     }
7911
7912     if (mtd_filename) {
7913         mtd_bdrv = bdrv_new ("mtd");
7914         if (bdrv_open(mtd_bdrv, mtd_filename,
7915                       snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7916             qemu_key_check(mtd_bdrv, mtd_filename)) {
7917             fprintf(stderr, "qemu: could not open Flash image %s\n",
7918                     mtd_filename);
7919             bdrv_delete(mtd_bdrv);
7920             mtd_bdrv = 0;
7921         }
7922     }
7923
7924     register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7925     register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7926
7927     init_ioports();
7928
7929     /* terminal init */
7930     memset(&display_state, 0, sizeof(display_state));
7931     if (nographic) {
7932         /* nearly nothing to do */
7933         dumb_display_init(ds);
7934     } else if (vnc_display != NULL) {
7935         vnc_display_init(ds, vnc_display);
7936     } else {
7937 #if defined(CONFIG_SDL)
7938         sdl_display_init(ds, full_screen, no_frame);
7939 #elif defined(CONFIG_COCOA)
7940         cocoa_display_init(ds, full_screen);
7941 #endif
7942     }
7943
7944     /* Maintain compatibility with multiple stdio monitors */
7945     if (!strcmp(monitor_device,"stdio")) {
7946         for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7947             if (!strcmp(serial_devices[i],"mon:stdio")) {
7948                 monitor_device[0] = '\0';
7949                 break;
7950             } else if (!strcmp(serial_devices[i],"stdio")) {
7951                 monitor_device[0] = '\0';
7952                 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7953                 break;
7954             }
7955         }
7956     }
7957     if (monitor_device[0] != '\0') {
7958         monitor_hd = qemu_chr_open(monitor_device);
7959         if (!monitor_hd) {
7960             fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7961             exit(1);
7962         }
7963         monitor_init(monitor_hd, !nographic);
7964     }
7965
7966     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7967         const char *devname = serial_devices[i];
7968         if (devname[0] != '\0' && strcmp(devname, "none")) {
7969             serial_hds[i] = qemu_chr_open(devname);
7970             if (!serial_hds[i]) {
7971                 fprintf(stderr, "qemu: could not open serial device '%s'\n", 
7972                         devname);
7973                 exit(1);
7974             }
7975             if (strstart(devname, "vc", 0))
7976                 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7977         }
7978     }
7979
7980     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7981         const char *devname = parallel_devices[i];
7982         if (devname[0] != '\0' && strcmp(devname, "none")) {
7983             parallel_hds[i] = qemu_chr_open(devname);
7984             if (!parallel_hds[i]) {
7985                 fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
7986                         devname);
7987                 exit(1);
7988             }
7989             if (strstart(devname, "vc", 0))
7990                 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7991         }
7992     }
7993
7994     machine->init(ram_size, vga_ram_size, boot_device,
7995                   ds, fd_filename, snapshot,
7996                   kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7997
7998     /* init USB devices */
7999     if (usb_enabled) {
8000         for(i = 0; i < usb_devices_index; i++) {
8001             if (usb_device_add(usb_devices[i]) < 0) {
8002                 fprintf(stderr, "Warning: could not add USB device %s\n",
8003                         usb_devices[i]);
8004             }
8005         }
8006     }
8007
8008     if (display_state.dpy_refresh) {
8009         display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8010         qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8011     }
8012
8013 #ifdef CONFIG_GDBSTUB
8014     if (use_gdbstub) {
8015         /* XXX: use standard host:port notation and modify options
8016            accordingly. */
8017         if (gdbserver_start(gdbstub_port) < 0) {
8018             fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8019                     gdbstub_port);
8020             exit(1);
8021         }
8022     }
8023 #endif
8024
8025     if (loadvm)
8026         do_loadvm(loadvm);
8027
8028     {
8029         /* XXX: simplify init */
8030         read_passwords();
8031         if (autostart) {
8032             vm_start();
8033         }
8034     }
8035
8036     if (daemonize) {
8037         uint8_t status = 0;
8038         ssize_t len;
8039         int fd;
8040
8041     again1:
8042         len = write(fds[1], &status, 1);
8043         if (len == -1 && (errno == EINTR))
8044             goto again1;
8045
8046         if (len != 1)
8047             exit(1);
8048
8049         TFR(fd = open("/dev/null", O_RDWR));
8050         if (fd == -1)
8051             exit(1);
8052
8053         dup2(fd, 0);
8054         dup2(fd, 1);
8055         dup2(fd, 2);
8056
8057         close(fd);
8058     }
8059
8060     main_loop();
8061     quit_timers();
8062     return 0;
8063 }