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