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