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