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