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