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