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