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