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