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