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