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