Fix some build issues for BSD.
[qemu] / vl.c
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "block.h"
40 #include "audio/audio.h"
41 #include "migration.h"
42 #include "kvm.h"
43
44 #include <unistd.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <time.h>
48 #include <errno.h>
49 #include <sys/time.h>
50 #include <zlib.h>
51
52 #ifndef _WIN32
53 #include <sys/times.h>
54 #include <sys/wait.h>
55 #include <termios.h>
56 #include <sys/mman.h>
57 #include <sys/ioctl.h>
58 #include <sys/resource.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <net/if.h>
62 #if defined(__NetBSD__)
63 #include <net/if_tap.h>
64 #endif
65 #ifdef __linux__
66 #include <linux/if_tun.h>
67 #endif
68 #include <arpa/inet.h>
69 #include <dirent.h>
70 #include <netdb.h>
71 #include <sys/select.h>
72 #ifdef _BSD
73 #include <sys/stat.h>
74 #ifdef __FreeBSD__
75 #include <libutil.h>
76 #else
77 #include <util.h>
78 #endif
79 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
80 #include <freebsd/stdlib.h>
81 #else
82 #ifdef __linux__
83 #include <pty.h>
84 #include <malloc.h>
85 #include <linux/rtc.h>
86
87 /* For the benefit of older linux systems which don't supply it,
88    we use a local copy of hpet.h. */
89 /* #include <linux/hpet.h> */
90 #include "hpet.h"
91
92 #include <linux/ppdev.h>
93 #include <linux/parport.h>
94 #endif
95 #ifdef __sun__
96 #include <sys/stat.h>
97 #include <sys/ethernet.h>
98 #include <sys/sockio.h>
99 #include <netinet/arp.h>
100 #include <netinet/in.h>
101 #include <netinet/in_systm.h>
102 #include <netinet/ip.h>
103 #include <netinet/ip_icmp.h> // must come after ip.h
104 #include <netinet/udp.h>
105 #include <netinet/tcp.h>
106 #include <net/if.h>
107 #include <syslog.h>
108 #include <stropts.h>
109 #endif
110 #endif
111 #endif
112
113 #include "qemu_socket.h"
114
115 #if defined(CONFIG_SLIRP)
116 #include "libslirp.h"
117 #endif
118
119 #if defined(__OpenBSD__)
120 #include <util.h>
121 #endif
122
123 #if defined(CONFIG_VDE)
124 #include <libvdeplug.h>
125 #endif
126
127 #ifdef _WIN32
128 #include <malloc.h>
129 #include <sys/timeb.h>
130 #include <mmsystem.h>
131 #define getopt_long_only getopt_long
132 #define memalign(align, size) malloc(size)
133 #endif
134
135 #ifdef CONFIG_SDL
136 #ifdef __APPLE__
137 #include <SDL/SDL.h>
138 #endif
139 #endif /* CONFIG_SDL */
140
141 #ifdef CONFIG_COCOA
142 #undef main
143 #define main qemu_main
144 #endif /* CONFIG_COCOA */
145
146 #include "disas.h"
147
148 #include "exec-all.h"
149
150 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
151 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
152 #ifdef __sun__
153 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
154 #else
155 #define SMBD_COMMAND "/usr/sbin/smbd"
156 #endif
157
158 //#define DEBUG_UNUSED_IOPORT
159 //#define DEBUG_IOPORT
160 //#define DEBUG_NET
161 //#define DEBUG_SLIRP
162
163 #ifdef TARGET_PPC
164 #define DEFAULT_RAM_SIZE 144
165 #else
166 #define DEFAULT_RAM_SIZE 128
167 #endif
168
169 /* Max number of USB devices that can be specified on the commandline.  */
170 #define MAX_USB_CMDLINE 8
171
172 /* XXX: use a two level table to limit memory usage */
173 #define MAX_IOPORTS 65536
174
175 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
176 const char *bios_name = NULL;
177 static void *ioport_opaque[MAX_IOPORTS];
178 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
179 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181    to store the VM snapshots */
182 DriveInfo drives_table[MAX_DRIVES+1];
183 int nb_drives;
184 /* point to the block driver where the snapshots are managed */
185 static BlockDriverState *bs_snapshots;
186 static int vga_ram_size;
187 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
188 DisplayState display_state;
189 int nographic;
190 static int curses;
191 const char* keyboard_layout = NULL;
192 int64_t ticks_per_sec;
193 ram_addr_t ram_size;
194 int nb_nics;
195 NICInfo nd_table[MAX_NICS];
196 int vm_running;
197 static int rtc_utc = 1;
198 static int rtc_date_offset = -1; /* -1 means no change */
199 int cirrus_vga_enabled = 1;
200 int vmsvga_enabled = 0;
201 #ifdef TARGET_SPARC
202 int graphic_width = 1024;
203 int graphic_height = 768;
204 int graphic_depth = 8;
205 #else
206 int graphic_width = 800;
207 int graphic_height = 600;
208 int graphic_depth = 15;
209 #endif
210 static int full_screen = 0;
211 static int no_frame = 0;
212 int no_quit = 0;
213 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
214 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
215 #ifdef TARGET_I386
216 int win2k_install_hack = 0;
217 #endif
218 int usb_enabled = 0;
219 int smp_cpus = 1;
220 const char *vnc_display;
221 int acpi_enabled = 1;
222 int fd_bootchk = 1;
223 int no_reboot = 0;
224 int no_shutdown = 0;
225 int cursor_hide = 1;
226 int graphic_rotate = 0;
227 int daemonize = 0;
228 const char *option_rom[MAX_OPTION_ROMS];
229 int nb_option_roms;
230 int semihosting_enabled = 0;
231 #ifdef TARGET_ARM
232 int old_param = 0;
233 #endif
234 const char *qemu_name;
235 int alt_grab = 0;
236 #ifdef TARGET_SPARC
237 unsigned int nb_prom_envs = 0;
238 const char *prom_envs[MAX_PROM_ENVS];
239 #endif
240 static int nb_drives_opt;
241 static struct drive_opt {
242     const char *file;
243     char opt[1024];
244 } drives_opt[MAX_DRIVES];
245
246 static CPUState *cur_cpu;
247 static CPUState *next_cpu;
248 static int event_pending = 1;
249 /* Conversion factor from emulated instructions to virtual clock ticks.  */
250 static int icount_time_shift;
251 /* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
252 #define MAX_ICOUNT_SHIFT 10
253 /* Compensate for varying guest execution speed.  */
254 static int64_t qemu_icount_bias;
255 static QEMUTimer *icount_rt_timer;
256 static QEMUTimer *icount_vm_timer;
257
258 uint8_t qemu_uuid[16];
259
260 /***********************************************************/
261 /* x86 ISA bus support */
262
263 target_phys_addr_t isa_mem_base = 0;
264 PicState2 *isa_pic;
265
266 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
267 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
268
269 static uint32_t ioport_read(int index, uint32_t address)
270 {
271     static IOPortReadFunc *default_func[3] = {
272         default_ioport_readb,
273         default_ioport_readw,
274         default_ioport_readl
275     };
276     IOPortReadFunc *func = ioport_read_table[index][address];
277     if (!func)
278         func = default_func[index];
279     return func(ioport_opaque[address], address);
280 }
281
282 static void ioport_write(int index, uint32_t address, uint32_t data)
283 {
284     static IOPortWriteFunc *default_func[3] = {
285         default_ioport_writeb,
286         default_ioport_writew,
287         default_ioport_writel
288     };
289     IOPortWriteFunc *func = ioport_write_table[index][address];
290     if (!func)
291         func = default_func[index];
292     func(ioport_opaque[address], address, data);
293 }
294
295 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
296 {
297 #ifdef DEBUG_UNUSED_IOPORT
298     fprintf(stderr, "unused inb: port=0x%04x\n", address);
299 #endif
300     return 0xff;
301 }
302
303 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
304 {
305 #ifdef DEBUG_UNUSED_IOPORT
306     fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
307 #endif
308 }
309
310 /* default is to make two byte accesses */
311 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
312 {
313     uint32_t data;
314     data = ioport_read(0, address);
315     address = (address + 1) & (MAX_IOPORTS - 1);
316     data |= ioport_read(0, address) << 8;
317     return data;
318 }
319
320 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
321 {
322     ioport_write(0, address, data & 0xff);
323     address = (address + 1) & (MAX_IOPORTS - 1);
324     ioport_write(0, address, (data >> 8) & 0xff);
325 }
326
327 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
328 {
329 #ifdef DEBUG_UNUSED_IOPORT
330     fprintf(stderr, "unused inl: port=0x%04x\n", address);
331 #endif
332     return 0xffffffff;
333 }
334
335 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
336 {
337 #ifdef DEBUG_UNUSED_IOPORT
338     fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
339 #endif
340 }
341
342 /* size is the word size in byte */
343 int register_ioport_read(int start, int length, int size,
344                          IOPortReadFunc *func, void *opaque)
345 {
346     int i, bsize;
347
348     if (size == 1) {
349         bsize = 0;
350     } else if (size == 2) {
351         bsize = 1;
352     } else if (size == 4) {
353         bsize = 2;
354     } else {
355         hw_error("register_ioport_read: invalid size");
356         return -1;
357     }
358     for(i = start; i < start + length; i += size) {
359         ioport_read_table[bsize][i] = func;
360         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
361             hw_error("register_ioport_read: invalid opaque");
362         ioport_opaque[i] = opaque;
363     }
364     return 0;
365 }
366
367 /* size is the word size in byte */
368 int register_ioport_write(int start, int length, int size,
369                           IOPortWriteFunc *func, void *opaque)
370 {
371     int i, bsize;
372
373     if (size == 1) {
374         bsize = 0;
375     } else if (size == 2) {
376         bsize = 1;
377     } else if (size == 4) {
378         bsize = 2;
379     } else {
380         hw_error("register_ioport_write: invalid size");
381         return -1;
382     }
383     for(i = start; i < start + length; i += size) {
384         ioport_write_table[bsize][i] = func;
385         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
386             hw_error("register_ioport_write: invalid opaque");
387         ioport_opaque[i] = opaque;
388     }
389     return 0;
390 }
391
392 void isa_unassign_ioport(int start, int length)
393 {
394     int i;
395
396     for(i = start; i < start + length; i++) {
397         ioport_read_table[0][i] = default_ioport_readb;
398         ioport_read_table[1][i] = default_ioport_readw;
399         ioport_read_table[2][i] = default_ioport_readl;
400
401         ioport_write_table[0][i] = default_ioport_writeb;
402         ioport_write_table[1][i] = default_ioport_writew;
403         ioport_write_table[2][i] = default_ioport_writel;
404     }
405 }
406
407 /***********************************************************/
408
409 void cpu_outb(CPUState *env, int addr, int val)
410 {
411 #ifdef DEBUG_IOPORT
412     if (loglevel & CPU_LOG_IOPORT)
413         fprintf(logfile, "outb: %04x %02x\n", addr, val);
414 #endif
415     ioport_write(0, addr, val);
416 #ifdef USE_KQEMU
417     if (env)
418         env->last_io_time = cpu_get_time_fast();
419 #endif
420 }
421
422 void cpu_outw(CPUState *env, int addr, int val)
423 {
424 #ifdef DEBUG_IOPORT
425     if (loglevel & CPU_LOG_IOPORT)
426         fprintf(logfile, "outw: %04x %04x\n", addr, val);
427 #endif
428     ioport_write(1, addr, val);
429 #ifdef USE_KQEMU
430     if (env)
431         env->last_io_time = cpu_get_time_fast();
432 #endif
433 }
434
435 void cpu_outl(CPUState *env, int addr, int val)
436 {
437 #ifdef DEBUG_IOPORT
438     if (loglevel & CPU_LOG_IOPORT)
439         fprintf(logfile, "outl: %04x %08x\n", addr, val);
440 #endif
441     ioport_write(2, addr, val);
442 #ifdef USE_KQEMU
443     if (env)
444         env->last_io_time = cpu_get_time_fast();
445 #endif
446 }
447
448 int cpu_inb(CPUState *env, int addr)
449 {
450     int val;
451     val = ioport_read(0, addr);
452 #ifdef DEBUG_IOPORT
453     if (loglevel & CPU_LOG_IOPORT)
454         fprintf(logfile, "inb : %04x %02x\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 int cpu_inw(CPUState *env, int addr)
464 {
465     int val;
466     val = ioport_read(1, addr);
467 #ifdef DEBUG_IOPORT
468     if (loglevel & CPU_LOG_IOPORT)
469         fprintf(logfile, "inw : %04x %04x\n", addr, val);
470 #endif
471 #ifdef USE_KQEMU
472     if (env)
473         env->last_io_time = cpu_get_time_fast();
474 #endif
475     return val;
476 }
477
478 int cpu_inl(CPUState *env, int addr)
479 {
480     int val;
481     val = ioport_read(2, addr);
482 #ifdef DEBUG_IOPORT
483     if (loglevel & CPU_LOG_IOPORT)
484         fprintf(logfile, "inl : %04x %08x\n", addr, val);
485 #endif
486 #ifdef USE_KQEMU
487     if (env)
488         env->last_io_time = cpu_get_time_fast();
489 #endif
490     return val;
491 }
492
493 /***********************************************************/
494 void hw_error(const char *fmt, ...)
495 {
496     va_list ap;
497     CPUState *env;
498
499     va_start(ap, fmt);
500     fprintf(stderr, "qemu: hardware error: ");
501     vfprintf(stderr, fmt, ap);
502     fprintf(stderr, "\n");
503     for(env = first_cpu; env != NULL; env = env->next_cpu) {
504         fprintf(stderr, "CPU #%d:\n", env->cpu_index);
505 #ifdef TARGET_I386
506         cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
507 #else
508         cpu_dump_state(env, stderr, fprintf, 0);
509 #endif
510     }
511     va_end(ap);
512     abort();
513 }
514
515 /***********************************************************/
516 /* keyboard/mouse */
517
518 static QEMUPutKBDEvent *qemu_put_kbd_event;
519 static void *qemu_put_kbd_event_opaque;
520 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
521 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
522
523 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
524 {
525     qemu_put_kbd_event_opaque = opaque;
526     qemu_put_kbd_event = func;
527 }
528
529 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
530                                                 void *opaque, int absolute,
531                                                 const char *name)
532 {
533     QEMUPutMouseEntry *s, *cursor;
534
535     s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
536     if (!s)
537         return NULL;
538
539     s->qemu_put_mouse_event = func;
540     s->qemu_put_mouse_event_opaque = opaque;
541     s->qemu_put_mouse_event_absolute = absolute;
542     s->qemu_put_mouse_event_name = qemu_strdup(name);
543     s->next = NULL;
544
545     if (!qemu_put_mouse_event_head) {
546         qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
547         return s;
548     }
549
550     cursor = qemu_put_mouse_event_head;
551     while (cursor->next != NULL)
552         cursor = cursor->next;
553
554     cursor->next = s;
555     qemu_put_mouse_event_current = s;
556
557     return s;
558 }
559
560 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
561 {
562     QEMUPutMouseEntry *prev = NULL, *cursor;
563
564     if (!qemu_put_mouse_event_head || entry == NULL)
565         return;
566
567     cursor = qemu_put_mouse_event_head;
568     while (cursor != NULL && cursor != entry) {
569         prev = cursor;
570         cursor = cursor->next;
571     }
572
573     if (cursor == NULL) // does not exist or list empty
574         return;
575     else if (prev == NULL) { // entry is head
576         qemu_put_mouse_event_head = cursor->next;
577         if (qemu_put_mouse_event_current == entry)
578             qemu_put_mouse_event_current = cursor->next;
579         qemu_free(entry->qemu_put_mouse_event_name);
580         qemu_free(entry);
581         return;
582     }
583
584     prev->next = entry->next;
585
586     if (qemu_put_mouse_event_current == entry)
587         qemu_put_mouse_event_current = prev;
588
589     qemu_free(entry->qemu_put_mouse_event_name);
590     qemu_free(entry);
591 }
592
593 void kbd_put_keycode(int keycode)
594 {
595     if (qemu_put_kbd_event) {
596         qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
597     }
598 }
599
600 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
601 {
602     QEMUPutMouseEvent *mouse_event;
603     void *mouse_event_opaque;
604     int width;
605
606     if (!qemu_put_mouse_event_current) {
607         return;
608     }
609
610     mouse_event =
611         qemu_put_mouse_event_current->qemu_put_mouse_event;
612     mouse_event_opaque =
613         qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
614
615     if (mouse_event) {
616         if (graphic_rotate) {
617             if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
618                 width = 0x7fff;
619             else
620                 width = graphic_width - 1;
621             mouse_event(mouse_event_opaque,
622                                  width - dy, dx, dz, buttons_state);
623         } else
624             mouse_event(mouse_event_opaque,
625                                  dx, dy, dz, buttons_state);
626     }
627 }
628
629 int kbd_mouse_is_absolute(void)
630 {
631     if (!qemu_put_mouse_event_current)
632         return 0;
633
634     return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
635 }
636
637 void do_info_mice(void)
638 {
639     QEMUPutMouseEntry *cursor;
640     int index = 0;
641
642     if (!qemu_put_mouse_event_head) {
643         term_printf("No mouse devices connected\n");
644         return;
645     }
646
647     term_printf("Mouse devices available:\n");
648     cursor = qemu_put_mouse_event_head;
649     while (cursor != NULL) {
650         term_printf("%c Mouse #%d: %s\n",
651                     (cursor == qemu_put_mouse_event_current ? '*' : ' '),
652                     index, cursor->qemu_put_mouse_event_name);
653         index++;
654         cursor = cursor->next;
655     }
656 }
657
658 void do_mouse_set(int index)
659 {
660     QEMUPutMouseEntry *cursor;
661     int i = 0;
662
663     if (!qemu_put_mouse_event_head) {
664         term_printf("No mouse devices connected\n");
665         return;
666     }
667
668     cursor = qemu_put_mouse_event_head;
669     while (cursor != NULL && index != i) {
670         i++;
671         cursor = cursor->next;
672     }
673
674     if (cursor != NULL)
675         qemu_put_mouse_event_current = cursor;
676     else
677         term_printf("Mouse at given index not found\n");
678 }
679
680 /* compute with 96 bit intermediate result: (a*b)/c */
681 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
682 {
683     union {
684         uint64_t ll;
685         struct {
686 #ifdef WORDS_BIGENDIAN
687             uint32_t high, low;
688 #else
689             uint32_t low, high;
690 #endif
691         } l;
692     } u, res;
693     uint64_t rl, rh;
694
695     u.ll = a;
696     rl = (uint64_t)u.l.low * (uint64_t)b;
697     rh = (uint64_t)u.l.high * (uint64_t)b;
698     rh += (rl >> 32);
699     res.l.high = rh / c;
700     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
701     return res.ll;
702 }
703
704 /***********************************************************/
705 /* real time host monotonic timer */
706
707 #define QEMU_TIMER_BASE 1000000000LL
708
709 #ifdef WIN32
710
711 static int64_t clock_freq;
712
713 static void init_get_clock(void)
714 {
715     LARGE_INTEGER freq;
716     int ret;
717     ret = QueryPerformanceFrequency(&freq);
718     if (ret == 0) {
719         fprintf(stderr, "Could not calibrate ticks\n");
720         exit(1);
721     }
722     clock_freq = freq.QuadPart;
723 }
724
725 static int64_t get_clock(void)
726 {
727     LARGE_INTEGER ti;
728     QueryPerformanceCounter(&ti);
729     return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
730 }
731
732 #else
733
734 static int use_rt_clock;
735
736 static void init_get_clock(void)
737 {
738     use_rt_clock = 0;
739 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
740     {
741         struct timespec ts;
742         if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
743             use_rt_clock = 1;
744         }
745     }
746 #endif
747 }
748
749 static int64_t get_clock(void)
750 {
751 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
752     if (use_rt_clock) {
753         struct timespec ts;
754         clock_gettime(CLOCK_MONOTONIC, &ts);
755         return ts.tv_sec * 1000000000LL + ts.tv_nsec;
756     } else
757 #endif
758     {
759         /* XXX: using gettimeofday leads to problems if the date
760            changes, so it should be avoided. */
761         struct timeval tv;
762         gettimeofday(&tv, NULL);
763         return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
764     }
765 }
766 #endif
767
768 /* Return the virtual CPU time, based on the instruction counter.  */
769 static int64_t cpu_get_icount(void)
770 {
771     int64_t icount;
772     CPUState *env = cpu_single_env;;
773     icount = qemu_icount;
774     if (env) {
775         if (!can_do_io(env))
776             fprintf(stderr, "Bad clock read\n");
777         icount -= (env->icount_decr.u16.low + env->icount_extra);
778     }
779     return qemu_icount_bias + (icount << icount_time_shift);
780 }
781
782 /***********************************************************/
783 /* guest cycle counter */
784
785 static int64_t cpu_ticks_prev;
786 static int64_t cpu_ticks_offset;
787 static int64_t cpu_clock_offset;
788 static int cpu_ticks_enabled;
789
790 /* return the host CPU cycle counter and handle stop/restart */
791 int64_t cpu_get_ticks(void)
792 {
793     if (use_icount) {
794         return cpu_get_icount();
795     }
796     if (!cpu_ticks_enabled) {
797         return cpu_ticks_offset;
798     } else {
799         int64_t ticks;
800         ticks = cpu_get_real_ticks();
801         if (cpu_ticks_prev > ticks) {
802             /* Note: non increasing ticks may happen if the host uses
803                software suspend */
804             cpu_ticks_offset += cpu_ticks_prev - ticks;
805         }
806         cpu_ticks_prev = ticks;
807         return ticks + cpu_ticks_offset;
808     }
809 }
810
811 /* return the host CPU monotonic timer and handle stop/restart */
812 static int64_t cpu_get_clock(void)
813 {
814     int64_t ti;
815     if (!cpu_ticks_enabled) {
816         return cpu_clock_offset;
817     } else {
818         ti = get_clock();
819         return ti + cpu_clock_offset;
820     }
821 }
822
823 /* enable cpu_get_ticks() */
824 void cpu_enable_ticks(void)
825 {
826     if (!cpu_ticks_enabled) {
827         cpu_ticks_offset -= cpu_get_real_ticks();
828         cpu_clock_offset -= get_clock();
829         cpu_ticks_enabled = 1;
830     }
831 }
832
833 /* disable cpu_get_ticks() : the clock is stopped. You must not call
834    cpu_get_ticks() after that.  */
835 void cpu_disable_ticks(void)
836 {
837     if (cpu_ticks_enabled) {
838         cpu_ticks_offset = cpu_get_ticks();
839         cpu_clock_offset = cpu_get_clock();
840         cpu_ticks_enabled = 0;
841     }
842 }
843
844 /***********************************************************/
845 /* timers */
846
847 #define QEMU_TIMER_REALTIME 0
848 #define QEMU_TIMER_VIRTUAL  1
849
850 struct QEMUClock {
851     int type;
852     /* XXX: add frequency */
853 };
854
855 struct QEMUTimer {
856     QEMUClock *clock;
857     int64_t expire_time;
858     QEMUTimerCB *cb;
859     void *opaque;
860     struct QEMUTimer *next;
861 };
862
863 struct qemu_alarm_timer {
864     char const *name;
865     unsigned int flags;
866
867     int (*start)(struct qemu_alarm_timer *t);
868     void (*stop)(struct qemu_alarm_timer *t);
869     void (*rearm)(struct qemu_alarm_timer *t);
870     void *priv;
871 };
872
873 #define ALARM_FLAG_DYNTICKS  0x1
874 #define ALARM_FLAG_EXPIRED   0x2
875
876 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
877 {
878     return t->flags & ALARM_FLAG_DYNTICKS;
879 }
880
881 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
882 {
883     if (!alarm_has_dynticks(t))
884         return;
885
886     t->rearm(t);
887 }
888
889 /* TODO: MIN_TIMER_REARM_US should be optimized */
890 #define MIN_TIMER_REARM_US 250
891
892 static struct qemu_alarm_timer *alarm_timer;
893 #ifndef _WIN32
894 static int alarm_timer_rfd, alarm_timer_wfd;
895 #endif
896
897 #ifdef _WIN32
898
899 struct qemu_alarm_win32 {
900     MMRESULT timerId;
901     HANDLE host_alarm;
902     unsigned int period;
903 } alarm_win32_data = {0, NULL, -1};
904
905 static int win32_start_timer(struct qemu_alarm_timer *t);
906 static void win32_stop_timer(struct qemu_alarm_timer *t);
907 static void win32_rearm_timer(struct qemu_alarm_timer *t);
908
909 #else
910
911 static int unix_start_timer(struct qemu_alarm_timer *t);
912 static void unix_stop_timer(struct qemu_alarm_timer *t);
913
914 #ifdef __linux__
915
916 static int dynticks_start_timer(struct qemu_alarm_timer *t);
917 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
918 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
919
920 static int hpet_start_timer(struct qemu_alarm_timer *t);
921 static void hpet_stop_timer(struct qemu_alarm_timer *t);
922
923 static int rtc_start_timer(struct qemu_alarm_timer *t);
924 static void rtc_stop_timer(struct qemu_alarm_timer *t);
925
926 #endif /* __linux__ */
927
928 #endif /* _WIN32 */
929
930 /* Correlation between real and virtual time is always going to be
931    fairly approximate, so ignore small variation.
932    When the guest is idle real and virtual time will be aligned in
933    the IO wait loop.  */
934 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
935
936 static void icount_adjust(void)
937 {
938     int64_t cur_time;
939     int64_t cur_icount;
940     int64_t delta;
941     static int64_t last_delta;
942     /* If the VM is not running, then do nothing.  */
943     if (!vm_running)
944         return;
945
946     cur_time = cpu_get_clock();
947     cur_icount = qemu_get_clock(vm_clock);
948     delta = cur_icount - cur_time;
949     /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
950     if (delta > 0
951         && last_delta + ICOUNT_WOBBLE < delta * 2
952         && icount_time_shift > 0) {
953         /* The guest is getting too far ahead.  Slow time down.  */
954         icount_time_shift--;
955     }
956     if (delta < 0
957         && last_delta - ICOUNT_WOBBLE > delta * 2
958         && icount_time_shift < MAX_ICOUNT_SHIFT) {
959         /* The guest is getting too far behind.  Speed time up.  */
960         icount_time_shift++;
961     }
962     last_delta = delta;
963     qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
964 }
965
966 static void icount_adjust_rt(void * opaque)
967 {
968     qemu_mod_timer(icount_rt_timer,
969                    qemu_get_clock(rt_clock) + 1000);
970     icount_adjust();
971 }
972
973 static void icount_adjust_vm(void * opaque)
974 {
975     qemu_mod_timer(icount_vm_timer,
976                    qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
977     icount_adjust();
978 }
979
980 static void init_icount_adjust(void)
981 {
982     /* Have both realtime and virtual time triggers for speed adjustment.
983        The realtime trigger catches emulated time passing too slowly,
984        the virtual time trigger catches emulated time passing too fast.
985        Realtime triggers occur even when idle, so use them less frequently
986        than VM triggers.  */
987     icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
988     qemu_mod_timer(icount_rt_timer,
989                    qemu_get_clock(rt_clock) + 1000);
990     icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
991     qemu_mod_timer(icount_vm_timer,
992                    qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
993 }
994
995 static struct qemu_alarm_timer alarm_timers[] = {
996 #ifndef _WIN32
997 #ifdef __linux__
998     {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
999      dynticks_stop_timer, dynticks_rearm_timer, NULL},
1000     /* HPET - if available - is preferred */
1001     {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1002     /* ...otherwise try RTC */
1003     {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1004 #endif
1005     {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1006 #else
1007     {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1008      win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1009     {"win32", 0, win32_start_timer,
1010      win32_stop_timer, NULL, &alarm_win32_data},
1011 #endif
1012     {NULL, }
1013 };
1014
1015 static void show_available_alarms(void)
1016 {
1017     int i;
1018
1019     printf("Available alarm timers, in order of precedence:\n");
1020     for (i = 0; alarm_timers[i].name; i++)
1021         printf("%s\n", alarm_timers[i].name);
1022 }
1023
1024 static void configure_alarms(char const *opt)
1025 {
1026     int i;
1027     int cur = 0;
1028     int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1029     char *arg;
1030     char *name;
1031     struct qemu_alarm_timer tmp;
1032
1033     if (!strcmp(opt, "?")) {
1034         show_available_alarms();
1035         exit(0);
1036     }
1037
1038     arg = strdup(opt);
1039
1040     /* Reorder the array */
1041     name = strtok(arg, ",");
1042     while (name) {
1043         for (i = 0; i < count && alarm_timers[i].name; i++) {
1044             if (!strcmp(alarm_timers[i].name, name))
1045                 break;
1046         }
1047
1048         if (i == count) {
1049             fprintf(stderr, "Unknown clock %s\n", name);
1050             goto next;
1051         }
1052
1053         if (i < cur)
1054             /* Ignore */
1055             goto next;
1056
1057         /* Swap */
1058         tmp = alarm_timers[i];
1059         alarm_timers[i] = alarm_timers[cur];
1060         alarm_timers[cur] = tmp;
1061
1062         cur++;
1063 next:
1064         name = strtok(NULL, ",");
1065     }
1066
1067     free(arg);
1068
1069     if (cur) {
1070         /* Disable remaining timers */
1071         for (i = cur; i < count; i++)
1072             alarm_timers[i].name = NULL;
1073     } else {
1074         show_available_alarms();
1075         exit(1);
1076     }
1077 }
1078
1079 QEMUClock *rt_clock;
1080 QEMUClock *vm_clock;
1081
1082 static QEMUTimer *active_timers[2];
1083
1084 static QEMUClock *qemu_new_clock(int type)
1085 {
1086     QEMUClock *clock;
1087     clock = qemu_mallocz(sizeof(QEMUClock));
1088     if (!clock)
1089         return NULL;
1090     clock->type = type;
1091     return clock;
1092 }
1093
1094 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1095 {
1096     QEMUTimer *ts;
1097
1098     ts = qemu_mallocz(sizeof(QEMUTimer));
1099     ts->clock = clock;
1100     ts->cb = cb;
1101     ts->opaque = opaque;
1102     return ts;
1103 }
1104
1105 void qemu_free_timer(QEMUTimer *ts)
1106 {
1107     qemu_free(ts);
1108 }
1109
1110 /* stop a timer, but do not dealloc it */
1111 void qemu_del_timer(QEMUTimer *ts)
1112 {
1113     QEMUTimer **pt, *t;
1114
1115     /* NOTE: this code must be signal safe because
1116        qemu_timer_expired() can be called from a signal. */
1117     pt = &active_timers[ts->clock->type];
1118     for(;;) {
1119         t = *pt;
1120         if (!t)
1121             break;
1122         if (t == ts) {
1123             *pt = t->next;
1124             break;
1125         }
1126         pt = &t->next;
1127     }
1128 }
1129
1130 /* modify the current timer so that it will be fired when current_time
1131    >= expire_time. The corresponding callback will be called. */
1132 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1133 {
1134     QEMUTimer **pt, *t;
1135
1136     qemu_del_timer(ts);
1137
1138     /* add the timer in the sorted list */
1139     /* NOTE: this code must be signal safe because
1140        qemu_timer_expired() can be called from a signal. */
1141     pt = &active_timers[ts->clock->type];
1142     for(;;) {
1143         t = *pt;
1144         if (!t)
1145             break;
1146         if (t->expire_time > expire_time)
1147             break;
1148         pt = &t->next;
1149     }
1150     ts->expire_time = expire_time;
1151     ts->next = *pt;
1152     *pt = ts;
1153
1154     /* Rearm if necessary  */
1155     if (pt == &active_timers[ts->clock->type]) {
1156         if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1157             qemu_rearm_alarm_timer(alarm_timer);
1158         }
1159         /* Interrupt execution to force deadline recalculation.  */
1160         if (use_icount && cpu_single_env) {
1161             cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1162         }
1163     }
1164 }
1165
1166 int qemu_timer_pending(QEMUTimer *ts)
1167 {
1168     QEMUTimer *t;
1169     for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1170         if (t == ts)
1171             return 1;
1172     }
1173     return 0;
1174 }
1175
1176 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1177 {
1178     if (!timer_head)
1179         return 0;
1180     return (timer_head->expire_time <= current_time);
1181 }
1182
1183 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1184 {
1185     QEMUTimer *ts;
1186
1187     for(;;) {
1188         ts = *ptimer_head;
1189         if (!ts || ts->expire_time > current_time)
1190             break;
1191         /* remove timer from the list before calling the callback */
1192         *ptimer_head = ts->next;
1193         ts->next = NULL;
1194
1195         /* run the callback (the timer list can be modified) */
1196         ts->cb(ts->opaque);
1197     }
1198 }
1199
1200 int64_t qemu_get_clock(QEMUClock *clock)
1201 {
1202     switch(clock->type) {
1203     case QEMU_TIMER_REALTIME:
1204         return get_clock() / 1000000;
1205     default:
1206     case QEMU_TIMER_VIRTUAL:
1207         if (use_icount) {
1208             return cpu_get_icount();
1209         } else {
1210             return cpu_get_clock();
1211         }
1212     }
1213 }
1214
1215 static void init_timers(void)
1216 {
1217     init_get_clock();
1218     ticks_per_sec = QEMU_TIMER_BASE;
1219     rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1220     vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1221 }
1222
1223 /* save a timer */
1224 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1225 {
1226     uint64_t expire_time;
1227
1228     if (qemu_timer_pending(ts)) {
1229         expire_time = ts->expire_time;
1230     } else {
1231         expire_time = -1;
1232     }
1233     qemu_put_be64(f, expire_time);
1234 }
1235
1236 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1237 {
1238     uint64_t expire_time;
1239
1240     expire_time = qemu_get_be64(f);
1241     if (expire_time != -1) {
1242         qemu_mod_timer(ts, expire_time);
1243     } else {
1244         qemu_del_timer(ts);
1245     }
1246 }
1247
1248 static void timer_save(QEMUFile *f, void *opaque)
1249 {
1250     if (cpu_ticks_enabled) {
1251         hw_error("cannot save state if virtual timers are running");
1252     }
1253     qemu_put_be64(f, cpu_ticks_offset);
1254     qemu_put_be64(f, ticks_per_sec);
1255     qemu_put_be64(f, cpu_clock_offset);
1256 }
1257
1258 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1259 {
1260     if (version_id != 1 && version_id != 2)
1261         return -EINVAL;
1262     if (cpu_ticks_enabled) {
1263         return -EINVAL;
1264     }
1265     cpu_ticks_offset=qemu_get_be64(f);
1266     ticks_per_sec=qemu_get_be64(f);
1267     if (version_id == 2) {
1268         cpu_clock_offset=qemu_get_be64(f);
1269     }
1270     return 0;
1271 }
1272
1273 #ifdef _WIN32
1274 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1275                                  DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1276 #else
1277 static void host_alarm_handler(int host_signum)
1278 #endif
1279 {
1280 #if 0
1281 #define DISP_FREQ 1000
1282     {
1283         static int64_t delta_min = INT64_MAX;
1284         static int64_t delta_max, delta_cum, last_clock, delta, ti;
1285         static int count;
1286         ti = qemu_get_clock(vm_clock);
1287         if (last_clock != 0) {
1288             delta = ti - last_clock;
1289             if (delta < delta_min)
1290                 delta_min = delta;
1291             if (delta > delta_max)
1292                 delta_max = delta;
1293             delta_cum += delta;
1294             if (++count == DISP_FREQ) {
1295                 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1296                        muldiv64(delta_min, 1000000, ticks_per_sec),
1297                        muldiv64(delta_max, 1000000, ticks_per_sec),
1298                        muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1299                        (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1300                 count = 0;
1301                 delta_min = INT64_MAX;
1302                 delta_max = 0;
1303                 delta_cum = 0;
1304             }
1305         }
1306         last_clock = ti;
1307     }
1308 #endif
1309     if (alarm_has_dynticks(alarm_timer) ||
1310         (!use_icount &&
1311             qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1312                                qemu_get_clock(vm_clock))) ||
1313         qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1314                            qemu_get_clock(rt_clock))) {
1315         CPUState *env = next_cpu;
1316
1317 #ifdef _WIN32
1318         struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1319         SetEvent(data->host_alarm);
1320 #else
1321         static const char byte = 0;
1322         write(alarm_timer_wfd, &byte, sizeof(byte));
1323 #endif
1324         alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1325
1326         if (env) {
1327             /* stop the currently executing cpu because a timer occured */
1328             cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1329 #ifdef USE_KQEMU
1330             if (env->kqemu_enabled) {
1331                 kqemu_cpu_interrupt(env);
1332             }
1333 #endif
1334         }
1335         event_pending = 1;
1336     }
1337 }
1338
1339 static int64_t qemu_next_deadline(void)
1340 {
1341     int64_t delta;
1342
1343     if (active_timers[QEMU_TIMER_VIRTUAL]) {
1344         delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1345                      qemu_get_clock(vm_clock);
1346     } else {
1347         /* To avoid problems with overflow limit this to 2^32.  */
1348         delta = INT32_MAX;
1349     }
1350
1351     if (delta < 0)
1352         delta = 0;
1353
1354     return delta;
1355 }
1356
1357 #if defined(__linux__) || defined(_WIN32)
1358 static uint64_t qemu_next_deadline_dyntick(void)
1359 {
1360     int64_t delta;
1361     int64_t rtdelta;
1362
1363     if (use_icount)
1364         delta = INT32_MAX;
1365     else
1366         delta = (qemu_next_deadline() + 999) / 1000;
1367
1368     if (active_timers[QEMU_TIMER_REALTIME]) {
1369         rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1370                  qemu_get_clock(rt_clock))*1000;
1371         if (rtdelta < delta)
1372             delta = rtdelta;
1373     }
1374
1375     if (delta < MIN_TIMER_REARM_US)
1376         delta = MIN_TIMER_REARM_US;
1377
1378     return delta;
1379 }
1380 #endif
1381
1382 #ifndef _WIN32
1383
1384 /* Sets a specific flag */
1385 static int fcntl_setfl(int fd, int flag)
1386 {
1387     int flags;
1388
1389     flags = fcntl(fd, F_GETFL);
1390     if (flags == -1)
1391         return -errno;
1392
1393     if (fcntl(fd, F_SETFL, flags | flag) == -1)
1394         return -errno;
1395
1396     return 0;
1397 }
1398
1399 #if defined(__linux__)
1400
1401 #define RTC_FREQ 1024
1402
1403 static void enable_sigio_timer(int fd)
1404 {
1405     struct sigaction act;
1406
1407     /* timer signal */
1408     sigfillset(&act.sa_mask);
1409     act.sa_flags = 0;
1410     act.sa_handler = host_alarm_handler;
1411
1412     sigaction(SIGIO, &act, NULL);
1413     fcntl_setfl(fd, O_ASYNC);
1414     fcntl(fd, F_SETOWN, getpid());
1415 }
1416
1417 static int hpet_start_timer(struct qemu_alarm_timer *t)
1418 {
1419     struct hpet_info info;
1420     int r, fd;
1421
1422     fd = open("/dev/hpet", O_RDONLY);
1423     if (fd < 0)
1424         return -1;
1425
1426     /* Set frequency */
1427     r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1428     if (r < 0) {
1429         fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1430                 "error, but for better emulation accuracy type:\n"
1431                 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1432         goto fail;
1433     }
1434
1435     /* Check capabilities */
1436     r = ioctl(fd, HPET_INFO, &info);
1437     if (r < 0)
1438         goto fail;
1439
1440     /* Enable periodic mode */
1441     r = ioctl(fd, HPET_EPI, 0);
1442     if (info.hi_flags && (r < 0))
1443         goto fail;
1444
1445     /* Enable interrupt */
1446     r = ioctl(fd, HPET_IE_ON, 0);
1447     if (r < 0)
1448         goto fail;
1449
1450     enable_sigio_timer(fd);
1451     t->priv = (void *)(long)fd;
1452
1453     return 0;
1454 fail:
1455     close(fd);
1456     return -1;
1457 }
1458
1459 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1460 {
1461     int fd = (long)t->priv;
1462
1463     close(fd);
1464 }
1465
1466 static int rtc_start_timer(struct qemu_alarm_timer *t)
1467 {
1468     int rtc_fd;
1469     unsigned long current_rtc_freq = 0;
1470
1471     TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1472     if (rtc_fd < 0)
1473         return -1;
1474     ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1475     if (current_rtc_freq != RTC_FREQ &&
1476         ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1477         fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1478                 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1479                 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1480         goto fail;
1481     }
1482     if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1483     fail:
1484         close(rtc_fd);
1485         return -1;
1486     }
1487
1488     enable_sigio_timer(rtc_fd);
1489
1490     t->priv = (void *)(long)rtc_fd;
1491
1492     return 0;
1493 }
1494
1495 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1496 {
1497     int rtc_fd = (long)t->priv;
1498
1499     close(rtc_fd);
1500 }
1501
1502 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1503 {
1504     struct sigevent ev;
1505     timer_t host_timer;
1506     struct sigaction act;
1507
1508     sigfillset(&act.sa_mask);
1509     act.sa_flags = 0;
1510     act.sa_handler = host_alarm_handler;
1511
1512     sigaction(SIGALRM, &act, NULL);
1513
1514     ev.sigev_value.sival_int = 0;
1515     ev.sigev_notify = SIGEV_SIGNAL;
1516     ev.sigev_signo = SIGALRM;
1517
1518     if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1519         perror("timer_create");
1520
1521         /* disable dynticks */
1522         fprintf(stderr, "Dynamic Ticks disabled\n");
1523
1524         return -1;
1525     }
1526
1527     t->priv = (void *)host_timer;
1528
1529     return 0;
1530 }
1531
1532 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1533 {
1534     timer_t host_timer = (timer_t)t->priv;
1535
1536     timer_delete(host_timer);
1537 }
1538
1539 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1540 {
1541     timer_t host_timer = (timer_t)t->priv;
1542     struct itimerspec timeout;
1543     int64_t nearest_delta_us = INT64_MAX;
1544     int64_t current_us;
1545
1546     if (!active_timers[QEMU_TIMER_REALTIME] &&
1547                 !active_timers[QEMU_TIMER_VIRTUAL])
1548         return;
1549
1550     nearest_delta_us = qemu_next_deadline_dyntick();
1551
1552     /* check whether a timer is already running */
1553     if (timer_gettime(host_timer, &timeout)) {
1554         perror("gettime");
1555         fprintf(stderr, "Internal timer error: aborting\n");
1556         exit(1);
1557     }
1558     current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1559     if (current_us && current_us <= nearest_delta_us)
1560         return;
1561
1562     timeout.it_interval.tv_sec = 0;
1563     timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1564     timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1565     timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1566     if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1567         perror("settime");
1568         fprintf(stderr, "Internal timer error: aborting\n");
1569         exit(1);
1570     }
1571 }
1572
1573 #endif /* defined(__linux__) */
1574
1575 static int unix_start_timer(struct qemu_alarm_timer *t)
1576 {
1577     struct sigaction act;
1578     struct itimerval itv;
1579     int err;
1580
1581     /* timer signal */
1582     sigfillset(&act.sa_mask);
1583     act.sa_flags = 0;
1584     act.sa_handler = host_alarm_handler;
1585
1586     sigaction(SIGALRM, &act, NULL);
1587
1588     itv.it_interval.tv_sec = 0;
1589     /* for i386 kernel 2.6 to get 1 ms */
1590     itv.it_interval.tv_usec = 999;
1591     itv.it_value.tv_sec = 0;
1592     itv.it_value.tv_usec = 10 * 1000;
1593
1594     err = setitimer(ITIMER_REAL, &itv, NULL);
1595     if (err)
1596         return -1;
1597
1598     return 0;
1599 }
1600
1601 static void unix_stop_timer(struct qemu_alarm_timer *t)
1602 {
1603     struct itimerval itv;
1604
1605     memset(&itv, 0, sizeof(itv));
1606     setitimer(ITIMER_REAL, &itv, NULL);
1607 }
1608
1609 #endif /* !defined(_WIN32) */
1610
1611 static void try_to_rearm_timer(void *opaque)
1612 {
1613     struct qemu_alarm_timer *t = opaque;
1614 #ifndef _WIN32
1615     ssize_t len;
1616
1617     /* Drain the notify pipe */
1618     do {
1619         char buffer[512];
1620         len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1621     } while ((len == -1 && errno == EINTR) || len > 0);
1622 #endif
1623
1624     /* vm time timers */
1625     if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
1626         qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
1627                         qemu_get_clock(vm_clock));
1628
1629     /* real time timers */
1630     qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
1631                     qemu_get_clock(rt_clock));
1632
1633     if (t->flags & ALARM_FLAG_EXPIRED) {
1634         alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1635         qemu_rearm_alarm_timer(alarm_timer);
1636     }
1637 }
1638
1639 #ifdef _WIN32
1640
1641 static int win32_start_timer(struct qemu_alarm_timer *t)
1642 {
1643     TIMECAPS tc;
1644     struct qemu_alarm_win32 *data = t->priv;
1645     UINT flags;
1646
1647     data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1648     if (!data->host_alarm) {
1649         perror("Failed CreateEvent");
1650         return -1;
1651     }
1652
1653     memset(&tc, 0, sizeof(tc));
1654     timeGetDevCaps(&tc, sizeof(tc));
1655
1656     if (data->period < tc.wPeriodMin)
1657         data->period = tc.wPeriodMin;
1658
1659     timeBeginPeriod(data->period);
1660
1661     flags = TIME_CALLBACK_FUNCTION;
1662     if (alarm_has_dynticks(t))
1663         flags |= TIME_ONESHOT;
1664     else
1665         flags |= TIME_PERIODIC;
1666
1667     data->timerId = timeSetEvent(1,         // interval (ms)
1668                         data->period,       // resolution
1669                         host_alarm_handler, // function
1670                         (DWORD)t,           // parameter
1671                         flags);
1672
1673     if (!data->timerId) {
1674         perror("Failed to initialize win32 alarm timer");
1675
1676         timeEndPeriod(data->period);
1677         CloseHandle(data->host_alarm);
1678         return -1;
1679     }
1680
1681     qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1682
1683     return 0;
1684 }
1685
1686 static void win32_stop_timer(struct qemu_alarm_timer *t)
1687 {
1688     struct qemu_alarm_win32 *data = t->priv;
1689
1690     timeKillEvent(data->timerId);
1691     timeEndPeriod(data->period);
1692
1693     CloseHandle(data->host_alarm);
1694 }
1695
1696 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1697 {
1698     struct qemu_alarm_win32 *data = t->priv;
1699     uint64_t nearest_delta_us;
1700
1701     if (!active_timers[QEMU_TIMER_REALTIME] &&
1702                 !active_timers[QEMU_TIMER_VIRTUAL])
1703         return;
1704
1705     nearest_delta_us = qemu_next_deadline_dyntick();
1706     nearest_delta_us /= 1000;
1707
1708     timeKillEvent(data->timerId);
1709
1710     data->timerId = timeSetEvent(1,
1711                         data->period,
1712                         host_alarm_handler,
1713                         (DWORD)t,
1714                         TIME_ONESHOT | TIME_PERIODIC);
1715
1716     if (!data->timerId) {
1717         perror("Failed to re-arm win32 alarm timer");
1718
1719         timeEndPeriod(data->period);
1720         CloseHandle(data->host_alarm);
1721         exit(1);
1722     }
1723 }
1724
1725 #endif /* _WIN32 */
1726
1727 static int init_timer_alarm(void)
1728 {
1729     struct qemu_alarm_timer *t = NULL;
1730     int i, err = -1;
1731
1732 #ifndef _WIN32
1733     int fds[2];
1734
1735     err = pipe(fds);
1736     if (err == -1)
1737         return -errno;
1738
1739     err = fcntl_setfl(fds[0], O_NONBLOCK);
1740     if (err < 0)
1741         goto fail;
1742
1743     err = fcntl_setfl(fds[1], O_NONBLOCK);
1744     if (err < 0)
1745         goto fail;
1746
1747     alarm_timer_rfd = fds[0];
1748     alarm_timer_wfd = fds[1];
1749 #endif
1750
1751     for (i = 0; alarm_timers[i].name; i++) {
1752         t = &alarm_timers[i];
1753
1754         err = t->start(t);
1755         if (!err)
1756             break;
1757     }
1758
1759     if (err) {
1760         err = -ENOENT;
1761         goto fail;
1762     }
1763
1764 #ifndef _WIN32
1765     qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1766                          try_to_rearm_timer, NULL, t);
1767 #endif
1768
1769     alarm_timer = t;
1770
1771     return 0;
1772
1773 fail:
1774 #ifndef _WIN32
1775     close(fds[0]);
1776     close(fds[1]);
1777 #endif
1778     return err;
1779 }
1780
1781 static void quit_timers(void)
1782 {
1783     alarm_timer->stop(alarm_timer);
1784     alarm_timer = NULL;
1785 }
1786
1787 /***********************************************************/
1788 /* host time/date access */
1789 void qemu_get_timedate(struct tm *tm, int offset)
1790 {
1791     time_t ti;
1792     struct tm *ret;
1793
1794     time(&ti);
1795     ti += offset;
1796     if (rtc_date_offset == -1) {
1797         if (rtc_utc)
1798             ret = gmtime(&ti);
1799         else
1800             ret = localtime(&ti);
1801     } else {
1802         ti -= rtc_date_offset;
1803         ret = gmtime(&ti);
1804     }
1805
1806     memcpy(tm, ret, sizeof(struct tm));
1807 }
1808
1809 int qemu_timedate_diff(struct tm *tm)
1810 {
1811     time_t seconds;
1812
1813     if (rtc_date_offset == -1)
1814         if (rtc_utc)
1815             seconds = mktimegm(tm);
1816         else
1817             seconds = mktime(tm);
1818     else
1819         seconds = mktimegm(tm) + rtc_date_offset;
1820
1821     return seconds - time(NULL);
1822 }
1823
1824 #ifdef _WIN32
1825 static void socket_cleanup(void)
1826 {
1827     WSACleanup();
1828 }
1829
1830 static int socket_init(void)
1831 {
1832     WSADATA Data;
1833     int ret, err;
1834
1835     ret = WSAStartup(MAKEWORD(2,2), &Data);
1836     if (ret != 0) {
1837         err = WSAGetLastError();
1838         fprintf(stderr, "WSAStartup: %d\n", err);
1839         return -1;
1840     }
1841     atexit(socket_cleanup);
1842     return 0;
1843 }
1844 #endif
1845
1846 const char *get_opt_name(char *buf, int buf_size, const char *p)
1847 {
1848     char *q;
1849
1850     q = buf;
1851     while (*p != '\0' && *p != '=') {
1852         if (q && (q - buf) < buf_size - 1)
1853             *q++ = *p;
1854         p++;
1855     }
1856     if (q)
1857         *q = '\0';
1858
1859     return p;
1860 }
1861
1862 const char *get_opt_value(char *buf, int buf_size, const char *p)
1863 {
1864     char *q;
1865
1866     q = buf;
1867     while (*p != '\0') {
1868         if (*p == ',') {
1869             if (*(p + 1) != ',')
1870                 break;
1871             p++;
1872         }
1873         if (q && (q - buf) < buf_size - 1)
1874             *q++ = *p;
1875         p++;
1876     }
1877     if (q)
1878         *q = '\0';
1879
1880     return p;
1881 }
1882
1883 int get_param_value(char *buf, int buf_size,
1884                     const char *tag, const char *str)
1885 {
1886     const char *p;
1887     char option[128];
1888
1889     p = str;
1890     for(;;) {
1891         p = get_opt_name(option, sizeof(option), p);
1892         if (*p != '=')
1893             break;
1894         p++;
1895         if (!strcmp(tag, option)) {
1896             (void)get_opt_value(buf, buf_size, p);
1897             return strlen(buf);
1898         } else {
1899             p = get_opt_value(NULL, 0, p);
1900         }
1901         if (*p != ',')
1902             break;
1903         p++;
1904     }
1905     return 0;
1906 }
1907
1908 int check_params(char *buf, int buf_size,
1909                  const char * const *params, const char *str)
1910 {
1911     const char *p;
1912     int i;
1913
1914     p = str;
1915     for(;;) {
1916         p = get_opt_name(buf, buf_size, p);
1917         if (*p != '=')
1918             return -1;
1919         p++;
1920         for(i = 0; params[i] != NULL; i++)
1921             if (!strcmp(params[i], buf))
1922                 break;
1923         if (params[i] == NULL)
1924             return -1;
1925         p = get_opt_value(NULL, 0, p);
1926         if (*p != ',')
1927             break;
1928         p++;
1929     }
1930     return 0;
1931 }
1932
1933 /***********************************************************/
1934 /* Bluetooth support */
1935 static int nb_hcis;
1936 static int cur_hci;
1937 static struct HCIInfo *hci_table[MAX_NICS];
1938 #if 0
1939 static struct bt_vlan_s {
1940     struct bt_scatternet_s net;
1941     int id;
1942     struct bt_vlan_s *next;
1943 } *first_bt_vlan;
1944
1945 /* find or alloc a new bluetooth "VLAN" */
1946 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1947 {
1948     struct bt_vlan_s **pvlan, *vlan;
1949     for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1950         if (vlan->id == id)
1951             return &vlan->net;
1952     }
1953     vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1954     vlan->id = id;
1955     pvlan = &first_bt_vlan;
1956     while (*pvlan != NULL)
1957         pvlan = &(*pvlan)->next;
1958     *pvlan = vlan;
1959     return &vlan->net;
1960 }
1961 #endif
1962
1963 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1964 {
1965 }
1966
1967 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1968 {
1969     return -ENOTSUP;
1970 }
1971
1972 static struct HCIInfo null_hci = {
1973     .cmd_send = null_hci_send,
1974     .sco_send = null_hci_send,
1975     .acl_send = null_hci_send,
1976     .bdaddr_set = null_hci_addr_set,
1977 };
1978
1979 struct HCIInfo *qemu_next_hci(void)
1980 {
1981     if (cur_hci == nb_hcis)
1982         return &null_hci;
1983
1984     return hci_table[cur_hci++];
1985 }
1986
1987 /***********************************************************/
1988 /* QEMU Block devices */
1989
1990 #define HD_ALIAS "index=%d,media=disk"
1991 #ifdef TARGET_PPC
1992 #define CDROM_ALIAS "index=1,media=cdrom"
1993 #else
1994 #define CDROM_ALIAS "index=2,media=cdrom"
1995 #endif
1996 #define FD_ALIAS "index=%d,if=floppy"
1997 #define PFLASH_ALIAS "if=pflash"
1998 #define MTD_ALIAS "if=mtd"
1999 #define SD_ALIAS "index=0,if=sd"
2000
2001 static int drive_add(const char *file, const char *fmt, ...)
2002 {
2003     va_list ap;
2004
2005     if (nb_drives_opt >= MAX_DRIVES) {
2006         fprintf(stderr, "qemu: too many drives\n");
2007         exit(1);
2008     }
2009
2010     drives_opt[nb_drives_opt].file = file;
2011     va_start(ap, fmt);
2012     vsnprintf(drives_opt[nb_drives_opt].opt,
2013               sizeof(drives_opt[0].opt), fmt, ap);
2014     va_end(ap);
2015
2016     return nb_drives_opt++;
2017 }
2018
2019 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2020 {
2021     int index;
2022
2023     /* seek interface, bus and unit */
2024
2025     for (index = 0; index < nb_drives; index++)
2026         if (drives_table[index].type == type &&
2027             drives_table[index].bus == bus &&
2028             drives_table[index].unit == unit)
2029         return index;
2030
2031     return -1;
2032 }
2033
2034 int drive_get_max_bus(BlockInterfaceType type)
2035 {
2036     int max_bus;
2037     int index;
2038
2039     max_bus = -1;
2040     for (index = 0; index < nb_drives; index++) {
2041         if(drives_table[index].type == type &&
2042            drives_table[index].bus > max_bus)
2043             max_bus = drives_table[index].bus;
2044     }
2045     return max_bus;
2046 }
2047
2048 static void bdrv_format_print(void *opaque, const char *name)
2049 {
2050     fprintf(stderr, " %s", name);
2051 }
2052
2053 static int drive_init(struct drive_opt *arg, int snapshot,
2054                       QEMUMachine *machine)
2055 {
2056     char buf[128];
2057     char file[1024];
2058     char devname[128];
2059     const char *mediastr = "";
2060     BlockInterfaceType type;
2061     enum { MEDIA_DISK, MEDIA_CDROM } media;
2062     int bus_id, unit_id;
2063     int cyls, heads, secs, translation;
2064     BlockDriverState *bdrv;
2065     BlockDriver *drv = NULL;
2066     int max_devs;
2067     int index;
2068     int cache;
2069     int bdrv_flags;
2070     char *str = arg->opt;
2071     static const char * const params[] = { "bus", "unit", "if", "index",
2072                                            "cyls", "heads", "secs", "trans",
2073                                            "media", "snapshot", "file",
2074                                            "cache", "format", NULL };
2075
2076     if (check_params(buf, sizeof(buf), params, str) < 0) {
2077          fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2078                          buf, str);
2079          return -1;
2080     }
2081
2082     file[0] = 0;
2083     cyls = heads = secs = 0;
2084     bus_id = 0;
2085     unit_id = -1;
2086     translation = BIOS_ATA_TRANSLATION_AUTO;
2087     index = -1;
2088     cache = 1;
2089
2090     if (machine->use_scsi) {
2091         type = IF_SCSI;
2092         max_devs = MAX_SCSI_DEVS;
2093         pstrcpy(devname, sizeof(devname), "scsi");
2094     } else {
2095         type = IF_IDE;
2096         max_devs = MAX_IDE_DEVS;
2097         pstrcpy(devname, sizeof(devname), "ide");
2098     }
2099     media = MEDIA_DISK;
2100
2101     /* extract parameters */
2102
2103     if (get_param_value(buf, sizeof(buf), "bus", str)) {
2104         bus_id = strtol(buf, NULL, 0);
2105         if (bus_id < 0) {
2106             fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2107             return -1;
2108         }
2109     }
2110
2111     if (get_param_value(buf, sizeof(buf), "unit", str)) {
2112         unit_id = strtol(buf, NULL, 0);
2113         if (unit_id < 0) {
2114             fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2115             return -1;
2116         }
2117     }
2118
2119     if (get_param_value(buf, sizeof(buf), "if", str)) {
2120         pstrcpy(devname, sizeof(devname), buf);
2121         if (!strcmp(buf, "ide")) {
2122             type = IF_IDE;
2123             max_devs = MAX_IDE_DEVS;
2124         } else if (!strcmp(buf, "scsi")) {
2125             type = IF_SCSI;
2126             max_devs = MAX_SCSI_DEVS;
2127         } else if (!strcmp(buf, "floppy")) {
2128             type = IF_FLOPPY;
2129             max_devs = 0;
2130         } else if (!strcmp(buf, "pflash")) {
2131             type = IF_PFLASH;
2132             max_devs = 0;
2133         } else if (!strcmp(buf, "mtd")) {
2134             type = IF_MTD;
2135             max_devs = 0;
2136         } else if (!strcmp(buf, "sd")) {
2137             type = IF_SD;
2138             max_devs = 0;
2139         } else {
2140             fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2141             return -1;
2142         }
2143     }
2144
2145     if (get_param_value(buf, sizeof(buf), "index", str)) {
2146         index = strtol(buf, NULL, 0);
2147         if (index < 0) {
2148             fprintf(stderr, "qemu: '%s' invalid index\n", str);
2149             return -1;
2150         }
2151     }
2152
2153     if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2154         cyls = strtol(buf, NULL, 0);
2155     }
2156
2157     if (get_param_value(buf, sizeof(buf), "heads", str)) {
2158         heads = strtol(buf, NULL, 0);
2159     }
2160
2161     if (get_param_value(buf, sizeof(buf), "secs", str)) {
2162         secs = strtol(buf, NULL, 0);
2163     }
2164
2165     if (cyls || heads || secs) {
2166         if (cyls < 1 || cyls > 16383) {
2167             fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2168             return -1;
2169         }
2170         if (heads < 1 || heads > 16) {
2171             fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2172             return -1;
2173         }
2174         if (secs < 1 || secs > 63) {
2175             fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2176             return -1;
2177         }
2178     }
2179
2180     if (get_param_value(buf, sizeof(buf), "trans", str)) {
2181         if (!cyls) {
2182             fprintf(stderr,
2183                     "qemu: '%s' trans must be used with cyls,heads and secs\n",
2184                     str);
2185             return -1;
2186         }
2187         if (!strcmp(buf, "none"))
2188             translation = BIOS_ATA_TRANSLATION_NONE;
2189         else if (!strcmp(buf, "lba"))
2190             translation = BIOS_ATA_TRANSLATION_LBA;
2191         else if (!strcmp(buf, "auto"))
2192             translation = BIOS_ATA_TRANSLATION_AUTO;
2193         else {
2194             fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2195             return -1;
2196         }
2197     }
2198
2199     if (get_param_value(buf, sizeof(buf), "media", str)) {
2200         if (!strcmp(buf, "disk")) {
2201             media = MEDIA_DISK;
2202         } else if (!strcmp(buf, "cdrom")) {
2203             if (cyls || secs || heads) {
2204                 fprintf(stderr,
2205                         "qemu: '%s' invalid physical CHS format\n", str);
2206                 return -1;
2207             }
2208             media = MEDIA_CDROM;
2209         } else {
2210             fprintf(stderr, "qemu: '%s' invalid media\n", str);
2211             return -1;
2212         }
2213     }
2214
2215     if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2216         if (!strcmp(buf, "on"))
2217             snapshot = 1;
2218         else if (!strcmp(buf, "off"))
2219             snapshot = 0;
2220         else {
2221             fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2222             return -1;
2223         }
2224     }
2225
2226     if (get_param_value(buf, sizeof(buf), "cache", str)) {
2227         if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2228             cache = 0;
2229         else if (!strcmp(buf, "writethrough"))
2230             cache = 1;
2231         else if (!strcmp(buf, "writeback"))
2232             cache = 2;
2233         else {
2234            fprintf(stderr, "qemu: invalid cache option\n");
2235            return -1;
2236         }
2237     }
2238
2239     if (get_param_value(buf, sizeof(buf), "format", str)) {
2240        if (strcmp(buf, "?") == 0) {
2241             fprintf(stderr, "qemu: Supported formats:");
2242             bdrv_iterate_format(bdrv_format_print, NULL);
2243             fprintf(stderr, "\n");
2244             return -1;
2245         }
2246         drv = bdrv_find_format(buf);
2247         if (!drv) {
2248             fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2249             return -1;
2250         }
2251     }
2252
2253     if (arg->file == NULL)
2254         get_param_value(file, sizeof(file), "file", str);
2255     else
2256         pstrcpy(file, sizeof(file), arg->file);
2257
2258     /* compute bus and unit according index */
2259
2260     if (index != -1) {
2261         if (bus_id != 0 || unit_id != -1) {
2262             fprintf(stderr,
2263                     "qemu: '%s' index cannot be used with bus and unit\n", str);
2264             return -1;
2265         }
2266         if (max_devs == 0)
2267         {
2268             unit_id = index;
2269             bus_id = 0;
2270         } else {
2271             unit_id = index % max_devs;
2272             bus_id = index / max_devs;
2273         }
2274     }
2275
2276     /* if user doesn't specify a unit_id,
2277      * try to find the first free
2278      */
2279
2280     if (unit_id == -1) {
2281        unit_id = 0;
2282        while (drive_get_index(type, bus_id, unit_id) != -1) {
2283            unit_id++;
2284            if (max_devs && unit_id >= max_devs) {
2285                unit_id -= max_devs;
2286                bus_id++;
2287            }
2288        }
2289     }
2290
2291     /* check unit id */
2292
2293     if (max_devs && unit_id >= max_devs) {
2294         fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2295                         str, unit_id, max_devs - 1);
2296         return -1;
2297     }
2298
2299     /*
2300      * ignore multiple definitions
2301      */
2302
2303     if (drive_get_index(type, bus_id, unit_id) != -1)
2304         return 0;
2305
2306     /* init */
2307
2308     if (type == IF_IDE || type == IF_SCSI)
2309         mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2310     if (max_devs)
2311         snprintf(buf, sizeof(buf), "%s%i%s%i",
2312                  devname, bus_id, mediastr, unit_id);
2313     else
2314         snprintf(buf, sizeof(buf), "%s%s%i",
2315                  devname, mediastr, unit_id);
2316     bdrv = bdrv_new(buf);
2317     drives_table[nb_drives].bdrv = bdrv;
2318     drives_table[nb_drives].type = type;
2319     drives_table[nb_drives].bus = bus_id;
2320     drives_table[nb_drives].unit = unit_id;
2321     nb_drives++;
2322
2323     switch(type) {
2324     case IF_IDE:
2325     case IF_SCSI:
2326         switch(media) {
2327         case MEDIA_DISK:
2328             if (cyls != 0) {
2329                 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2330                 bdrv_set_translation_hint(bdrv, translation);
2331             }
2332             break;
2333         case MEDIA_CDROM:
2334             bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2335             break;
2336         }
2337         break;
2338     case IF_SD:
2339         /* FIXME: This isn't really a floppy, but it's a reasonable
2340            approximation.  */
2341     case IF_FLOPPY:
2342         bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2343         break;
2344     case IF_PFLASH:
2345     case IF_MTD:
2346         break;
2347     }
2348     if (!file[0])
2349         return 0;
2350     bdrv_flags = 0;
2351     if (snapshot) {
2352         bdrv_flags |= BDRV_O_SNAPSHOT;
2353         cache = 2; /* always use write-back with snapshot */
2354     }
2355     if (cache == 0) /* no caching */
2356         bdrv_flags |= BDRV_O_NOCACHE;
2357     else if (cache == 2) /* write-back */
2358         bdrv_flags |= BDRV_O_CACHE_WB;
2359     if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2360         fprintf(stderr, "qemu: could not open disk image %s\n",
2361                         file);
2362         return -1;
2363     }
2364     return 0;
2365 }
2366
2367 /***********************************************************/
2368 /* USB devices */
2369
2370 static USBPort *used_usb_ports;
2371 static USBPort *free_usb_ports;
2372
2373 /* ??? Maybe change this to register a hub to keep track of the topology.  */
2374 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2375                             usb_attachfn attach)
2376 {
2377     port->opaque = opaque;
2378     port->index = index;
2379     port->attach = attach;
2380     port->next = free_usb_ports;
2381     free_usb_ports = port;
2382 }
2383
2384 int usb_device_add_dev(USBDevice *dev)
2385 {
2386     USBPort *port;
2387
2388     /* Find a USB port to add the device to.  */
2389     port = free_usb_ports;
2390     if (!port->next) {
2391         USBDevice *hub;
2392
2393         /* Create a new hub and chain it on.  */
2394         free_usb_ports = NULL;
2395         port->next = used_usb_ports;
2396         used_usb_ports = port;
2397
2398         hub = usb_hub_init(VM_USB_HUB_SIZE);
2399         usb_attach(port, hub);
2400         port = free_usb_ports;
2401     }
2402
2403     free_usb_ports = port->next;
2404     port->next = used_usb_ports;
2405     used_usb_ports = port;
2406     usb_attach(port, dev);
2407     return 0;
2408 }
2409
2410 static int usb_device_add(const char *devname)
2411 {
2412     const char *p;
2413     USBDevice *dev;
2414
2415     if (!free_usb_ports)
2416         return -1;
2417
2418     if (strstart(devname, "host:", &p)) {
2419         dev = usb_host_device_open(p);
2420     } else if (!strcmp(devname, "mouse")) {
2421         dev = usb_mouse_init();
2422     } else if (!strcmp(devname, "tablet")) {
2423         dev = usb_tablet_init();
2424     } else if (!strcmp(devname, "keyboard")) {
2425         dev = usb_keyboard_init();
2426     } else if (strstart(devname, "disk:", &p)) {
2427         dev = usb_msd_init(p);
2428     } else if (!strcmp(devname, "wacom-tablet")) {
2429         dev = usb_wacom_init();
2430     } else if (strstart(devname, "serial:", &p)) {
2431         dev = usb_serial_init(p);
2432 #ifdef CONFIG_BRLAPI
2433     } else if (!strcmp(devname, "braille")) {
2434         dev = usb_baum_init();
2435 #endif
2436     } else if (strstart(devname, "net:", &p)) {
2437         int nic = nb_nics;
2438
2439         if (net_client_init("nic", p) < 0)
2440             return -1;
2441         nd_table[nic].model = "usb";
2442         dev = usb_net_init(&nd_table[nic]);
2443     } else {
2444         return -1;
2445     }
2446     if (!dev)
2447         return -1;
2448
2449     return usb_device_add_dev(dev);
2450 }
2451
2452 int usb_device_del_addr(int bus_num, int addr)
2453 {
2454     USBPort *port;
2455     USBPort **lastp;
2456     USBDevice *dev;
2457
2458     if (!used_usb_ports)
2459         return -1;
2460
2461     if (bus_num != 0)
2462         return -1;
2463
2464     lastp = &used_usb_ports;
2465     port = used_usb_ports;
2466     while (port && port->dev->addr != addr) {
2467         lastp = &port->next;
2468         port = port->next;
2469     }
2470
2471     if (!port)
2472         return -1;
2473
2474     dev = port->dev;
2475     *lastp = port->next;
2476     usb_attach(port, NULL);
2477     dev->handle_destroy(dev);
2478     port->next = free_usb_ports;
2479     free_usb_ports = port;
2480     return 0;
2481 }
2482
2483 static int usb_device_del(const char *devname)
2484 {
2485     int bus_num, addr;
2486     const char *p;
2487
2488     if (strstart(devname, "host:", &p))
2489         return usb_host_device_close(p);
2490
2491     if (!used_usb_ports)
2492         return -1;
2493
2494     p = strchr(devname, '.');
2495     if (!p)
2496         return -1;
2497     bus_num = strtoul(devname, NULL, 0);
2498     addr = strtoul(p + 1, NULL, 0);
2499
2500     return usb_device_del_addr(bus_num, addr);
2501 }
2502
2503 void do_usb_add(const char *devname)
2504 {
2505     usb_device_add(devname);
2506 }
2507
2508 void do_usb_del(const char *devname)
2509 {
2510     usb_device_del(devname);
2511 }
2512
2513 void usb_info(void)
2514 {
2515     USBDevice *dev;
2516     USBPort *port;
2517     const char *speed_str;
2518
2519     if (!usb_enabled) {
2520         term_printf("USB support not enabled\n");
2521         return;
2522     }
2523
2524     for (port = used_usb_ports; port; port = port->next) {
2525         dev = port->dev;
2526         if (!dev)
2527             continue;
2528         switch(dev->speed) {
2529         case USB_SPEED_LOW:
2530             speed_str = "1.5";
2531             break;
2532         case USB_SPEED_FULL:
2533             speed_str = "12";
2534             break;
2535         case USB_SPEED_HIGH:
2536             speed_str = "480";
2537             break;
2538         default:
2539             speed_str = "?";
2540             break;
2541         }
2542         term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
2543                     0, dev->addr, speed_str, dev->devname);
2544     }
2545 }
2546
2547 /***********************************************************/
2548 /* PCMCIA/Cardbus */
2549
2550 static struct pcmcia_socket_entry_s {
2551     struct pcmcia_socket_s *socket;
2552     struct pcmcia_socket_entry_s *next;
2553 } *pcmcia_sockets = 0;
2554
2555 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2556 {
2557     struct pcmcia_socket_entry_s *entry;
2558
2559     entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2560     entry->socket = socket;
2561     entry->next = pcmcia_sockets;
2562     pcmcia_sockets = entry;
2563 }
2564
2565 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2566 {
2567     struct pcmcia_socket_entry_s *entry, **ptr;
2568
2569     ptr = &pcmcia_sockets;
2570     for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2571         if (entry->socket == socket) {
2572             *ptr = entry->next;
2573             qemu_free(entry);
2574         }
2575 }
2576
2577 void pcmcia_info(void)
2578 {
2579     struct pcmcia_socket_entry_s *iter;
2580     if (!pcmcia_sockets)
2581         term_printf("No PCMCIA sockets\n");
2582
2583     for (iter = pcmcia_sockets; iter; iter = iter->next)
2584         term_printf("%s: %s\n", iter->socket->slot_string,
2585                     iter->socket->attached ? iter->socket->card_string :
2586                     "Empty");
2587 }
2588
2589 /***********************************************************/
2590 /* dumb display */
2591
2592 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2593 {
2594 }
2595
2596 static void dumb_resize(DisplayState *ds, int w, int h)
2597 {
2598 }
2599
2600 static void dumb_display_init(DisplayState *ds)
2601 {
2602     ds->data = NULL;
2603     ds->linesize = 0;
2604     ds->depth = 0;
2605     ds->dpy_update = dumb_update;
2606     ds->dpy_resize = dumb_resize;
2607     ds->dpy_refresh = NULL;
2608     ds->gui_timer_interval = 0;
2609     ds->idle = 1;
2610 }
2611
2612 /***********************************************************/
2613 /* I/O handling */
2614
2615 #define MAX_IO_HANDLERS 64
2616
2617 typedef struct IOHandlerRecord {
2618     int fd;
2619     IOCanRWHandler *fd_read_poll;
2620     IOHandler *fd_read;
2621     IOHandler *fd_write;
2622     int deleted;
2623     void *opaque;
2624     /* temporary data */
2625     struct pollfd *ufd;
2626     struct IOHandlerRecord *next;
2627 } IOHandlerRecord;
2628
2629 static IOHandlerRecord *first_io_handler;
2630
2631 /* XXX: fd_read_poll should be suppressed, but an API change is
2632    necessary in the character devices to suppress fd_can_read(). */
2633 int qemu_set_fd_handler2(int fd,
2634                          IOCanRWHandler *fd_read_poll,
2635                          IOHandler *fd_read,
2636                          IOHandler *fd_write,
2637                          void *opaque)
2638 {
2639     IOHandlerRecord **pioh, *ioh;
2640
2641     if (!fd_read && !fd_write) {
2642         pioh = &first_io_handler;
2643         for(;;) {
2644             ioh = *pioh;
2645             if (ioh == NULL)
2646                 break;
2647             if (ioh->fd == fd) {
2648                 ioh->deleted = 1;
2649                 break;
2650             }
2651             pioh = &ioh->next;
2652         }
2653     } else {
2654         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2655             if (ioh->fd == fd)
2656                 goto found;
2657         }
2658         ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2659         if (!ioh)
2660             return -1;
2661         ioh->next = first_io_handler;
2662         first_io_handler = ioh;
2663     found:
2664         ioh->fd = fd;
2665         ioh->fd_read_poll = fd_read_poll;
2666         ioh->fd_read = fd_read;
2667         ioh->fd_write = fd_write;
2668         ioh->opaque = opaque;
2669         ioh->deleted = 0;
2670     }
2671     return 0;
2672 }
2673
2674 int qemu_set_fd_handler(int fd,
2675                         IOHandler *fd_read,
2676                         IOHandler *fd_write,
2677                         void *opaque)
2678 {
2679     return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2680 }
2681
2682 #ifdef _WIN32
2683 /***********************************************************/
2684 /* Polling handling */
2685
2686 typedef struct PollingEntry {
2687     PollingFunc *func;
2688     void *opaque;
2689     struct PollingEntry *next;
2690 } PollingEntry;
2691
2692 static PollingEntry *first_polling_entry;
2693
2694 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2695 {
2696     PollingEntry **ppe, *pe;
2697     pe = qemu_mallocz(sizeof(PollingEntry));
2698     if (!pe)
2699         return -1;
2700     pe->func = func;
2701     pe->opaque = opaque;
2702     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2703     *ppe = pe;
2704     return 0;
2705 }
2706
2707 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2708 {
2709     PollingEntry **ppe, *pe;
2710     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2711         pe = *ppe;
2712         if (pe->func == func && pe->opaque == opaque) {
2713             *ppe = pe->next;
2714             qemu_free(pe);
2715             break;
2716         }
2717     }
2718 }
2719
2720 /***********************************************************/
2721 /* Wait objects support */
2722 typedef struct WaitObjects {
2723     int num;
2724     HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2725     WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2726     void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2727 } WaitObjects;
2728
2729 static WaitObjects wait_objects = {0};
2730
2731 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2732 {
2733     WaitObjects *w = &wait_objects;
2734
2735     if (w->num >= MAXIMUM_WAIT_OBJECTS)
2736         return -1;
2737     w->events[w->num] = handle;
2738     w->func[w->num] = func;
2739     w->opaque[w->num] = opaque;
2740     w->num++;
2741     return 0;
2742 }
2743
2744 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2745 {
2746     int i, found;
2747     WaitObjects *w = &wait_objects;
2748
2749     found = 0;
2750     for (i = 0; i < w->num; i++) {
2751         if (w->events[i] == handle)
2752             found = 1;
2753         if (found) {
2754             w->events[i] = w->events[i + 1];
2755             w->func[i] = w->func[i + 1];
2756             w->opaque[i] = w->opaque[i + 1];
2757         }
2758     }
2759     if (found)
2760         w->num--;
2761 }
2762 #endif
2763
2764 #define SELF_ANNOUNCE_ROUNDS 5
2765 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
2766 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
2767 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
2768
2769 static int announce_self_create(uint8_t *buf, 
2770                                 uint8_t *mac_addr)
2771 {
2772     uint32_t magic = EXPERIMENTAL_MAGIC;
2773     uint16_t proto = htons(ETH_P_EXPERIMENTAL);
2774
2775     /* FIXME: should we send a different packet (arp/rarp/ping)? */
2776
2777     memset(buf, 0xff, 6);         /* h_dst */
2778     memcpy(buf + 6, mac_addr, 6); /* h_src */
2779     memcpy(buf + 12, &proto, 2);  /* h_proto */
2780     memcpy(buf + 14, &magic, 4);  /* magic */
2781
2782     return 18; /* len */
2783 }
2784
2785 void qemu_announce_self(void)
2786 {
2787     int i, j, len;
2788     VLANState *vlan;
2789     VLANClientState *vc;
2790     uint8_t buf[256];
2791
2792     for (i = 0; i < nb_nics; i++) {
2793         len = announce_self_create(buf, nd_table[i].macaddr);
2794         vlan = nd_table[i].vlan;
2795         for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2796             for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
2797                 vc->fd_read(vc->opaque, buf, len);
2798         }
2799     }
2800 }
2801
2802 /***********************************************************/
2803 /* savevm/loadvm support */
2804
2805 #define IO_BUF_SIZE 32768
2806
2807 struct QEMUFile {
2808     QEMUFilePutBufferFunc *put_buffer;
2809     QEMUFileGetBufferFunc *get_buffer;
2810     QEMUFileCloseFunc *close;
2811     QEMUFileRateLimit *rate_limit;
2812     void *opaque;
2813     int is_write;
2814
2815     int64_t buf_offset; /* start of buffer when writing, end of buffer
2816                            when reading */
2817     int buf_index;
2818     int buf_size; /* 0 when writing */
2819     uint8_t buf[IO_BUF_SIZE];
2820
2821     int has_error;
2822 };
2823
2824 typedef struct QEMUFileSocket
2825 {
2826     int fd;
2827     QEMUFile *file;
2828 } QEMUFileSocket;
2829
2830 static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2831 {
2832     QEMUFileSocket *s = opaque;
2833     ssize_t len;
2834
2835     do {
2836         len = recv(s->fd, buf, size, 0);
2837     } while (len == -1 && socket_error() == EINTR);
2838
2839     if (len == -1)
2840         len = -socket_error();
2841
2842     return len;
2843 }
2844
2845 static int socket_close(void *opaque)
2846 {
2847     QEMUFileSocket *s = opaque;
2848     qemu_free(s);
2849     return 0;
2850 }
2851
2852 QEMUFile *qemu_fopen_socket(int fd)
2853 {
2854     QEMUFileSocket *s = qemu_mallocz(sizeof(QEMUFileSocket));
2855
2856     if (s == NULL)
2857         return NULL;
2858
2859     s->fd = fd;
2860     s->file = qemu_fopen_ops(s, NULL, socket_get_buffer, socket_close, NULL);
2861     return s->file;
2862 }
2863
2864 typedef struct QEMUFileStdio
2865 {
2866     FILE *outfile;
2867 } QEMUFileStdio;
2868
2869 static int file_put_buffer(void *opaque, const uint8_t *buf,
2870                             int64_t pos, int size)
2871 {
2872     QEMUFileStdio *s = opaque;
2873     fseek(s->outfile, pos, SEEK_SET);
2874     fwrite(buf, 1, size, s->outfile);
2875     return size;
2876 }
2877
2878 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2879 {
2880     QEMUFileStdio *s = opaque;
2881     fseek(s->outfile, pos, SEEK_SET);
2882     return fread(buf, 1, size, s->outfile);
2883 }
2884
2885 static int file_close(void *opaque)
2886 {
2887     QEMUFileStdio *s = opaque;
2888     fclose(s->outfile);
2889     qemu_free(s);
2890     return 0;
2891 }
2892
2893 QEMUFile *qemu_fopen(const char *filename, const char *mode)
2894 {
2895     QEMUFileStdio *s;
2896
2897     s = qemu_mallocz(sizeof(QEMUFileStdio));
2898     if (!s)
2899         return NULL;
2900
2901     s->outfile = fopen(filename, mode);
2902     if (!s->outfile)
2903         goto fail;
2904
2905     if (!strcmp(mode, "wb"))
2906         return qemu_fopen_ops(s, file_put_buffer, NULL, file_close, NULL);
2907     else if (!strcmp(mode, "rb"))
2908         return qemu_fopen_ops(s, NULL, file_get_buffer, file_close, NULL);
2909
2910 fail:
2911     if (s->outfile)
2912         fclose(s->outfile);
2913     qemu_free(s);
2914     return NULL;
2915 }
2916
2917 typedef struct QEMUFileBdrv
2918 {
2919     BlockDriverState *bs;
2920     int64_t base_offset;
2921 } QEMUFileBdrv;
2922
2923 static int bdrv_put_buffer(void *opaque, const uint8_t *buf,
2924                            int64_t pos, int size)
2925 {
2926     QEMUFileBdrv *s = opaque;
2927     bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
2928     return size;
2929 }
2930
2931 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2932 {
2933     QEMUFileBdrv *s = opaque;
2934     return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
2935 }
2936
2937 static int bdrv_fclose(void *opaque)
2938 {
2939     QEMUFileBdrv *s = opaque;
2940     qemu_free(s);
2941     return 0;
2942 }
2943
2944 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
2945 {
2946     QEMUFileBdrv *s;
2947
2948     s = qemu_mallocz(sizeof(QEMUFileBdrv));
2949     if (!s)
2950         return NULL;
2951
2952     s->bs = bs;
2953     s->base_offset = offset;
2954
2955     if (is_writable)
2956         return qemu_fopen_ops(s, bdrv_put_buffer, NULL, bdrv_fclose, NULL);
2957
2958     return qemu_fopen_ops(s, NULL, bdrv_get_buffer, bdrv_fclose, NULL);
2959 }
2960
2961 QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
2962                          QEMUFileGetBufferFunc *get_buffer,
2963                          QEMUFileCloseFunc *close,
2964                          QEMUFileRateLimit *rate_limit)
2965 {
2966     QEMUFile *f;
2967
2968     f = qemu_mallocz(sizeof(QEMUFile));
2969     if (!f)
2970         return NULL;
2971
2972     f->opaque = opaque;
2973     f->put_buffer = put_buffer;
2974     f->get_buffer = get_buffer;
2975     f->close = close;
2976     f->rate_limit = rate_limit;
2977     f->is_write = 0;
2978
2979     return f;
2980 }
2981
2982 int qemu_file_has_error(QEMUFile *f)
2983 {
2984     return f->has_error;
2985 }
2986
2987 void qemu_fflush(QEMUFile *f)
2988 {
2989     if (!f->put_buffer)
2990         return;
2991
2992     if (f->is_write && f->buf_index > 0) {
2993         int len;
2994
2995         len = f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
2996         if (len > 0)
2997             f->buf_offset += f->buf_index;
2998         else
2999             f->has_error = 1;
3000         f->buf_index = 0;
3001     }
3002 }
3003
3004 static void qemu_fill_buffer(QEMUFile *f)
3005 {
3006     int len;
3007
3008     if (!f->get_buffer)
3009         return;
3010
3011     if (f->is_write)
3012         abort();
3013
3014     len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
3015     if (len > 0) {
3016         f->buf_index = 0;
3017         f->buf_size = len;
3018         f->buf_offset += len;
3019     } else if (len != -EAGAIN)
3020         f->has_error = 1;
3021 }
3022
3023 int qemu_fclose(QEMUFile *f)
3024 {
3025     int ret = 0;
3026     qemu_fflush(f);
3027     if (f->close)
3028         ret = f->close(f->opaque);
3029     qemu_free(f);
3030     return ret;
3031 }
3032
3033 void qemu_file_put_notify(QEMUFile *f)
3034 {
3035     f->put_buffer(f->opaque, NULL, 0, 0);
3036 }
3037
3038 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3039 {
3040     int l;
3041
3042     if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
3043         fprintf(stderr,
3044                 "Attempted to write to buffer while read buffer is not empty\n");
3045         abort();
3046     }
3047
3048     while (!f->has_error && size > 0) {
3049         l = IO_BUF_SIZE - f->buf_index;
3050         if (l > size)
3051             l = size;
3052         memcpy(f->buf + f->buf_index, buf, l);
3053         f->is_write = 1;
3054         f->buf_index += l;
3055         buf += l;
3056         size -= l;
3057         if (f->buf_index >= IO_BUF_SIZE)
3058             qemu_fflush(f);
3059     }
3060 }
3061
3062 void qemu_put_byte(QEMUFile *f, int v)
3063 {
3064     if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
3065         fprintf(stderr,
3066                 "Attempted to write to buffer while read buffer is not empty\n");
3067         abort();
3068     }
3069
3070     f->buf[f->buf_index++] = v;
3071     f->is_write = 1;
3072     if (f->buf_index >= IO_BUF_SIZE)
3073         qemu_fflush(f);
3074 }
3075
3076 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
3077 {
3078     int size, l;
3079
3080     if (f->is_write)
3081         abort();
3082
3083     size = size1;
3084     while (size > 0) {
3085         l = f->buf_size - f->buf_index;
3086         if (l == 0) {
3087             qemu_fill_buffer(f);
3088             l = f->buf_size - f->buf_index;
3089             if (l == 0)
3090                 break;
3091         }
3092         if (l > size)
3093             l = size;
3094         memcpy(buf, f->buf + f->buf_index, l);
3095         f->buf_index += l;
3096         buf += l;
3097         size -= l;
3098     }
3099     return size1 - size;
3100 }
3101
3102 int qemu_get_byte(QEMUFile *f)
3103 {
3104     if (f->is_write)
3105         abort();
3106
3107     if (f->buf_index >= f->buf_size) {
3108         qemu_fill_buffer(f);
3109         if (f->buf_index >= f->buf_size)
3110             return 0;
3111     }
3112     return f->buf[f->buf_index++];
3113 }
3114
3115 int64_t qemu_ftell(QEMUFile *f)
3116 {
3117     return f->buf_offset - f->buf_size + f->buf_index;
3118 }
3119
3120 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3121 {
3122     if (whence == SEEK_SET) {
3123         /* nothing to do */
3124     } else if (whence == SEEK_CUR) {
3125         pos += qemu_ftell(f);
3126     } else {
3127         /* SEEK_END not supported */
3128         return -1;
3129     }
3130     if (f->put_buffer) {
3131         qemu_fflush(f);
3132         f->buf_offset = pos;
3133     } else {
3134         f->buf_offset = pos;
3135         f->buf_index = 0;
3136         f->buf_size = 0;
3137     }
3138     return pos;
3139 }
3140
3141 int qemu_file_rate_limit(QEMUFile *f)
3142 {
3143     if (f->rate_limit)
3144         return f->rate_limit(f->opaque);
3145
3146     return 0;
3147 }
3148
3149 void qemu_put_be16(QEMUFile *f, unsigned int v)
3150 {
3151     qemu_put_byte(f, v >> 8);
3152     qemu_put_byte(f, v);
3153 }
3154
3155 void qemu_put_be32(QEMUFile *f, unsigned int v)
3156 {
3157     qemu_put_byte(f, v >> 24);
3158     qemu_put_byte(f, v >> 16);
3159     qemu_put_byte(f, v >> 8);
3160     qemu_put_byte(f, v);
3161 }
3162
3163 void qemu_put_be64(QEMUFile *f, uint64_t v)
3164 {
3165     qemu_put_be32(f, v >> 32);
3166     qemu_put_be32(f, v);
3167 }
3168
3169 unsigned int qemu_get_be16(QEMUFile *f)
3170 {
3171     unsigned int v;
3172     v = qemu_get_byte(f) << 8;
3173     v |= qemu_get_byte(f);
3174     return v;
3175 }
3176
3177 unsigned int qemu_get_be32(QEMUFile *f)
3178 {
3179     unsigned int v;
3180     v = qemu_get_byte(f) << 24;
3181     v |= qemu_get_byte(f) << 16;
3182     v |= qemu_get_byte(f) << 8;
3183     v |= qemu_get_byte(f);
3184     return v;
3185 }
3186
3187 uint64_t qemu_get_be64(QEMUFile *f)
3188 {
3189     uint64_t v;
3190     v = (uint64_t)qemu_get_be32(f) << 32;
3191     v |= qemu_get_be32(f);
3192     return v;
3193 }
3194
3195 typedef struct SaveStateEntry {
3196     char idstr[256];
3197     int instance_id;
3198     int version_id;
3199     int section_id;
3200     SaveLiveStateHandler *save_live_state;
3201     SaveStateHandler *save_state;
3202     LoadStateHandler *load_state;
3203     void *opaque;
3204     struct SaveStateEntry *next;
3205 } SaveStateEntry;
3206
3207 static SaveStateEntry *first_se;
3208
3209 /* TODO: Individual devices generally have very little idea about the rest
3210    of the system, so instance_id should be removed/replaced.
3211    Meanwhile pass -1 as instance_id if you do not already have a clearly
3212    distinguishing id for all instances of your device class. */
3213 int register_savevm_live(const char *idstr,
3214                          int instance_id,
3215                          int version_id,
3216                          SaveLiveStateHandler *save_live_state,
3217                          SaveStateHandler *save_state,
3218                          LoadStateHandler *load_state,
3219                          void *opaque)
3220 {
3221     SaveStateEntry *se, **pse;
3222     static int global_section_id;
3223
3224     se = qemu_malloc(sizeof(SaveStateEntry));
3225     if (!se)
3226         return -1;
3227     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3228     se->instance_id = (instance_id == -1) ? 0 : instance_id;
3229     se->version_id = version_id;
3230     se->section_id = global_section_id++;
3231     se->save_live_state = save_live_state;
3232     se->save_state = save_state;
3233     se->load_state = load_state;
3234     se->opaque = opaque;
3235     se->next = NULL;
3236
3237     /* add at the end of list */
3238     pse = &first_se;
3239     while (*pse != NULL) {
3240         if (instance_id == -1
3241                 && strcmp(se->idstr, (*pse)->idstr) == 0
3242                 && se->instance_id <= (*pse)->instance_id)
3243             se->instance_id = (*pse)->instance_id + 1;
3244         pse = &(*pse)->next;
3245     }
3246     *pse = se;
3247     return 0;
3248 }
3249
3250 int register_savevm(const char *idstr,
3251                     int instance_id,
3252                     int version_id,
3253                     SaveStateHandler *save_state,
3254                     LoadStateHandler *load_state,
3255                     void *opaque)
3256 {
3257     return register_savevm_live(idstr, instance_id, version_id,
3258                                 NULL, save_state, load_state, opaque);
3259 }
3260
3261 #define QEMU_VM_FILE_MAGIC           0x5145564d
3262 #define QEMU_VM_FILE_VERSION_COMPAT  0x00000002
3263 #define QEMU_VM_FILE_VERSION         0x00000003
3264
3265 #define QEMU_VM_EOF                  0x00
3266 #define QEMU_VM_SECTION_START        0x01
3267 #define QEMU_VM_SECTION_PART         0x02
3268 #define QEMU_VM_SECTION_END          0x03
3269 #define QEMU_VM_SECTION_FULL         0x04
3270
3271 int qemu_savevm_state_begin(QEMUFile *f)
3272 {
3273     SaveStateEntry *se;
3274
3275     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3276     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3277
3278     for (se = first_se; se != NULL; se = se->next) {
3279         int len;
3280
3281         if (se->save_live_state == NULL)
3282             continue;
3283
3284         /* Section type */
3285         qemu_put_byte(f, QEMU_VM_SECTION_START);
3286         qemu_put_be32(f, se->section_id);
3287
3288         /* ID string */
3289         len = strlen(se->idstr);
3290         qemu_put_byte(f, len);
3291         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3292
3293         qemu_put_be32(f, se->instance_id);
3294         qemu_put_be32(f, se->version_id);
3295
3296         se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
3297     }
3298
3299     if (qemu_file_has_error(f))
3300         return -EIO;
3301
3302     return 0;
3303 }
3304
3305 int qemu_savevm_state_iterate(QEMUFile *f)
3306 {
3307     SaveStateEntry *se;
3308     int ret = 1;
3309
3310     for (se = first_se; se != NULL; se = se->next) {
3311         if (se->save_live_state == NULL)
3312             continue;
3313
3314         /* Section type */
3315         qemu_put_byte(f, QEMU_VM_SECTION_PART);
3316         qemu_put_be32(f, se->section_id);
3317
3318         ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
3319     }
3320
3321     if (ret)
3322         return 1;
3323
3324     if (qemu_file_has_error(f))
3325         return -EIO;
3326
3327     return 0;
3328 }
3329
3330 int qemu_savevm_state_complete(QEMUFile *f)
3331 {
3332     SaveStateEntry *se;
3333
3334     for (se = first_se; se != NULL; se = se->next) {
3335         if (se->save_live_state == NULL)
3336             continue;
3337
3338         /* Section type */
3339         qemu_put_byte(f, QEMU_VM_SECTION_END);
3340         qemu_put_be32(f, se->section_id);
3341
3342         se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
3343     }
3344
3345     for(se = first_se; se != NULL; se = se->next) {
3346         int len;
3347
3348         if (se->save_state == NULL)
3349             continue;
3350
3351         /* Section type */
3352         qemu_put_byte(f, QEMU_VM_SECTION_FULL);
3353         qemu_put_be32(f, se->section_id);
3354
3355         /* ID string */
3356         len = strlen(se->idstr);
3357         qemu_put_byte(f, len);
3358         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3359
3360         qemu_put_be32(f, se->instance_id);
3361         qemu_put_be32(f, se->version_id);
3362
3363         se->save_state(f, se->opaque);
3364     }
3365
3366     qemu_put_byte(f, QEMU_VM_EOF);
3367
3368     if (qemu_file_has_error(f))
3369         return -EIO;
3370
3371     return 0;
3372 }
3373
3374 int qemu_savevm_state(QEMUFile *f)
3375 {
3376     int saved_vm_running;
3377     int ret;
3378
3379     saved_vm_running = vm_running;
3380     vm_stop(0);
3381
3382     bdrv_flush_all();
3383
3384     ret = qemu_savevm_state_begin(f);
3385     if (ret < 0)
3386         goto out;
3387
3388     do {
3389         ret = qemu_savevm_state_iterate(f);
3390         if (ret < 0)
3391             goto out;
3392     } while (ret == 0);
3393
3394     ret = qemu_savevm_state_complete(f);
3395
3396 out:
3397     if (qemu_file_has_error(f))
3398         ret = -EIO;
3399
3400     if (!ret && saved_vm_running)
3401         vm_start();
3402
3403     return ret;
3404 }
3405
3406 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3407 {
3408     SaveStateEntry *se;
3409
3410     for(se = first_se; se != NULL; se = se->next) {
3411         if (!strcmp(se->idstr, idstr) &&
3412             instance_id == se->instance_id)
3413             return se;
3414     }
3415     return NULL;
3416 }
3417
3418 typedef struct LoadStateEntry {
3419     SaveStateEntry *se;
3420     int section_id;
3421     int version_id;
3422     struct LoadStateEntry *next;
3423 } LoadStateEntry;
3424
3425 static int qemu_loadvm_state_v2(QEMUFile *f)
3426 {
3427     SaveStateEntry *se;
3428     int len, ret, instance_id, record_len, version_id;
3429     int64_t total_len, end_pos, cur_pos;
3430     char idstr[256];
3431
3432     total_len = qemu_get_be64(f);
3433     end_pos = total_len + qemu_ftell(f);
3434     for(;;) {
3435         if (qemu_ftell(f) >= end_pos)
3436             break;
3437         len = qemu_get_byte(f);
3438         qemu_get_buffer(f, (uint8_t *)idstr, len);
3439         idstr[len] = '\0';
3440         instance_id = qemu_get_be32(f);
3441         version_id = qemu_get_be32(f);
3442         record_len = qemu_get_be32(f);
3443         cur_pos = qemu_ftell(f);
3444         se = find_se(idstr, instance_id);
3445         if (!se) {
3446             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3447                     instance_id, idstr);
3448         } else {
3449             ret = se->load_state(f, se->opaque, version_id);
3450             if (ret < 0) {
3451                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3452                         instance_id, idstr);
3453             }
3454         }
3455         /* always seek to exact end of record */
3456         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3457     }
3458
3459     if (qemu_file_has_error(f))
3460         return -EIO;
3461
3462     return 0;
3463 }
3464
3465 int qemu_loadvm_state(QEMUFile *f)
3466 {
3467     LoadStateEntry *first_le = NULL;
3468     uint8_t section_type;
3469     unsigned int v;
3470     int ret;
3471
3472     v = qemu_get_be32(f);
3473     if (v != QEMU_VM_FILE_MAGIC)
3474         return -EINVAL;
3475
3476     v = qemu_get_be32(f);
3477     if (v == QEMU_VM_FILE_VERSION_COMPAT)
3478         return qemu_loadvm_state_v2(f);
3479     if (v != QEMU_VM_FILE_VERSION)
3480         return -ENOTSUP;
3481
3482     while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
3483         uint32_t instance_id, version_id, section_id;
3484         LoadStateEntry *le;
3485         SaveStateEntry *se;
3486         char idstr[257];
3487         int len;
3488
3489         switch (section_type) {
3490         case QEMU_VM_SECTION_START:
3491         case QEMU_VM_SECTION_FULL:
3492             /* Read section start */
3493             section_id = qemu_get_be32(f);
3494             len = qemu_get_byte(f);
3495             qemu_get_buffer(f, (uint8_t *)idstr, len);
3496             idstr[len] = 0;
3497             instance_id = qemu_get_be32(f);
3498             version_id = qemu_get_be32(f);
3499
3500             /* Find savevm section */
3501             se = find_se(idstr, instance_id);
3502             if (se == NULL) {
3503                 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
3504                 ret = -EINVAL;
3505                 goto out;
3506             }
3507
3508             /* Validate version */
3509             if (version_id > se->version_id) {
3510                 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
3511                         version_id, idstr, se->version_id);
3512                 ret = -EINVAL;
3513                 goto out;
3514             }
3515
3516             /* Add entry */
3517             le = qemu_mallocz(sizeof(*le));
3518             if (le == NULL) {
3519                 ret = -ENOMEM;
3520                 goto out;
3521             }
3522
3523             le->se = se;
3524             le->section_id = section_id;
3525             le->version_id = version_id;
3526             le->next = first_le;
3527             first_le = le;
3528
3529             le->se->load_state(f, le->se->opaque, le->version_id);
3530             break;
3531         case QEMU_VM_SECTION_PART:
3532         case QEMU_VM_SECTION_END:
3533             section_id = qemu_get_be32(f);
3534
3535             for (le = first_le; le && le->section_id != section_id; le = le->next);
3536             if (le == NULL) {
3537                 fprintf(stderr, "Unknown savevm section %d\n", section_id);
3538                 ret = -EINVAL;
3539                 goto out;
3540             }
3541
3542             le->se->load_state(f, le->se->opaque, le->version_id);
3543             break;
3544         default:
3545             fprintf(stderr, "Unknown savevm section type %d\n", section_type);
3546             ret = -EINVAL;
3547             goto out;
3548         }
3549     }
3550
3551     ret = 0;
3552
3553 out:
3554     while (first_le) {
3555         LoadStateEntry *le = first_le;
3556         first_le = first_le->next;
3557         qemu_free(le);
3558     }
3559
3560     if (qemu_file_has_error(f))
3561         ret = -EIO;
3562
3563     return ret;
3564 }
3565
3566 /* device can contain snapshots */
3567 static int bdrv_can_snapshot(BlockDriverState *bs)
3568 {
3569     return (bs &&
3570             !bdrv_is_removable(bs) &&
3571             !bdrv_is_read_only(bs));
3572 }
3573
3574 /* device must be snapshots in order to have a reliable snapshot */
3575 static int bdrv_has_snapshot(BlockDriverState *bs)
3576 {
3577     return (bs &&
3578             !bdrv_is_removable(bs) &&
3579             !bdrv_is_read_only(bs));
3580 }
3581
3582 static BlockDriverState *get_bs_snapshots(void)
3583 {
3584     BlockDriverState *bs;
3585     int i;
3586
3587     if (bs_snapshots)
3588         return bs_snapshots;
3589     for(i = 0; i <= nb_drives; i++) {
3590         bs = drives_table[i].bdrv;
3591         if (bdrv_can_snapshot(bs))
3592             goto ok;
3593     }
3594     return NULL;
3595  ok:
3596     bs_snapshots = bs;
3597     return bs;
3598 }
3599
3600 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
3601                               const char *name)
3602 {
3603     QEMUSnapshotInfo *sn_tab, *sn;
3604     int nb_sns, i, ret;
3605
3606     ret = -ENOENT;
3607     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3608     if (nb_sns < 0)
3609         return ret;
3610     for(i = 0; i < nb_sns; i++) {
3611         sn = &sn_tab[i];
3612         if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
3613             *sn_info = *sn;
3614             ret = 0;
3615             break;
3616         }
3617     }
3618     qemu_free(sn_tab);
3619     return ret;
3620 }
3621
3622 void do_savevm(const char *name)
3623 {
3624     BlockDriverState *bs, *bs1;
3625     QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
3626     int must_delete, ret, i;
3627     BlockDriverInfo bdi1, *bdi = &bdi1;
3628     QEMUFile *f;
3629     int saved_vm_running;
3630 #ifdef _WIN32
3631     struct _timeb tb;
3632 #else
3633     struct timeval tv;
3634 #endif
3635
3636     bs = get_bs_snapshots();
3637     if (!bs) {
3638         term_printf("No block device can accept snapshots\n");
3639         return;
3640     }
3641
3642     /* ??? Should this occur after vm_stop?  */
3643     qemu_aio_flush();
3644
3645     saved_vm_running = vm_running;
3646     vm_stop(0);
3647
3648     must_delete = 0;
3649     if (name) {
3650         ret = bdrv_snapshot_find(bs, old_sn, name);
3651         if (ret >= 0) {
3652             must_delete = 1;
3653         }
3654     }
3655     memset(sn, 0, sizeof(*sn));
3656     if (must_delete) {
3657         pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
3658         pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
3659     } else {
3660         if (name)
3661             pstrcpy(sn->name, sizeof(sn->name), name);
3662     }
3663
3664     /* fill auxiliary fields */
3665 #ifdef _WIN32
3666     _ftime(&tb);
3667     sn->date_sec = tb.time;
3668     sn->date_nsec = tb.millitm * 1000000;
3669 #else
3670     gettimeofday(&tv, NULL);
3671     sn->date_sec = tv.tv_sec;
3672     sn->date_nsec = tv.tv_usec * 1000;
3673 #endif
3674     sn->vm_clock_nsec = qemu_get_clock(vm_clock);
3675
3676     if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3677         term_printf("Device %s does not support VM state snapshots\n",
3678                     bdrv_get_device_name(bs));
3679         goto the_end;
3680     }
3681
3682     /* save the VM state */
3683     f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
3684     if (!f) {
3685         term_printf("Could not open VM state file\n");
3686         goto the_end;
3687     }
3688     ret = qemu_savevm_state(f);
3689     sn->vm_state_size = qemu_ftell(f);
3690     qemu_fclose(f);
3691     if (ret < 0) {
3692         term_printf("Error %d while writing VM\n", ret);
3693         goto the_end;
3694     }
3695
3696     /* create the snapshots */
3697
3698     for(i = 0; i < nb_drives; i++) {
3699         bs1 = drives_table[i].bdrv;
3700         if (bdrv_has_snapshot(bs1)) {
3701             if (must_delete) {
3702                 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
3703                 if (ret < 0) {
3704                     term_printf("Error while deleting snapshot on '%s'\n",
3705                                 bdrv_get_device_name(bs1));
3706                 }
3707             }
3708             ret = bdrv_snapshot_create(bs1, sn);
3709             if (ret < 0) {
3710                 term_printf("Error while creating snapshot on '%s'\n",
3711                             bdrv_get_device_name(bs1));
3712             }
3713         }
3714     }
3715
3716  the_end:
3717     if (saved_vm_running)
3718         vm_start();
3719 }
3720
3721 void do_loadvm(const char *name)
3722 {
3723     BlockDriverState *bs, *bs1;
3724     BlockDriverInfo bdi1, *bdi = &bdi1;
3725     QEMUFile *f;
3726     int i, ret;
3727     int saved_vm_running;
3728
3729     bs = get_bs_snapshots();
3730     if (!bs) {
3731         term_printf("No block device supports snapshots\n");
3732         return;
3733     }
3734
3735     /* Flush all IO requests so they don't interfere with the new state.  */
3736     qemu_aio_flush();
3737
3738     saved_vm_running = vm_running;
3739     vm_stop(0);
3740
3741     for(i = 0; i <= nb_drives; i++) {
3742         bs1 = drives_table[i].bdrv;
3743         if (bdrv_has_snapshot(bs1)) {
3744             ret = bdrv_snapshot_goto(bs1, name);
3745             if (ret < 0) {
3746                 if (bs != bs1)
3747                     term_printf("Warning: ");
3748                 switch(ret) {
3749                 case -ENOTSUP:
3750                     term_printf("Snapshots not supported on device '%s'\n",
3751                                 bdrv_get_device_name(bs1));
3752                     break;
3753                 case -ENOENT:
3754                     term_printf("Could not find snapshot '%s' on device '%s'\n",
3755                                 name, bdrv_get_device_name(bs1));
3756                     break;
3757                 default:
3758                     term_printf("Error %d while activating snapshot on '%s'\n",
3759                                 ret, bdrv_get_device_name(bs1));
3760                     break;
3761                 }
3762                 /* fatal on snapshot block device */
3763                 if (bs == bs1)
3764                     goto the_end;
3765             }
3766         }
3767     }
3768
3769     if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3770         term_printf("Device %s does not support VM state snapshots\n",
3771                     bdrv_get_device_name(bs));
3772         return;
3773     }
3774
3775     /* restore the VM state */
3776     f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
3777     if (!f) {
3778         term_printf("Could not open VM state file\n");
3779         goto the_end;
3780     }
3781     ret = qemu_loadvm_state(f);
3782     qemu_fclose(f);
3783     if (ret < 0) {
3784         term_printf("Error %d while loading VM state\n", ret);
3785     }
3786  the_end:
3787     if (saved_vm_running)
3788         vm_start();
3789 }
3790
3791 void do_delvm(const char *name)
3792 {
3793     BlockDriverState *bs, *bs1;
3794     int i, ret;
3795
3796     bs = get_bs_snapshots();
3797     if (!bs) {
3798         term_printf("No block device supports snapshots\n");
3799         return;
3800     }
3801
3802     for(i = 0; i <= nb_drives; i++) {
3803         bs1 = drives_table[i].bdrv;
3804         if (bdrv_has_snapshot(bs1)) {
3805             ret = bdrv_snapshot_delete(bs1, name);
3806             if (ret < 0) {
3807                 if (ret == -ENOTSUP)
3808                     term_printf("Snapshots not supported on device '%s'\n",
3809                                 bdrv_get_device_name(bs1));
3810                 else
3811                     term_printf("Error %d while deleting snapshot on '%s'\n",
3812                                 ret, bdrv_get_device_name(bs1));
3813             }
3814         }
3815     }
3816 }
3817
3818 void do_info_snapshots(void)
3819 {
3820     BlockDriverState *bs, *bs1;
3821     QEMUSnapshotInfo *sn_tab, *sn;
3822     int nb_sns, i;
3823     char buf[256];
3824
3825     bs = get_bs_snapshots();
3826     if (!bs) {
3827         term_printf("No available block device supports snapshots\n");
3828         return;
3829     }
3830     term_printf("Snapshot devices:");
3831     for(i = 0; i <= nb_drives; i++) {
3832         bs1 = drives_table[i].bdrv;
3833         if (bdrv_has_snapshot(bs1)) {
3834             if (bs == bs1)
3835                 term_printf(" %s", bdrv_get_device_name(bs1));
3836         }
3837     }
3838     term_printf("\n");
3839
3840     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3841     if (nb_sns < 0) {
3842         term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
3843         return;
3844     }
3845     term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
3846     term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
3847     for(i = 0; i < nb_sns; i++) {
3848         sn = &sn_tab[i];
3849         term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
3850     }
3851     qemu_free(sn_tab);
3852 }
3853
3854 /***********************************************************/
3855 /* ram save/restore */
3856
3857 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3858 {
3859     int v;
3860
3861     v = qemu_get_byte(f);
3862     switch(v) {
3863     case 0:
3864         if (qemu_get_buffer(f, buf, len) != len)
3865             return -EIO;
3866         break;
3867     case 1:
3868         v = qemu_get_byte(f);
3869         memset(buf, v, len);
3870         break;
3871     default:
3872         return -EINVAL;
3873     }
3874
3875     if (qemu_file_has_error(f))
3876         return -EIO;
3877
3878     return 0;
3879 }
3880
3881 static int ram_load_v1(QEMUFile *f, void *opaque)
3882 {
3883     int ret;
3884     ram_addr_t i;
3885
3886     if (qemu_get_be32(f) != phys_ram_size)
3887         return -EINVAL;
3888     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3889         ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3890         if (ret)
3891             return ret;
3892     }
3893     return 0;
3894 }
3895
3896 #define BDRV_HASH_BLOCK_SIZE 1024
3897 #define IOBUF_SIZE 4096
3898 #define RAM_CBLOCK_MAGIC 0xfabe
3899
3900 typedef struct RamDecompressState {
3901     z_stream zstream;
3902     QEMUFile *f;
3903     uint8_t buf[IOBUF_SIZE];
3904 } RamDecompressState;
3905
3906 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3907 {
3908     int ret;
3909     memset(s, 0, sizeof(*s));
3910     s->f = f;
3911     ret = inflateInit(&s->zstream);
3912     if (ret != Z_OK)
3913         return -1;
3914     return 0;
3915 }
3916
3917 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3918 {
3919     int ret, clen;
3920
3921     s->zstream.avail_out = len;
3922     s->zstream.next_out = buf;
3923     while (s->zstream.avail_out > 0) {
3924         if (s->zstream.avail_in == 0) {
3925             if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3926                 return -1;
3927             clen = qemu_get_be16(s->f);
3928             if (clen > IOBUF_SIZE)
3929                 return -1;
3930             qemu_get_buffer(s->f, s->buf, clen);
3931             s->zstream.avail_in = clen;
3932             s->zstream.next_in = s->buf;
3933         }
3934         ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3935         if (ret != Z_OK && ret != Z_STREAM_END) {
3936             return -1;
3937         }
3938     }
3939     return 0;
3940 }
3941
3942 static void ram_decompress_close(RamDecompressState *s)
3943 {
3944     inflateEnd(&s->zstream);
3945 }
3946
3947 #define RAM_SAVE_FLAG_FULL      0x01
3948 #define RAM_SAVE_FLAG_COMPRESS  0x02
3949 #define RAM_SAVE_FLAG_MEM_SIZE  0x04
3950 #define RAM_SAVE_FLAG_PAGE      0x08
3951 #define RAM_SAVE_FLAG_EOS       0x10
3952
3953 static int is_dup_page(uint8_t *page, uint8_t ch)
3954 {
3955     uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3956     uint32_t *array = (uint32_t *)page;
3957     int i;
3958
3959     for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3960         if (array[i] != val)
3961             return 0;
3962     }
3963
3964     return 1;
3965 }
3966
3967 static int ram_save_block(QEMUFile *f)
3968 {
3969     static ram_addr_t current_addr = 0;
3970     ram_addr_t saved_addr = current_addr;
3971     ram_addr_t addr = 0;
3972     int found = 0;
3973
3974     while (addr < phys_ram_size) {
3975         if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3976             uint8_t ch;
3977
3978             cpu_physical_memory_reset_dirty(current_addr,
3979                                             current_addr + TARGET_PAGE_SIZE,
3980                                             MIGRATION_DIRTY_FLAG);
3981
3982             ch = *(phys_ram_base + current_addr);
3983
3984             if (is_dup_page(phys_ram_base + current_addr, ch)) {
3985                 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3986                 qemu_put_byte(f, ch);
3987             } else {
3988                 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3989                 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3990             }
3991
3992             found = 1;
3993             break;
3994         }
3995         addr += TARGET_PAGE_SIZE;
3996         current_addr = (saved_addr + addr) % phys_ram_size;
3997     }
3998
3999     return found;
4000 }
4001
4002 static ram_addr_t ram_save_threshold = 10;
4003
4004 static ram_addr_t ram_save_remaining(void)
4005 {
4006     ram_addr_t addr;
4007     ram_addr_t count = 0;
4008
4009     for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
4010         if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
4011             count++;
4012     }
4013
4014     return count;
4015 }
4016
4017 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
4018 {
4019     ram_addr_t addr;
4020
4021     if (stage == 1) {
4022         /* Make sure all dirty bits are set */
4023         for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
4024             if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
4025                 cpu_physical_memory_set_dirty(addr);
4026         }
4027         
4028         /* Enable dirty memory tracking */
4029         cpu_physical_memory_set_dirty_tracking(1);
4030
4031         qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
4032     }
4033
4034     while (!qemu_file_rate_limit(f)) {
4035         int ret;
4036
4037         ret = ram_save_block(f);
4038         if (ret == 0) /* no more blocks */
4039             break;
4040     }
4041
4042     /* try transferring iterative blocks of memory */
4043
4044     if (stage == 3) {
4045         cpu_physical_memory_set_dirty_tracking(0);
4046
4047         /* flush all remaining blocks regardless of rate limiting */
4048         while (ram_save_block(f) != 0);
4049     }
4050
4051     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
4052
4053     return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
4054 }
4055
4056 static int ram_load_dead(QEMUFile *f, void *opaque)
4057 {
4058     RamDecompressState s1, *s = &s1;
4059     uint8_t buf[10];
4060     ram_addr_t i;
4061
4062     if (ram_decompress_open(s, f) < 0)
4063         return -EINVAL;
4064     for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
4065         if (ram_decompress_buf(s, buf, 1) < 0) {
4066             fprintf(stderr, "Error while reading ram block header\n");
4067             goto error;
4068         }
4069         if (buf[0] == 0) {
4070             if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
4071                 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
4072                 goto error;
4073             }
4074         } else {
4075         error:
4076             printf("Error block header\n");
4077             return -EINVAL;
4078         }
4079     }
4080     ram_decompress_close(s);
4081
4082     return 0;
4083 }
4084
4085 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4086 {
4087     ram_addr_t addr;
4088     int flags;
4089
4090     if (version_id == 1)
4091         return ram_load_v1(f, opaque);
4092
4093     if (version_id == 2) {
4094         if (qemu_get_be32(f) != phys_ram_size)
4095             return -EINVAL;
4096         return ram_load_dead(f, opaque);
4097     }
4098
4099     if (version_id != 3)
4100         return -EINVAL;
4101
4102     do {
4103         addr = qemu_get_be64(f);
4104
4105         flags = addr & ~TARGET_PAGE_MASK;
4106         addr &= TARGET_PAGE_MASK;
4107
4108         if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
4109             if (addr != phys_ram_size)
4110                 return -EINVAL;
4111         }
4112
4113         if (flags & RAM_SAVE_FLAG_FULL) {
4114             if (ram_load_dead(f, opaque) < 0)
4115                 return -EINVAL;
4116         }
4117         
4118         if (flags & RAM_SAVE_FLAG_COMPRESS) {
4119             uint8_t ch = qemu_get_byte(f);
4120             memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
4121         } else if (flags & RAM_SAVE_FLAG_PAGE)
4122             qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
4123     } while (!(flags & RAM_SAVE_FLAG_EOS));
4124
4125     return 0;
4126 }
4127
4128 void qemu_service_io(void)
4129 {
4130     CPUState *env = cpu_single_env;
4131     if (env) {
4132         cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4133 #ifdef USE_KQEMU
4134         if (env->kqemu_enabled) {
4135             kqemu_cpu_interrupt(env);
4136         }
4137 #endif
4138     }
4139 }
4140
4141 /***********************************************************/
4142 /* bottom halves (can be seen as timers which expire ASAP) */
4143
4144 struct QEMUBH {
4145     QEMUBHFunc *cb;
4146     void *opaque;
4147     int scheduled;
4148     int idle;
4149     int deleted;
4150     QEMUBH *next;
4151 };
4152
4153 static QEMUBH *first_bh = NULL;
4154
4155 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
4156 {
4157     QEMUBH *bh;
4158     bh = qemu_mallocz(sizeof(QEMUBH));
4159     if (!bh)
4160         return NULL;
4161     bh->cb = cb;
4162     bh->opaque = opaque;
4163     bh->next = first_bh;
4164     first_bh = bh;
4165     return bh;
4166 }
4167
4168 int qemu_bh_poll(void)
4169 {
4170     QEMUBH *bh, **bhp;
4171     int ret;
4172
4173     ret = 0;
4174     for (bh = first_bh; bh; bh = bh->next) {
4175         if (!bh->deleted && bh->scheduled) {
4176             bh->scheduled = 0;
4177             if (!bh->idle)
4178                 ret = 1;
4179             bh->idle = 0;
4180             bh->cb(bh->opaque);
4181         }
4182     }
4183
4184     /* remove deleted bhs */
4185     bhp = &first_bh;
4186     while (*bhp) {
4187         bh = *bhp;
4188         if (bh->deleted) {
4189             *bhp = bh->next;
4190             qemu_free(bh);
4191         } else
4192             bhp = &bh->next;
4193     }
4194
4195     return ret;
4196 }
4197
4198 void qemu_bh_schedule_idle(QEMUBH *bh)
4199 {
4200     if (bh->scheduled)
4201         return;
4202     bh->scheduled = 1;
4203     bh->idle = 1;
4204 }
4205
4206 void qemu_bh_schedule(QEMUBH *bh)
4207 {
4208     CPUState *env = cpu_single_env;
4209     if (bh->scheduled)
4210         return;
4211     bh->scheduled = 1;
4212     bh->idle = 0;
4213     /* stop the currently executing CPU to execute the BH ASAP */
4214     if (env) {
4215         cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4216     }
4217 }
4218
4219 void qemu_bh_cancel(QEMUBH *bh)
4220 {
4221     bh->scheduled = 0;
4222 }
4223
4224 void qemu_bh_delete(QEMUBH *bh)
4225 {
4226     bh->scheduled = 0;
4227     bh->deleted = 1;
4228 }
4229
4230 static void qemu_bh_update_timeout(int *timeout)
4231 {
4232     QEMUBH *bh;
4233
4234     for (bh = first_bh; bh; bh = bh->next) {
4235         if (!bh->deleted && bh->scheduled) {
4236             if (bh->idle) {
4237                 /* idle bottom halves will be polled at least
4238                  * every 10ms */
4239                 *timeout = MIN(10, *timeout);
4240             } else {
4241                 /* non-idle bottom halves will be executed
4242                  * immediately */
4243                 *timeout = 0;
4244                 break;
4245             }
4246         }
4247     }
4248 }
4249
4250 /***********************************************************/
4251 /* machine registration */
4252
4253 static QEMUMachine *first_machine = NULL;
4254
4255 int qemu_register_machine(QEMUMachine *m)
4256 {
4257     QEMUMachine **pm;
4258     pm = &first_machine;
4259     while (*pm != NULL)
4260         pm = &(*pm)->next;
4261     m->next = NULL;
4262     *pm = m;
4263     return 0;
4264 }
4265
4266 static QEMUMachine *find_machine(const char *name)
4267 {
4268     QEMUMachine *m;
4269
4270     for(m = first_machine; m != NULL; m = m->next) {
4271         if (!strcmp(m->name, name))
4272             return m;
4273     }
4274     return NULL;
4275 }
4276
4277 /***********************************************************/
4278 /* main execution loop */
4279
4280 static void gui_update(void *opaque)
4281 {
4282     DisplayState *ds = opaque;
4283     ds->dpy_refresh(ds);
4284     qemu_mod_timer(ds->gui_timer,
4285         (ds->gui_timer_interval ?
4286             ds->gui_timer_interval :
4287             GUI_REFRESH_INTERVAL)
4288         + qemu_get_clock(rt_clock));
4289 }
4290
4291 struct vm_change_state_entry {
4292     VMChangeStateHandler *cb;
4293     void *opaque;
4294     LIST_ENTRY (vm_change_state_entry) entries;
4295 };
4296
4297 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4298
4299 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4300                                                      void *opaque)
4301 {
4302     VMChangeStateEntry *e;
4303
4304     e = qemu_mallocz(sizeof (*e));
4305     if (!e)
4306         return NULL;
4307
4308     e->cb = cb;
4309     e->opaque = opaque;
4310     LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4311     return e;
4312 }
4313
4314 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4315 {
4316     LIST_REMOVE (e, entries);
4317     qemu_free (e);
4318 }
4319
4320 static void vm_state_notify(int running)
4321 {
4322     VMChangeStateEntry *e;
4323
4324     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4325         e->cb(e->opaque, running);
4326     }
4327 }
4328
4329 /* XXX: support several handlers */
4330 static VMStopHandler *vm_stop_cb;
4331 static void *vm_stop_opaque;
4332
4333 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4334 {
4335     vm_stop_cb = cb;
4336     vm_stop_opaque = opaque;
4337     return 0;
4338 }
4339
4340 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4341 {
4342     vm_stop_cb = NULL;
4343 }
4344
4345 void vm_start(void)
4346 {
4347     if (!vm_running) {
4348         cpu_enable_ticks();
4349         vm_running = 1;
4350         vm_state_notify(1);
4351         qemu_rearm_alarm_timer(alarm_timer);
4352     }
4353 }
4354
4355 void vm_stop(int reason)
4356 {
4357     if (vm_running) {
4358         cpu_disable_ticks();
4359         vm_running = 0;
4360         if (reason != 0) {
4361             if (vm_stop_cb) {
4362                 vm_stop_cb(vm_stop_opaque, reason);
4363             }
4364         }
4365         vm_state_notify(0);
4366     }
4367 }
4368
4369 /* reset/shutdown handler */
4370
4371 typedef struct QEMUResetEntry {
4372     QEMUResetHandler *func;
4373     void *opaque;
4374     struct QEMUResetEntry *next;
4375 } QEMUResetEntry;
4376
4377 static QEMUResetEntry *first_reset_entry;
4378 static int reset_requested;
4379 static int shutdown_requested;
4380 static int powerdown_requested;
4381
4382 int qemu_shutdown_requested(void)
4383 {
4384     int r = shutdown_requested;
4385     shutdown_requested = 0;
4386     return r;
4387 }
4388
4389 int qemu_reset_requested(void)
4390 {
4391     int r = reset_requested;
4392     reset_requested = 0;
4393     return r;
4394 }
4395
4396 int qemu_powerdown_requested(void)
4397 {
4398     int r = powerdown_requested;
4399     powerdown_requested = 0;
4400     return r;
4401 }
4402
4403 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4404 {
4405     QEMUResetEntry **pre, *re;
4406
4407     pre = &first_reset_entry;
4408     while (*pre != NULL)
4409         pre = &(*pre)->next;
4410     re = qemu_mallocz(sizeof(QEMUResetEntry));
4411     re->func = func;
4412     re->opaque = opaque;
4413     re->next = NULL;
4414     *pre = re;
4415 }
4416
4417 void qemu_system_reset(void)
4418 {
4419     QEMUResetEntry *re;
4420
4421     /* reset all devices */
4422     for(re = first_reset_entry; re != NULL; re = re->next) {
4423         re->func(re->opaque);
4424     }
4425 }
4426
4427 void qemu_system_reset_request(void)
4428 {
4429     if (no_reboot) {
4430         shutdown_requested = 1;
4431     } else {
4432         reset_requested = 1;
4433     }
4434     if (cpu_single_env)
4435         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4436 }
4437
4438 void qemu_system_shutdown_request(void)
4439 {
4440     shutdown_requested = 1;
4441     if (cpu_single_env)
4442         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4443 }
4444
4445 void qemu_system_powerdown_request(void)
4446 {
4447     powerdown_requested = 1;
4448     if (cpu_single_env)
4449         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4450 }
4451
4452 #ifdef _WIN32
4453 void host_main_loop_wait(int *timeout)
4454 {
4455     int ret, ret2, i;
4456     PollingEntry *pe;
4457
4458
4459     /* XXX: need to suppress polling by better using win32 events */
4460     ret = 0;
4461     for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4462         ret |= pe->func(pe->opaque);
4463     }
4464     if (ret == 0) {
4465         int err;
4466         WaitObjects *w = &wait_objects;
4467
4468         ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4469         if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4470             if (w->func[ret - WAIT_OBJECT_0])
4471                 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4472
4473             /* Check for additional signaled events */
4474             for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4475
4476                 /* Check if event is signaled */
4477                 ret2 = WaitForSingleObject(w->events[i], 0);
4478                 if(ret2 == WAIT_OBJECT_0) {
4479                     if (w->func[i])
4480                         w->func[i](w->opaque[i]);
4481                 } else if (ret2 == WAIT_TIMEOUT) {
4482                 } else {
4483                     err = GetLastError();
4484                     fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4485                 }
4486             }
4487         } else if (ret == WAIT_TIMEOUT) {
4488         } else {
4489             err = GetLastError();
4490             fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4491         }
4492     }
4493
4494     *timeout = 0;
4495 }
4496 #else
4497 void host_main_loop_wait(int *timeout)
4498 {
4499 }
4500 #endif
4501
4502 void main_loop_wait(int timeout)
4503 {
4504     IOHandlerRecord *ioh;
4505     fd_set rfds, wfds, xfds;
4506     int ret, nfds;
4507     struct timeval tv;
4508
4509     qemu_bh_update_timeout(&timeout);
4510
4511     host_main_loop_wait(&timeout);
4512
4513     /* poll any events */
4514     /* XXX: separate device handlers from system ones */
4515     nfds = -1;
4516     FD_ZERO(&rfds);
4517     FD_ZERO(&wfds);
4518     FD_ZERO(&xfds);
4519     for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4520         if (ioh->deleted)
4521             continue;
4522         if (ioh->fd_read &&
4523             (!ioh->fd_read_poll ||
4524              ioh->fd_read_poll(ioh->opaque) != 0)) {
4525             FD_SET(ioh->fd, &rfds);
4526             if (ioh->fd > nfds)
4527                 nfds = ioh->fd;
4528         }
4529         if (ioh->fd_write) {
4530             FD_SET(ioh->fd, &wfds);
4531             if (ioh->fd > nfds)
4532                 nfds = ioh->fd;
4533         }
4534     }
4535
4536     tv.tv_sec = timeout / 1000;
4537     tv.tv_usec = (timeout % 1000) * 1000;
4538
4539 #if defined(CONFIG_SLIRP)
4540     if (slirp_is_inited()) {
4541         slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4542     }
4543 #endif
4544     ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4545     if (ret > 0) {
4546         IOHandlerRecord **pioh;
4547
4548         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4549             if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4550                 ioh->fd_read(ioh->opaque);
4551             }
4552             if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4553                 ioh->fd_write(ioh->opaque);
4554             }
4555         }
4556
4557         /* remove deleted IO handlers */
4558         pioh = &first_io_handler;
4559         while (*pioh) {
4560             ioh = *pioh;
4561             if (ioh->deleted) {
4562                 *pioh = ioh->next;
4563                 qemu_free(ioh);
4564             } else
4565                 pioh = &ioh->next;
4566         }
4567     }
4568 #if defined(CONFIG_SLIRP)
4569     if (slirp_is_inited()) {
4570         if (ret < 0) {
4571             FD_ZERO(&rfds);
4572             FD_ZERO(&wfds);
4573             FD_ZERO(&xfds);
4574         }
4575         slirp_select_poll(&rfds, &wfds, &xfds);
4576     }
4577 #endif
4578
4579     /* Check bottom-halves last in case any of the earlier events triggered
4580        them.  */
4581     qemu_bh_poll();
4582
4583 }
4584
4585 static int main_loop(void)
4586 {
4587     int ret, timeout;
4588 #ifdef CONFIG_PROFILER
4589     int64_t ti;
4590 #endif
4591     CPUState *env;
4592
4593     cur_cpu = first_cpu;
4594     next_cpu = cur_cpu->next_cpu ?: first_cpu;
4595     for(;;) {
4596         if (vm_running) {
4597
4598             for(;;) {
4599                 /* get next cpu */
4600                 env = next_cpu;
4601 #ifdef CONFIG_PROFILER
4602                 ti = profile_getclock();
4603 #endif
4604                 if (use_icount) {
4605                     int64_t count;
4606                     int decr;
4607                     qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4608                     env->icount_decr.u16.low = 0;
4609                     env->icount_extra = 0;
4610                     count = qemu_next_deadline();
4611                     count = (count + (1 << icount_time_shift) - 1)
4612                             >> icount_time_shift;
4613                     qemu_icount += count;
4614                     decr = (count > 0xffff) ? 0xffff : count;
4615                     count -= decr;
4616                     env->icount_decr.u16.low = decr;
4617                     env->icount_extra = count;
4618                 }
4619                 ret = cpu_exec(env);
4620 #ifdef CONFIG_PROFILER
4621                 qemu_time += profile_getclock() - ti;
4622 #endif
4623                 if (use_icount) {
4624                     /* Fold pending instructions back into the
4625                        instruction counter, and clear the interrupt flag.  */
4626                     qemu_icount -= (env->icount_decr.u16.low
4627                                     + env->icount_extra);
4628                     env->icount_decr.u32 = 0;
4629                     env->icount_extra = 0;
4630                 }
4631                 next_cpu = env->next_cpu ?: first_cpu;
4632                 if (event_pending && likely(ret != EXCP_DEBUG)) {
4633                     ret = EXCP_INTERRUPT;
4634                     event_pending = 0;
4635                     break;
4636                 }
4637                 if (ret == EXCP_HLT) {
4638                     /* Give the next CPU a chance to run.  */
4639                     cur_cpu = env;
4640                     continue;
4641                 }
4642                 if (ret != EXCP_HALTED)
4643                     break;
4644                 /* all CPUs are halted ? */
4645                 if (env == cur_cpu)
4646                     break;
4647             }
4648             cur_cpu = env;
4649
4650             if (shutdown_requested) {
4651                 ret = EXCP_INTERRUPT;
4652                 if (no_shutdown) {
4653                     vm_stop(0);
4654                     no_shutdown = 0;
4655                 }
4656                 else
4657                     break;
4658             }
4659             if (reset_requested) {
4660                 reset_requested = 0;
4661                 qemu_system_reset();
4662                 ret = EXCP_INTERRUPT;
4663             }
4664             if (powerdown_requested) {
4665                 powerdown_requested = 0;
4666                 qemu_system_powerdown();
4667                 ret = EXCP_INTERRUPT;
4668             }
4669             if (unlikely(ret == EXCP_DEBUG)) {
4670                 vm_stop(EXCP_DEBUG);
4671             }
4672             /* If all cpus are halted then wait until the next IRQ */
4673             /* XXX: use timeout computed from timers */
4674             if (ret == EXCP_HALTED) {
4675                 if (use_icount) {
4676                     int64_t add;
4677                     int64_t delta;
4678                     /* Advance virtual time to the next event.  */
4679                     if (use_icount == 1) {
4680                         /* When not using an adaptive execution frequency
4681                            we tend to get badly out of sync with real time,
4682                            so just delay for a reasonable amount of time.  */
4683                         delta = 0;
4684                     } else {
4685                         delta = cpu_get_icount() - cpu_get_clock();
4686                     }
4687                     if (delta > 0) {
4688                         /* If virtual time is ahead of real time then just
4689                            wait for IO.  */
4690                         timeout = (delta / 1000000) + 1;
4691                     } else {
4692                         /* Wait for either IO to occur or the next
4693                            timer event.  */
4694                         add = qemu_next_deadline();
4695                         /* We advance the timer before checking for IO.
4696                            Limit the amount we advance so that early IO
4697                            activity won't get the guest too far ahead.  */
4698                         if (add > 10000000)
4699                             add = 10000000;
4700                         delta += add;
4701                         add = (add + (1 << icount_time_shift) - 1)
4702                               >> icount_time_shift;
4703                         qemu_icount += add;
4704                         timeout = delta / 1000000;
4705                         if (timeout < 0)
4706                             timeout = 0;
4707                     }
4708                 } else {
4709                     timeout = 5000;
4710                 }
4711             } else {
4712                 timeout = 0;
4713             }
4714         } else {
4715             if (shutdown_requested) {
4716                 ret = EXCP_INTERRUPT;
4717                 break;
4718             }
4719             timeout = 5000;
4720         }
4721 #ifdef CONFIG_PROFILER
4722         ti = profile_getclock();
4723 #endif
4724         main_loop_wait(timeout);
4725 #ifdef CONFIG_PROFILER
4726         dev_time += profile_getclock() - ti;
4727 #endif
4728     }
4729     cpu_disable_ticks();
4730     return ret;
4731 }
4732
4733 static void help(int exitcode)
4734 {
4735     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4736            "usage: %s [options] [disk_image]\n"
4737            "\n"
4738            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4739            "\n"
4740            "Standard options:\n"
4741            "-M machine      select emulated machine (-M ? for list)\n"
4742            "-cpu cpu        select CPU (-cpu ? for list)\n"
4743            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
4744            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
4745            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
4746            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4747            "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
4748            "       [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
4749            "       [,cache=writethrough|writeback|none][,format=f]\n"
4750            "                use 'file' as a drive image\n"
4751            "-mtdblock file  use 'file' as on-board Flash memory image\n"
4752            "-sd file        use 'file' as SecureDigital card image\n"
4753            "-pflash file    use 'file' as a parallel flash image\n"
4754            "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
4755            "-snapshot       write to temporary files instead of disk image files\n"
4756 #ifdef CONFIG_SDL
4757            "-no-frame       open SDL window without a frame and window decorations\n"
4758            "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4759            "-no-quit        disable SDL window close capability\n"
4760 #endif
4761 #ifdef TARGET_I386
4762            "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
4763 #endif
4764            "-m megs         set virtual RAM size to megs MB [default=%d]\n"
4765            "-smp n          set the number of CPUs to 'n' [default=1]\n"
4766            "-nographic      disable graphical output and redirect serial I/Os to console\n"
4767            "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
4768 #ifndef _WIN32
4769            "-k language     use keyboard layout (for example \"fr\" for French)\n"
4770 #endif
4771 #ifdef HAS_AUDIO
4772            "-audio-help     print list of audio drivers and their options\n"
4773            "-soundhw c1,... enable audio support\n"
4774            "                and only specified sound cards (comma separated list)\n"
4775            "                use -soundhw ? to get the list of supported cards\n"
4776            "                use -soundhw all to enable all of them\n"
4777 #endif
4778            "-vga [std|cirrus|vmware]\n"
4779            "                select video card type\n"
4780            "-localtime      set the real time clock to local time [default=utc]\n"
4781            "-full-screen    start in full screen\n"
4782 #ifdef TARGET_I386
4783            "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
4784 #endif
4785            "-usb            enable the USB driver (will be the default soon)\n"
4786            "-usbdevice name add the host or guest USB device 'name'\n"
4787 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4788            "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
4789 #endif
4790            "-name string    set the name of the guest\n"
4791            "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4792            "\n"
4793            "Network options:\n"
4794            "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4795            "                create a new Network Interface Card and connect it to VLAN 'n'\n"
4796 #ifdef CONFIG_SLIRP
4797            "-net user[,vlan=n][,hostname=host]\n"
4798            "                connect the user mode network stack to VLAN 'n' and send\n"
4799            "                hostname 'host' to DHCP clients\n"
4800 #endif
4801 #ifdef _WIN32
4802            "-net tap[,vlan=n],ifname=name\n"
4803            "                connect the host TAP network interface to VLAN 'n'\n"
4804 #else
4805            "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4806            "                connect the host TAP network interface to VLAN 'n' and use the\n"
4807            "                network scripts 'file' (default=%s)\n"
4808            "                and 'dfile' (default=%s);\n"
4809            "                use '[down]script=no' to disable script execution;\n"
4810            "                use 'fd=h' to connect to an already opened TAP interface\n"
4811 #endif
4812            "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4813            "                connect the vlan 'n' to another VLAN using a socket connection\n"
4814            "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4815            "                connect the vlan 'n' to multicast maddr and port\n"
4816 #ifdef CONFIG_VDE
4817            "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4818            "                connect the vlan 'n' to port 'n' of a vde switch running\n"
4819            "                on host and listening for incoming connections on 'socketpath'.\n"
4820            "                Use group 'groupname' and mode 'octalmode' to change default\n"
4821            "                ownership and permissions for communication port.\n"
4822 #endif
4823            "-net none       use it alone to have zero network devices; if no -net option\n"
4824            "                is provided, the default is '-net nic -net user'\n"
4825            "\n"
4826 #ifdef CONFIG_SLIRP
4827            "-tftp dir       allow tftp access to files in dir [-net user]\n"
4828            "-bootp file     advertise file in BOOTP replies\n"
4829 #ifndef _WIN32
4830            "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
4831 #endif
4832            "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4833            "                redirect TCP or UDP connections from host to guest [-net user]\n"
4834 #endif
4835            "\n"
4836            "Linux boot specific:\n"
4837            "-kernel bzImage use 'bzImage' as kernel image\n"
4838            "-append cmdline use 'cmdline' as kernel command line\n"
4839            "-initrd file    use 'file' as initial ram disk\n"
4840            "\n"
4841            "Debug/Expert options:\n"
4842            "-monitor dev    redirect the monitor to char device 'dev'\n"
4843            "-serial dev     redirect the serial port to char device 'dev'\n"
4844            "-parallel dev   redirect the parallel port to char device 'dev'\n"
4845            "-pidfile file   Write PID to 'file'\n"
4846            "-S              freeze CPU at startup (use 'c' to start execution)\n"
4847            "-s              wait gdb connection to port\n"
4848            "-p port         set gdb connection port [default=%s]\n"
4849            "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
4850            "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
4851            "                translation (t=none or lba) (usually qemu can guess them)\n"
4852            "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
4853 #ifdef USE_KQEMU
4854            "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
4855            "-no-kqemu       disable KQEMU kernel module usage\n"
4856 #endif
4857 #ifdef CONFIG_KVM
4858            "-enable-kvm     enable KVM full virtualization support\n"
4859 #endif
4860 #ifdef TARGET_I386
4861            "-no-acpi        disable ACPI\n"
4862 #endif
4863 #ifdef CONFIG_CURSES
4864            "-curses         use a curses/ncurses interface instead of SDL\n"
4865 #endif
4866            "-no-reboot      exit instead of rebooting\n"
4867            "-no-shutdown    stop before shutdown\n"
4868            "-loadvm [tag|id]  start right away with a saved state (loadvm in monitor)\n"
4869            "-vnc display    start a VNC server on display\n"
4870 #ifndef _WIN32
4871            "-daemonize      daemonize QEMU after initializing\n"
4872 #endif
4873            "-option-rom rom load a file, rom, into the option ROM space\n"
4874 #ifdef TARGET_SPARC
4875            "-prom-env variable=value  set OpenBIOS nvram variables\n"
4876 #endif
4877            "-clock          force the use of the given methods for timer alarm.\n"
4878            "                To see what timers are available use -clock ?\n"
4879            "-startdate      select initial date of the clock\n"
4880            "-icount [N|auto]\n"
4881            "                Enable virtual instruction counter with 2^N clock ticks per instruction\n"
4882            "\n"
4883            "During emulation, the following keys are useful:\n"
4884            "ctrl-alt-f      toggle full screen\n"
4885            "ctrl-alt-n      switch to virtual console 'n'\n"
4886            "ctrl-alt        toggle mouse and keyboard grab\n"
4887            "\n"
4888            "When using -nographic, press 'ctrl-a h' to get some help.\n"
4889            ,
4890            "qemu",
4891            DEFAULT_RAM_SIZE,
4892 #ifndef _WIN32
4893            DEFAULT_NETWORK_SCRIPT,
4894            DEFAULT_NETWORK_DOWN_SCRIPT,
4895 #endif
4896            DEFAULT_GDBSTUB_PORT,
4897            "/tmp/qemu.log");
4898     exit(exitcode);
4899 }
4900
4901 #define HAS_ARG 0x0001
4902
4903 enum {
4904     QEMU_OPTION_h,
4905
4906     QEMU_OPTION_M,
4907     QEMU_OPTION_cpu,
4908     QEMU_OPTION_fda,
4909     QEMU_OPTION_fdb,
4910     QEMU_OPTION_hda,
4911     QEMU_OPTION_hdb,
4912     QEMU_OPTION_hdc,
4913     QEMU_OPTION_hdd,
4914     QEMU_OPTION_drive,
4915     QEMU_OPTION_cdrom,
4916     QEMU_OPTION_mtdblock,
4917     QEMU_OPTION_sd,
4918     QEMU_OPTION_pflash,
4919     QEMU_OPTION_boot,
4920     QEMU_OPTION_snapshot,
4921 #ifdef TARGET_I386
4922     QEMU_OPTION_no_fd_bootchk,
4923 #endif
4924     QEMU_OPTION_m,
4925     QEMU_OPTION_nographic,
4926     QEMU_OPTION_portrait,
4927 #ifdef HAS_AUDIO
4928     QEMU_OPTION_audio_help,
4929     QEMU_OPTION_soundhw,
4930 #endif
4931
4932     QEMU_OPTION_net,
4933     QEMU_OPTION_tftp,
4934     QEMU_OPTION_bootp,
4935     QEMU_OPTION_smb,
4936     QEMU_OPTION_redir,
4937
4938     QEMU_OPTION_kernel,
4939     QEMU_OPTION_append,
4940     QEMU_OPTION_initrd,
4941
4942     QEMU_OPTION_S,
4943     QEMU_OPTION_s,
4944     QEMU_OPTION_p,
4945     QEMU_OPTION_d,
4946     QEMU_OPTION_hdachs,
4947     QEMU_OPTION_L,
4948     QEMU_OPTION_bios,
4949     QEMU_OPTION_k,
4950     QEMU_OPTION_localtime,
4951     QEMU_OPTION_g,
4952     QEMU_OPTION_vga,
4953     QEMU_OPTION_echr,
4954     QEMU_OPTION_monitor,
4955     QEMU_OPTION_serial,
4956     QEMU_OPTION_parallel,
4957     QEMU_OPTION_loadvm,
4958     QEMU_OPTION_full_screen,
4959     QEMU_OPTION_no_frame,
4960     QEMU_OPTION_alt_grab,
4961     QEMU_OPTION_no_quit,
4962     QEMU_OPTION_pidfile,
4963     QEMU_OPTION_no_kqemu,
4964     QEMU_OPTION_kernel_kqemu,
4965     QEMU_OPTION_enable_kvm,
4966     QEMU_OPTION_win2k_hack,
4967     QEMU_OPTION_usb,
4968     QEMU_OPTION_usbdevice,
4969     QEMU_OPTION_smp,
4970     QEMU_OPTION_vnc,
4971     QEMU_OPTION_no_acpi,
4972     QEMU_OPTION_curses,
4973     QEMU_OPTION_no_reboot,
4974     QEMU_OPTION_no_shutdown,
4975     QEMU_OPTION_show_cursor,
4976     QEMU_OPTION_daemonize,
4977     QEMU_OPTION_option_rom,
4978     QEMU_OPTION_semihosting,
4979     QEMU_OPTION_name,
4980     QEMU_OPTION_prom_env,
4981     QEMU_OPTION_old_param,
4982     QEMU_OPTION_clock,
4983     QEMU_OPTION_startdate,
4984     QEMU_OPTION_tb_size,
4985     QEMU_OPTION_icount,
4986     QEMU_OPTION_uuid,
4987     QEMU_OPTION_incoming,
4988 };
4989
4990 typedef struct QEMUOption {
4991     const char *name;
4992     int flags;
4993     int index;
4994 } QEMUOption;
4995
4996 static const QEMUOption qemu_options[] = {
4997     { "h", 0, QEMU_OPTION_h },
4998     { "help", 0, QEMU_OPTION_h },
4999
5000     { "M", HAS_ARG, QEMU_OPTION_M },
5001     { "cpu", HAS_ARG, QEMU_OPTION_cpu },
5002     { "fda", HAS_ARG, QEMU_OPTION_fda },
5003     { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5004     { "hda", HAS_ARG, QEMU_OPTION_hda },
5005     { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5006     { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5007     { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5008     { "drive", HAS_ARG, QEMU_OPTION_drive },
5009     { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5010     { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
5011     { "sd", HAS_ARG, QEMU_OPTION_sd },
5012     { "pflash", HAS_ARG, QEMU_OPTION_pflash },
5013     { "boot", HAS_ARG, QEMU_OPTION_boot },
5014     { "snapshot", 0, QEMU_OPTION_snapshot },
5015 #ifdef TARGET_I386
5016     { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5017 #endif
5018     { "m", HAS_ARG, QEMU_OPTION_m },
5019     { "nographic", 0, QEMU_OPTION_nographic },
5020     { "portrait", 0, QEMU_OPTION_portrait },
5021     { "k", HAS_ARG, QEMU_OPTION_k },
5022 #ifdef HAS_AUDIO
5023     { "audio-help", 0, QEMU_OPTION_audio_help },
5024     { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5025 #endif
5026
5027     { "net", HAS_ARG, QEMU_OPTION_net},
5028 #ifdef CONFIG_SLIRP
5029     { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5030     { "bootp", HAS_ARG, QEMU_OPTION_bootp },
5031 #ifndef _WIN32
5032     { "smb", HAS_ARG, QEMU_OPTION_smb },
5033 #endif
5034     { "redir", HAS_ARG, QEMU_OPTION_redir },
5035 #endif
5036
5037     { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5038     { "append", HAS_ARG, QEMU_OPTION_append },
5039     { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5040
5041     { "S", 0, QEMU_OPTION_S },
5042     { "s", 0, QEMU_OPTION_s },
5043     { "p", HAS_ARG, QEMU_OPTION_p },
5044     { "d", HAS_ARG, QEMU_OPTION_d },
5045     { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5046     { "L", HAS_ARG, QEMU_OPTION_L },
5047     { "bios", HAS_ARG, QEMU_OPTION_bios },
5048 #ifdef USE_KQEMU
5049     { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5050     { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5051 #endif
5052 #ifdef CONFIG_KVM
5053     { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
5054 #endif
5055 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5056     { "g", 1, QEMU_OPTION_g },
5057 #endif
5058     { "localtime", 0, QEMU_OPTION_localtime },
5059     { "vga", HAS_ARG, QEMU_OPTION_vga },
5060     { "echr", HAS_ARG, QEMU_OPTION_echr },
5061     { "monitor", HAS_ARG, QEMU_OPTION_monitor },
5062     { "serial", HAS_ARG, QEMU_OPTION_serial },
5063     { "parallel", HAS_ARG, QEMU_OPTION_parallel },
5064     { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5065     { "full-screen", 0, QEMU_OPTION_full_screen },
5066 #ifdef CONFIG_SDL
5067     { "no-frame", 0, QEMU_OPTION_no_frame },
5068     { "alt-grab", 0, QEMU_OPTION_alt_grab },
5069     { "no-quit", 0, QEMU_OPTION_no_quit },
5070 #endif
5071     { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5072     { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5073     { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5074     { "smp", HAS_ARG, QEMU_OPTION_smp },
5075     { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5076 #ifdef CONFIG_CURSES
5077     { "curses", 0, QEMU_OPTION_curses },
5078 #endif
5079     { "uuid", HAS_ARG, QEMU_OPTION_uuid },
5080
5081     /* temporary options */
5082     { "usb", 0, QEMU_OPTION_usb },
5083     { "no-acpi", 0, QEMU_OPTION_no_acpi },
5084     { "no-reboot", 0, QEMU_OPTION_no_reboot },
5085     { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
5086     { "show-cursor", 0, QEMU_OPTION_show_cursor },
5087     { "daemonize", 0, QEMU_OPTION_daemonize },
5088     { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
5089 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5090     { "semihosting", 0, QEMU_OPTION_semihosting },
5091 #endif
5092     { "name", HAS_ARG, QEMU_OPTION_name },
5093 #if defined(TARGET_SPARC)
5094     { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
5095 #endif
5096 #if defined(TARGET_ARM)
5097     { "old-param", 0, QEMU_OPTION_old_param },
5098 #endif
5099     { "clock", HAS_ARG, QEMU_OPTION_clock },
5100     { "startdate", HAS_ARG, QEMU_OPTION_startdate },
5101     { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
5102     { "icount", HAS_ARG, QEMU_OPTION_icount },
5103     { "incoming", HAS_ARG, QEMU_OPTION_incoming },
5104     { NULL },
5105 };
5106
5107 /* password input */
5108
5109 int qemu_key_check(BlockDriverState *bs, const char *name)
5110 {
5111     char password[256];
5112     int i;
5113
5114     if (!bdrv_is_encrypted(bs))
5115         return 0;
5116
5117     term_printf("%s is encrypted.\n", name);
5118     for(i = 0; i < 3; i++) {
5119         monitor_readline("Password: ", 1, password, sizeof(password));
5120         if (bdrv_set_key(bs, password) == 0)
5121             return 0;
5122         term_printf("invalid password\n");
5123     }
5124     return -EPERM;
5125 }
5126
5127 static BlockDriverState *get_bdrv(int index)
5128 {
5129     if (index > nb_drives)
5130         return NULL;
5131     return drives_table[index].bdrv;
5132 }
5133
5134 static void read_passwords(void)
5135 {
5136     BlockDriverState *bs;
5137     int i;
5138
5139     for(i = 0; i < 6; i++) {
5140         bs = get_bdrv(i);
5141         if (bs)
5142             qemu_key_check(bs, bdrv_get_device_name(bs));
5143     }
5144 }
5145
5146 #ifdef HAS_AUDIO
5147 struct soundhw soundhw[] = {
5148 #ifdef HAS_AUDIO_CHOICE
5149 #if defined(TARGET_I386) || defined(TARGET_MIPS)
5150     {
5151         "pcspk",
5152         "PC speaker",
5153         0,
5154         1,
5155         { .init_isa = pcspk_audio_init }
5156     },
5157 #endif
5158     {
5159         "sb16",
5160         "Creative Sound Blaster 16",
5161         0,
5162         1,
5163         { .init_isa = SB16_init }
5164     },
5165
5166 #ifdef CONFIG_CS4231A
5167     {
5168         "cs4231a",
5169         "CS4231A",
5170         0,
5171         1,
5172         { .init_isa = cs4231a_init }
5173     },
5174 #endif
5175
5176 #ifdef CONFIG_ADLIB
5177     {
5178         "adlib",
5179 #ifdef HAS_YMF262
5180         "Yamaha YMF262 (OPL3)",
5181 #else
5182         "Yamaha YM3812 (OPL2)",
5183 #endif
5184         0,
5185         1,
5186         { .init_isa = Adlib_init }
5187     },
5188 #endif
5189
5190 #ifdef CONFIG_GUS
5191     {
5192         "gus",
5193         "Gravis Ultrasound GF1",
5194         0,
5195         1,
5196         { .init_isa = GUS_init }
5197     },
5198 #endif
5199
5200 #ifdef CONFIG_AC97
5201     {
5202         "ac97",
5203         "Intel 82801AA AC97 Audio",
5204         0,
5205         0,
5206         { .init_pci = ac97_init }
5207     },
5208 #endif
5209
5210     {
5211         "es1370",
5212         "ENSONIQ AudioPCI ES1370",
5213         0,
5214         0,
5215         { .init_pci = es1370_init }
5216     },
5217 #endif
5218
5219     { NULL, NULL, 0, 0, { NULL } }
5220 };
5221
5222 static void select_soundhw (const char *optarg)
5223 {
5224     struct soundhw *c;
5225
5226     if (*optarg == '?') {
5227     show_valid_cards:
5228
5229         printf ("Valid sound card names (comma separated):\n");
5230         for (c = soundhw; c->name; ++c) {
5231             printf ("%-11s %s\n", c->name, c->descr);
5232         }
5233         printf ("\n-soundhw all will enable all of the above\n");
5234         exit (*optarg != '?');
5235     }
5236     else {
5237         size_t l;
5238         const char *p;
5239         char *e;
5240         int bad_card = 0;
5241
5242         if (!strcmp (optarg, "all")) {
5243             for (c = soundhw; c->name; ++c) {
5244                 c->enabled = 1;
5245             }
5246             return;
5247         }
5248
5249         p = optarg;
5250         while (*p) {
5251             e = strchr (p, ',');
5252             l = !e ? strlen (p) : (size_t) (e - p);
5253
5254             for (c = soundhw; c->name; ++c) {
5255                 if (!strncmp (c->name, p, l)) {
5256                     c->enabled = 1;
5257                     break;
5258                 }
5259             }
5260
5261             if (!c->name) {
5262                 if (l > 80) {
5263                     fprintf (stderr,
5264                              "Unknown sound card name (too big to show)\n");
5265                 }
5266                 else {
5267                     fprintf (stderr, "Unknown sound card name `%.*s'\n",
5268                              (int) l, p);
5269                 }
5270                 bad_card = 1;
5271             }
5272             p += l + (e != NULL);
5273         }
5274
5275         if (bad_card)
5276             goto show_valid_cards;
5277     }
5278 }
5279 #endif
5280
5281 static void select_vgahw (const char *p)
5282 {
5283     const char *opts;
5284
5285     if (strstart(p, "std", &opts)) {
5286         cirrus_vga_enabled = 0;
5287         vmsvga_enabled = 0;
5288     } else if (strstart(p, "cirrus", &opts)) {
5289         cirrus_vga_enabled = 1;
5290         vmsvga_enabled = 0;
5291     } else if (strstart(p, "vmware", &opts)) {
5292         cirrus_vga_enabled = 0;
5293         vmsvga_enabled = 1;
5294     } else {
5295     invalid_vga:
5296         fprintf(stderr, "Unknown vga type: %s\n", p);
5297         exit(1);
5298     }
5299     while (*opts) {
5300         const char *nextopt;
5301
5302         if (strstart(opts, ",retrace=", &nextopt)) {
5303             opts = nextopt;
5304             if (strstart(opts, "dumb", &nextopt))
5305                 vga_retrace_method = VGA_RETRACE_DUMB;
5306             else if (strstart(opts, "precise", &nextopt))
5307                 vga_retrace_method = VGA_RETRACE_PRECISE;
5308             else goto invalid_vga;
5309         } else goto invalid_vga;
5310         opts = nextopt;
5311     }
5312 }
5313
5314 #ifdef _WIN32
5315 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5316 {
5317     exit(STATUS_CONTROL_C_EXIT);
5318     return TRUE;
5319 }
5320 #endif
5321
5322 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
5323 {
5324     int ret;
5325
5326     if(strlen(str) != 36)
5327         return -1;
5328
5329     ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
5330             &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
5331             &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
5332
5333     if(ret != 16)
5334         return -1;
5335
5336     return 0;
5337 }
5338
5339 #define MAX_NET_CLIENTS 32
5340
5341 #ifndef _WIN32
5342
5343 static void termsig_handler(int signal)
5344 {
5345     qemu_system_shutdown_request();
5346 }
5347
5348 static void termsig_setup(void)
5349 {
5350     struct sigaction act;
5351
5352     memset(&act, 0, sizeof(act));
5353     act.sa_handler = termsig_handler;
5354     sigaction(SIGINT,  &act, NULL);
5355     sigaction(SIGHUP,  &act, NULL);
5356     sigaction(SIGTERM, &act, NULL);
5357 }
5358
5359 #endif
5360
5361 int main(int argc, char **argv)
5362 {
5363 #ifdef CONFIG_GDBSTUB
5364     int use_gdbstub;
5365     const char *gdbstub_port;
5366 #endif
5367     uint32_t boot_devices_bitmap = 0;
5368     int i;
5369     int snapshot, linux_boot, net_boot;
5370     const char *initrd_filename;
5371     const char *kernel_filename, *kernel_cmdline;
5372     const char *boot_devices = "";
5373     DisplayState *ds = &display_state;
5374     int cyls, heads, secs, translation;
5375     const char *net_clients[MAX_NET_CLIENTS];
5376     int nb_net_clients;
5377     int hda_index;
5378     int optind;
5379     const char *r, *optarg;
5380     CharDriverState *monitor_hd;
5381     const char *monitor_device;
5382     const char *serial_devices[MAX_SERIAL_PORTS];
5383     int serial_device_index;
5384     const char *parallel_devices[MAX_PARALLEL_PORTS];
5385     int parallel_device_index;
5386     const char *loadvm = NULL;
5387     QEMUMachine *machine;
5388     const char *cpu_model;
5389     const char *usb_devices[MAX_USB_CMDLINE];
5390     int usb_devices_index;
5391     int fds[2];
5392     int tb_size;
5393     const char *pid_file = NULL;
5394     int autostart;
5395     const char *incoming = NULL;
5396
5397     LIST_INIT (&vm_change_state_head);
5398 #ifndef _WIN32
5399     {
5400         struct sigaction act;
5401         sigfillset(&act.sa_mask);
5402         act.sa_flags = 0;
5403         act.sa_handler = SIG_IGN;
5404         sigaction(SIGPIPE, &act, NULL);
5405     }
5406 #else
5407     SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5408     /* Note: cpu_interrupt() is currently not SMP safe, so we force
5409        QEMU to run on a single CPU */
5410     {
5411         HANDLE h;
5412         DWORD mask, smask;
5413         int i;
5414         h = GetCurrentProcess();
5415         if (GetProcessAffinityMask(h, &mask, &smask)) {
5416             for(i = 0; i < 32; i++) {
5417                 if (mask & (1 << i))
5418                     break;
5419             }
5420             if (i != 32) {
5421                 mask = 1 << i;
5422                 SetProcessAffinityMask(h, mask);
5423             }
5424         }
5425     }
5426 #endif
5427
5428     register_machines();
5429     machine = first_machine;
5430     cpu_model = NULL;
5431     initrd_filename = NULL;
5432     ram_size = 0;
5433     vga_ram_size = VGA_RAM_SIZE;
5434 #ifdef CONFIG_GDBSTUB
5435     use_gdbstub = 0;
5436     gdbstub_port = DEFAULT_GDBSTUB_PORT;
5437 #endif
5438     snapshot = 0;
5439     nographic = 0;
5440     curses = 0;
5441     kernel_filename = NULL;
5442     kernel_cmdline = "";
5443     cyls = heads = secs = 0;
5444     translation = BIOS_ATA_TRANSLATION_AUTO;
5445     monitor_device = "vc";
5446
5447     serial_devices[0] = "vc:80Cx24C";
5448     for(i = 1; i < MAX_SERIAL_PORTS; i++)
5449         serial_devices[i] = NULL;
5450     serial_device_index = 0;
5451
5452     parallel_devices[0] = "vc:640x480";
5453     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5454         parallel_devices[i] = NULL;
5455     parallel_device_index = 0;
5456
5457     usb_devices_index = 0;
5458
5459     nb_net_clients = 0;
5460     nb_drives = 0;
5461     nb_drives_opt = 0;
5462     hda_index = -1;
5463
5464     nb_nics = 0;
5465
5466     tb_size = 0;
5467     autostart= 1;
5468
5469     optind = 1;
5470     for(;;) {
5471         if (optind >= argc)
5472             break;
5473         r = argv[optind];
5474         if (r[0] != '-') {
5475             hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5476         } else {
5477             const QEMUOption *popt;
5478
5479             optind++;
5480             /* Treat --foo the same as -foo.  */
5481             if (r[1] == '-')
5482                 r++;
5483             popt = qemu_options;
5484             for(;;) {
5485                 if (!popt->name) {
5486                     fprintf(stderr, "%s: invalid option -- '%s'\n",
5487                             argv[0], r);
5488                     exit(1);
5489                 }
5490                 if (!strcmp(popt->name, r + 1))
5491                     break;
5492                 popt++;
5493             }
5494             if (popt->flags & HAS_ARG) {
5495                 if (optind >= argc) {
5496                     fprintf(stderr, "%s: option '%s' requires an argument\n",
5497                             argv[0], r);
5498                     exit(1);
5499                 }
5500                 optarg = argv[optind++];
5501             } else {
5502                 optarg = NULL;
5503             }
5504
5505             switch(popt->index) {
5506             case QEMU_OPTION_M:
5507                 machine = find_machine(optarg);
5508                 if (!machine) {
5509                     QEMUMachine *m;
5510                     printf("Supported machines are:\n");
5511                     for(m = first_machine; m != NULL; m = m->next) {
5512                         printf("%-10s %s%s\n",
5513                                m->name, m->desc,
5514                                m == first_machine ? " (default)" : "");
5515                     }
5516                     exit(*optarg != '?');
5517                 }
5518                 break;
5519             case QEMU_OPTION_cpu:
5520                 /* hw initialization will check this */
5521                 if (*optarg == '?') {
5522 /* XXX: implement xxx_cpu_list for targets that still miss it */
5523 #if defined(cpu_list)
5524                     cpu_list(stdout, &fprintf);
5525 #endif
5526                     exit(0);
5527                 } else {
5528                     cpu_model = optarg;
5529                 }
5530                 break;
5531             case QEMU_OPTION_initrd:
5532                 initrd_filename = optarg;
5533                 break;
5534             case QEMU_OPTION_hda:
5535                 if (cyls == 0)
5536                     hda_index = drive_add(optarg, HD_ALIAS, 0);
5537                 else
5538                     hda_index = drive_add(optarg, HD_ALIAS
5539                              ",cyls=%d,heads=%d,secs=%d%s",
5540                              0, cyls, heads, secs,
5541                              translation == BIOS_ATA_TRANSLATION_LBA ?
5542                                  ",trans=lba" :
5543                              translation == BIOS_ATA_TRANSLATION_NONE ?
5544                                  ",trans=none" : "");
5545                  break;
5546             case QEMU_OPTION_hdb:
5547             case QEMU_OPTION_hdc:
5548             case QEMU_OPTION_hdd:
5549                 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5550                 break;
5551             case QEMU_OPTION_drive:
5552                 drive_add(NULL, "%s", optarg);
5553                 break;
5554             case QEMU_OPTION_mtdblock:
5555                 drive_add(optarg, MTD_ALIAS);
5556                 break;
5557             case QEMU_OPTION_sd:
5558                 drive_add(optarg, SD_ALIAS);
5559                 break;
5560             case QEMU_OPTION_pflash:
5561                 drive_add(optarg, PFLASH_ALIAS);
5562                 break;
5563             case QEMU_OPTION_snapshot:
5564                 snapshot = 1;
5565                 break;
5566             case QEMU_OPTION_hdachs:
5567                 {
5568                     const char *p;
5569                     p = optarg;
5570                     cyls = strtol(p, (char **)&p, 0);
5571                     if (cyls < 1 || cyls > 16383)
5572                         goto chs_fail;
5573                     if (*p != ',')
5574                         goto chs_fail;
5575                     p++;
5576                     heads = strtol(p, (char **)&p, 0);
5577                     if (heads < 1 || heads > 16)
5578                         goto chs_fail;
5579                     if (*p != ',')
5580                         goto chs_fail;
5581                     p++;
5582                     secs = strtol(p, (char **)&p, 0);
5583                     if (secs < 1 || secs > 63)
5584                         goto chs_fail;
5585                     if (*p == ',') {
5586                         p++;
5587                         if (!strcmp(p, "none"))
5588                             translation = BIOS_ATA_TRANSLATION_NONE;
5589                         else if (!strcmp(p, "lba"))
5590                             translation = BIOS_ATA_TRANSLATION_LBA;
5591                         else if (!strcmp(p, "auto"))
5592                             translation = BIOS_ATA_TRANSLATION_AUTO;
5593                         else
5594                             goto chs_fail;
5595                     } else if (*p != '\0') {
5596                     chs_fail:
5597                         fprintf(stderr, "qemu: invalid physical CHS format\n");
5598                         exit(1);
5599                     }
5600                     if (hda_index != -1)
5601                         snprintf(drives_opt[hda_index].opt,
5602                                  sizeof(drives_opt[hda_index].opt),
5603                                  HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5604                                  0, cyls, heads, secs,
5605                                  translation == BIOS_ATA_TRANSLATION_LBA ?
5606                                     ",trans=lba" :
5607                                  translation == BIOS_ATA_TRANSLATION_NONE ?
5608                                      ",trans=none" : "");
5609                 }
5610                 break;
5611             case QEMU_OPTION_nographic:
5612                 nographic = 1;
5613                 break;
5614 #ifdef CONFIG_CURSES
5615             case QEMU_OPTION_curses:
5616                 curses = 1;
5617                 break;
5618 #endif
5619             case QEMU_OPTION_portrait:
5620                 graphic_rotate = 1;
5621                 break;
5622             case QEMU_OPTION_kernel:
5623                 kernel_filename = optarg;
5624                 break;
5625             case QEMU_OPTION_append:
5626                 kernel_cmdline = optarg;
5627                 break;
5628             case QEMU_OPTION_cdrom:
5629                 drive_add(optarg, CDROM_ALIAS);
5630                 break;
5631             case QEMU_OPTION_boot:
5632                 boot_devices = optarg;
5633                 /* We just do some generic consistency checks */
5634                 {
5635                     /* Could easily be extended to 64 devices if needed */
5636                     const char *p;
5637                     
5638                     boot_devices_bitmap = 0;
5639                     for (p = boot_devices; *p != '\0'; p++) {
5640                         /* Allowed boot devices are:
5641                          * a b     : floppy disk drives
5642                          * c ... f : IDE disk drives
5643                          * g ... m : machine implementation dependant drives
5644                          * n ... p : network devices
5645                          * It's up to each machine implementation to check
5646                          * if the given boot devices match the actual hardware
5647                          * implementation and firmware features.
5648                          */
5649                         if (*p < 'a' || *p > 'q') {
5650                             fprintf(stderr, "Invalid boot device '%c'\n", *p);
5651                             exit(1);
5652                         }
5653                         if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5654                             fprintf(stderr,
5655                                     "Boot device '%c' was given twice\n",*p);
5656                             exit(1);
5657                         }
5658                         boot_devices_bitmap |= 1 << (*p - 'a');
5659                     }
5660                 }
5661                 break;
5662             case QEMU_OPTION_fda:
5663             case QEMU_OPTION_fdb:
5664                 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5665                 break;
5666 #ifdef TARGET_I386
5667             case QEMU_OPTION_no_fd_bootchk:
5668                 fd_bootchk = 0;
5669                 break;
5670 #endif
5671             case QEMU_OPTION_net:
5672                 if (nb_net_clients >= MAX_NET_CLIENTS) {
5673                     fprintf(stderr, "qemu: too many network clients\n");
5674                     exit(1);
5675                 }
5676                 net_clients[nb_net_clients] = optarg;
5677                 nb_net_clients++;
5678                 break;
5679 #ifdef CONFIG_SLIRP
5680             case QEMU_OPTION_tftp:
5681                 tftp_prefix = optarg;
5682                 break;
5683             case QEMU_OPTION_bootp:
5684                 bootp_filename = optarg;
5685                 break;
5686 #ifndef _WIN32
5687             case QEMU_OPTION_smb:
5688                 net_slirp_smb(optarg);
5689                 break;
5690 #endif
5691             case QEMU_OPTION_redir:
5692                 net_slirp_redir(optarg);
5693                 break;
5694 #endif
5695 #ifdef HAS_AUDIO
5696             case QEMU_OPTION_audio_help:
5697                 AUD_help ();
5698                 exit (0);
5699                 break;
5700             case QEMU_OPTION_soundhw:
5701                 select_soundhw (optarg);
5702                 break;
5703 #endif
5704             case QEMU_OPTION_h:
5705                 help(0);
5706                 break;
5707             case QEMU_OPTION_m: {
5708                 uint64_t value;
5709                 char *ptr;
5710
5711                 value = strtoul(optarg, &ptr, 10);
5712                 switch (*ptr) {
5713                 case 0: case 'M': case 'm':
5714                     value <<= 20;
5715                     break;
5716                 case 'G': case 'g':
5717                     value <<= 30;
5718                     break;
5719                 default:
5720                     fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5721                     exit(1);
5722                 }
5723
5724                 /* On 32-bit hosts, QEMU is limited by virtual address space */
5725                 if (value > (2047 << 20)
5726 #ifndef USE_KQEMU
5727                     && HOST_LONG_BITS == 32
5728 #endif
5729                     ) {
5730                     fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5731                     exit(1);
5732                 }
5733                 if (value != (uint64_t)(ram_addr_t)value) {
5734                     fprintf(stderr, "qemu: ram size too large\n");
5735                     exit(1);
5736                 }
5737                 ram_size = value;
5738                 break;
5739             }
5740             case QEMU_OPTION_d:
5741                 {
5742                     int mask;
5743                     const CPULogItem *item;
5744
5745                     mask = cpu_str_to_log_mask(optarg);
5746                     if (!mask) {
5747                         printf("Log items (comma separated):\n");
5748                     for(item = cpu_log_items; item->mask != 0; item++) {
5749                         printf("%-10s %s\n", item->name, item->help);
5750                     }
5751                     exit(1);
5752                     }
5753                     cpu_set_log(mask);
5754                 }
5755                 break;
5756 #ifdef CONFIG_GDBSTUB
5757             case QEMU_OPTION_s:
5758                 use_gdbstub = 1;
5759                 break;
5760             case QEMU_OPTION_p:
5761                 gdbstub_port = optarg;
5762                 break;
5763 #endif
5764             case QEMU_OPTION_L:
5765                 bios_dir = optarg;
5766                 break;
5767             case QEMU_OPTION_bios:
5768                 bios_name = optarg;
5769                 break;
5770             case QEMU_OPTION_S:
5771                 autostart = 0;
5772                 break;
5773             case QEMU_OPTION_k:
5774                 keyboard_layout = optarg;
5775                 break;
5776             case QEMU_OPTION_localtime:
5777                 rtc_utc = 0;
5778                 break;
5779             case QEMU_OPTION_vga:
5780                 select_vgahw (optarg);
5781                 break;
5782             case QEMU_OPTION_g:
5783                 {
5784                     const char *p;
5785                     int w, h, depth;
5786                     p = optarg;
5787                     w = strtol(p, (char **)&p, 10);
5788                     if (w <= 0) {
5789                     graphic_error:
5790                         fprintf(stderr, "qemu: invalid resolution or depth\n");
5791                         exit(1);
5792                     }
5793                     if (*p != 'x')
5794                         goto graphic_error;
5795                     p++;
5796                     h = strtol(p, (char **)&p, 10);
5797                     if (h <= 0)
5798                         goto graphic_error;
5799                     if (*p == 'x') {
5800                         p++;
5801                         depth = strtol(p, (char **)&p, 10);
5802                         if (depth != 8 && depth != 15 && depth != 16 &&
5803                             depth != 24 && depth != 32)
5804                             goto graphic_error;
5805                     } else if (*p == '\0') {
5806                         depth = graphic_depth;
5807                     } else {
5808                         goto graphic_error;
5809                     }
5810
5811                     graphic_width = w;
5812                     graphic_height = h;
5813                     graphic_depth = depth;
5814                 }
5815                 break;
5816             case QEMU_OPTION_echr:
5817                 {
5818                     char *r;
5819                     term_escape_char = strtol(optarg, &r, 0);
5820                     if (r == optarg)
5821                         printf("Bad argument to echr\n");
5822                     break;
5823                 }
5824             case QEMU_OPTION_monitor:
5825                 monitor_device = optarg;
5826                 break;
5827             case QEMU_OPTION_serial:
5828                 if (serial_device_index >= MAX_SERIAL_PORTS) {
5829                     fprintf(stderr, "qemu: too many serial ports\n");
5830                     exit(1);
5831                 }
5832                 serial_devices[serial_device_index] = optarg;
5833                 serial_device_index++;
5834                 break;
5835             case QEMU_OPTION_parallel:
5836                 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5837                     fprintf(stderr, "qemu: too many parallel ports\n");
5838                     exit(1);
5839                 }
5840                 parallel_devices[parallel_device_index] = optarg;
5841                 parallel_device_index++;
5842                 break;
5843             case QEMU_OPTION_loadvm:
5844                 loadvm = optarg;
5845                 break;
5846             case QEMU_OPTION_full_screen:
5847                 full_screen = 1;
5848                 break;
5849 #ifdef CONFIG_SDL
5850             case QEMU_OPTION_no_frame:
5851                 no_frame = 1;
5852                 break;
5853             case QEMU_OPTION_alt_grab:
5854                 alt_grab = 1;
5855                 break;
5856             case QEMU_OPTION_no_quit:
5857                 no_quit = 1;
5858                 break;
5859 #endif
5860             case QEMU_OPTION_pidfile:
5861                 pid_file = optarg;
5862                 break;
5863 #ifdef TARGET_I386
5864             case QEMU_OPTION_win2k_hack:
5865                 win2k_install_hack = 1;
5866                 break;
5867 #endif
5868 #ifdef USE_KQEMU
5869             case QEMU_OPTION_no_kqemu:
5870                 kqemu_allowed = 0;
5871                 break;
5872             case QEMU_OPTION_kernel_kqemu:
5873                 kqemu_allowed = 2;
5874                 break;
5875 #endif
5876 #ifdef CONFIG_KVM
5877             case QEMU_OPTION_enable_kvm:
5878                 kvm_allowed = 1;
5879 #ifdef USE_KQEMU
5880                 kqemu_allowed = 0;
5881 #endif
5882                 break;
5883 #endif
5884             case QEMU_OPTION_usb:
5885                 usb_enabled = 1;
5886                 break;
5887             case QEMU_OPTION_usbdevice:
5888                 usb_enabled = 1;
5889                 if (usb_devices_index >= MAX_USB_CMDLINE) {
5890                     fprintf(stderr, "Too many USB devices\n");
5891                     exit(1);
5892                 }
5893                 usb_devices[usb_devices_index] = optarg;
5894                 usb_devices_index++;
5895                 break;
5896             case QEMU_OPTION_smp:
5897                 smp_cpus = atoi(optarg);
5898                 if (smp_cpus < 1) {
5899                     fprintf(stderr, "Invalid number of CPUs\n");
5900                     exit(1);
5901                 }
5902                 break;
5903             case QEMU_OPTION_vnc:
5904                 vnc_display = optarg;
5905                 break;
5906             case QEMU_OPTION_no_acpi:
5907                 acpi_enabled = 0;
5908                 break;
5909             case QEMU_OPTION_no_reboot:
5910                 no_reboot = 1;
5911                 break;
5912             case QEMU_OPTION_no_shutdown:
5913                 no_shutdown = 1;
5914                 break;
5915             case QEMU_OPTION_show_cursor:
5916                 cursor_hide = 0;
5917                 break;
5918             case QEMU_OPTION_uuid:
5919                 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5920                     fprintf(stderr, "Fail to parse UUID string."
5921                             " Wrong format.\n");
5922                     exit(1);
5923                 }
5924                 break;
5925             case QEMU_OPTION_daemonize:
5926                 daemonize = 1;
5927                 break;
5928             case QEMU_OPTION_option_rom:
5929                 if (nb_option_roms >= MAX_OPTION_ROMS) {
5930                     fprintf(stderr, "Too many option ROMs\n");
5931                     exit(1);
5932                 }
5933                 option_rom[nb_option_roms] = optarg;
5934                 nb_option_roms++;
5935                 break;
5936             case QEMU_OPTION_semihosting:
5937                 semihosting_enabled = 1;
5938                 break;
5939             case QEMU_OPTION_name:
5940                 qemu_name = optarg;
5941                 break;
5942 #ifdef TARGET_SPARC
5943             case QEMU_OPTION_prom_env:
5944                 if (nb_prom_envs >= MAX_PROM_ENVS) {
5945                     fprintf(stderr, "Too many prom variables\n");
5946                     exit(1);
5947                 }
5948                 prom_envs[nb_prom_envs] = optarg;
5949                 nb_prom_envs++;
5950                 break;
5951 #endif
5952 #ifdef TARGET_ARM
5953             case QEMU_OPTION_old_param:
5954                 old_param = 1;
5955                 break;
5956 #endif
5957             case QEMU_OPTION_clock:
5958                 configure_alarms(optarg);
5959                 break;
5960             case QEMU_OPTION_startdate:
5961                 {
5962                     struct tm tm;
5963                     time_t rtc_start_date;
5964                     if (!strcmp(optarg, "now")) {
5965                         rtc_date_offset = -1;
5966                     } else {
5967                         if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5968                                &tm.tm_year,
5969                                &tm.tm_mon,
5970                                &tm.tm_mday,
5971                                &tm.tm_hour,
5972                                &tm.tm_min,
5973                                &tm.tm_sec) == 6) {
5974                             /* OK */
5975                         } else if (sscanf(optarg, "%d-%d-%d",
5976                                           &tm.tm_year,
5977                                           &tm.tm_mon,
5978                                           &tm.tm_mday) == 3) {
5979                             tm.tm_hour = 0;
5980                             tm.tm_min = 0;
5981                             tm.tm_sec = 0;
5982                         } else {
5983                             goto date_fail;
5984                         }
5985                         tm.tm_year -= 1900;
5986                         tm.tm_mon--;
5987                         rtc_start_date = mktimegm(&tm);
5988                         if (rtc_start_date == -1) {
5989                         date_fail:
5990                             fprintf(stderr, "Invalid date format. Valid format are:\n"
5991                                     "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5992                             exit(1);
5993                         }
5994                         rtc_date_offset = time(NULL) - rtc_start_date;
5995                     }
5996                 }
5997                 break;
5998             case QEMU_OPTION_tb_size:
5999                 tb_size = strtol(optarg, NULL, 0);
6000                 if (tb_size < 0)
6001                     tb_size = 0;
6002                 break;
6003             case QEMU_OPTION_icount:
6004                 use_icount = 1;
6005                 if (strcmp(optarg, "auto") == 0) {
6006                     icount_time_shift = -1;
6007                 } else {
6008                     icount_time_shift = strtol(optarg, NULL, 0);
6009                 }
6010                 break;
6011             case QEMU_OPTION_incoming:
6012                 incoming = optarg;
6013                 break;
6014             }
6015         }
6016     }
6017
6018 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
6019     if (kvm_allowed && kqemu_allowed) {
6020         fprintf(stderr,
6021                 "You can not enable both KVM and kqemu at the same time\n");
6022         exit(1);
6023     }
6024 #endif
6025
6026     machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
6027     if (smp_cpus > machine->max_cpus) {
6028         fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
6029                 "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
6030                 machine->max_cpus);
6031         exit(1);
6032     }
6033
6034     if (nographic) {
6035        if (serial_device_index == 0)
6036            serial_devices[0] = "stdio";
6037        if (parallel_device_index == 0)
6038            parallel_devices[0] = "null";
6039        if (strncmp(monitor_device, "vc", 2) == 0)
6040            monitor_device = "stdio";
6041     }
6042
6043 #ifndef _WIN32
6044     if (daemonize) {
6045         pid_t pid;
6046
6047         if (pipe(fds) == -1)
6048             exit(1);
6049
6050         pid = fork();
6051         if (pid > 0) {
6052             uint8_t status;
6053             ssize_t len;
6054
6055             close(fds[1]);
6056
6057         again:
6058             len = read(fds[0], &status, 1);
6059             if (len == -1 && (errno == EINTR))
6060                 goto again;
6061
6062             if (len != 1)
6063                 exit(1);
6064             else if (status == 1) {
6065                 fprintf(stderr, "Could not acquire pidfile\n");
6066                 exit(1);
6067             } else
6068                 exit(0);
6069         } else if (pid < 0)
6070             exit(1);
6071
6072         setsid();
6073
6074         pid = fork();
6075         if (pid > 0)
6076             exit(0);
6077         else if (pid < 0)
6078             exit(1);
6079
6080         umask(027);
6081
6082         signal(SIGTSTP, SIG_IGN);
6083         signal(SIGTTOU, SIG_IGN);
6084         signal(SIGTTIN, SIG_IGN);
6085     }
6086 #endif
6087
6088     if (pid_file && qemu_create_pidfile(pid_file) != 0) {
6089         if (daemonize) {
6090             uint8_t status = 1;
6091             write(fds[1], &status, 1);
6092         } else
6093             fprintf(stderr, "Could not acquire pid file\n");
6094         exit(1);
6095     }
6096
6097 #ifdef USE_KQEMU
6098     if (smp_cpus > 1)
6099         kqemu_allowed = 0;
6100 #endif
6101     linux_boot = (kernel_filename != NULL);
6102     net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6103
6104     if (!linux_boot && net_boot == 0 &&
6105         !machine->nodisk_ok && nb_drives_opt == 0)
6106         help(1);
6107
6108     if (!linux_boot && *kernel_cmdline != '\0') {
6109         fprintf(stderr, "-append only allowed with -kernel option\n");
6110         exit(1);
6111     }
6112
6113     if (!linux_boot && initrd_filename != NULL) {
6114         fprintf(stderr, "-initrd only allowed with -kernel option\n");
6115         exit(1);
6116     }
6117
6118     /* boot to floppy or the default cd if no hard disk defined yet */
6119     if (!boot_devices[0]) {
6120         boot_devices = "cad";
6121     }
6122     setvbuf(stdout, NULL, _IOLBF, 0);
6123
6124     init_timers();
6125     if (init_timer_alarm() < 0) {
6126         fprintf(stderr, "could not initialize alarm timer\n");
6127         exit(1);
6128     }
6129     if (use_icount && icount_time_shift < 0) {
6130         use_icount = 2;
6131         /* 125MIPS seems a reasonable initial guess at the guest speed.
6132            It will be corrected fairly quickly anyway.  */
6133         icount_time_shift = 3;
6134         init_icount_adjust();
6135     }
6136
6137 #ifdef _WIN32
6138     socket_init();
6139 #endif
6140
6141     /* init network clients */
6142     if (nb_net_clients == 0) {
6143         /* if no clients, we use a default config */
6144         net_clients[nb_net_clients++] = "nic";
6145 #ifdef CONFIG_SLIRP
6146         net_clients[nb_net_clients++] = "user";
6147 #endif
6148     }
6149
6150     for(i = 0;i < nb_net_clients; i++) {
6151         if (net_client_parse(net_clients[i]) < 0)
6152             exit(1);
6153     }
6154     net_client_check();
6155
6156 #ifdef TARGET_I386
6157     /* XXX: this should be moved in the PC machine instantiation code */
6158     if (net_boot != 0) {
6159         int netroms = 0;
6160         for (i = 0; i < nb_nics && i < 4; i++) {
6161             const char *model = nd_table[i].model;
6162             char buf[1024];
6163             if (net_boot & (1 << i)) {
6164                 if (model == NULL)
6165                     model = "ne2k_pci";
6166                 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
6167                 if (get_image_size(buf) > 0) {
6168                     if (nb_option_roms >= MAX_OPTION_ROMS) {
6169                         fprintf(stderr, "Too many option ROMs\n");
6170                         exit(1);
6171                     }
6172                     option_rom[nb_option_roms] = strdup(buf);
6173                     nb_option_roms++;
6174                     netroms++;
6175                 }
6176             }
6177         }
6178         if (netroms == 0) {
6179             fprintf(stderr, "No valid PXE rom found for network device\n");
6180             exit(1);
6181         }
6182     }
6183 #endif
6184
6185     /* init the memory */
6186     phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
6187
6188     if (machine->ram_require & RAMSIZE_FIXED) {
6189         if (ram_size > 0) {
6190             if (ram_size < phys_ram_size) {
6191                 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
6192                                 machine->name, (unsigned long long) phys_ram_size);
6193                 exit(-1);
6194             }
6195
6196             phys_ram_size = ram_size;
6197         } else
6198             ram_size = phys_ram_size;
6199     } else {
6200         if (ram_size == 0)
6201             ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6202
6203         phys_ram_size += ram_size;
6204     }
6205
6206     phys_ram_base = qemu_vmalloc(phys_ram_size);
6207     if (!phys_ram_base) {
6208         fprintf(stderr, "Could not allocate physical memory\n");
6209         exit(1);
6210     }
6211
6212     /* init the dynamic translator */
6213     cpu_exec_init_all(tb_size * 1024 * 1024);
6214
6215     bdrv_init();
6216
6217     /* we always create the cdrom drive, even if no disk is there */
6218
6219     if (nb_drives_opt < MAX_DRIVES)
6220         drive_add(NULL, CDROM_ALIAS);
6221
6222     /* we always create at least one floppy */
6223
6224     if (nb_drives_opt < MAX_DRIVES)
6225         drive_add(NULL, FD_ALIAS, 0);
6226
6227     /* we always create one sd slot, even if no card is in it */
6228
6229     if (nb_drives_opt < MAX_DRIVES)
6230         drive_add(NULL, SD_ALIAS);
6231
6232     /* open the virtual block devices */
6233
6234     for(i = 0; i < nb_drives_opt; i++)
6235         if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6236             exit(1);
6237
6238     register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6239     register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6240
6241     /* terminal init */
6242     memset(&display_state, 0, sizeof(display_state));
6243     if (nographic) {
6244         if (curses) {
6245             fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
6246             exit(1);
6247         }
6248         /* nearly nothing to do */
6249         dumb_display_init(ds);
6250     } else if (vnc_display != NULL) {
6251         vnc_display_init(ds);
6252         if (vnc_display_open(ds, vnc_display) < 0)
6253             exit(1);
6254     } else
6255 #if defined(CONFIG_CURSES)
6256     if (curses) {
6257         curses_display_init(ds, full_screen);
6258     } else
6259 #endif
6260     {
6261 #if defined(CONFIG_SDL)
6262         sdl_display_init(ds, full_screen, no_frame);
6263 #elif defined(CONFIG_COCOA)
6264         cocoa_display_init(ds, full_screen);
6265 #else
6266         dumb_display_init(ds);
6267 #endif
6268     }
6269
6270 #ifndef _WIN32
6271     /* must be after terminal init, SDL library changes signal handlers */
6272     termsig_setup();
6273 #endif
6274
6275     /* Maintain compatibility with multiple stdio monitors */
6276     if (!strcmp(monitor_device,"stdio")) {
6277         for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6278             const char *devname = serial_devices[i];
6279             if (devname && !strcmp(devname,"mon:stdio")) {
6280                 monitor_device = NULL;
6281                 break;
6282             } else if (devname && !strcmp(devname,"stdio")) {
6283                 monitor_device = NULL;
6284                 serial_devices[i] = "mon:stdio";
6285                 break;
6286             }
6287         }
6288     }
6289     if (monitor_device) {
6290         monitor_hd = qemu_chr_open("monitor", monitor_device);
6291         if (!monitor_hd) {
6292             fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6293             exit(1);
6294         }
6295         monitor_init(monitor_hd, !nographic);
6296     }
6297
6298     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6299         const char *devname = serial_devices[i];
6300         if (devname && strcmp(devname, "none")) {
6301             char label[32];
6302             snprintf(label, sizeof(label), "serial%d", i);
6303             serial_hds[i] = qemu_chr_open(label, devname);
6304             if (!serial_hds[i]) {
6305                 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6306                         devname);
6307                 exit(1);
6308             }
6309             if (strstart(devname, "vc", 0))
6310                 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6311         }
6312     }
6313
6314     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6315         const char *devname = parallel_devices[i];
6316         if (devname && strcmp(devname, "none")) {
6317             char label[32];
6318             snprintf(label, sizeof(label), "parallel%d", i);
6319             parallel_hds[i] = qemu_chr_open(label, devname);
6320             if (!parallel_hds[i]) {
6321                 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6322                         devname);
6323                 exit(1);
6324             }
6325             if (strstart(devname, "vc", 0))
6326                 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6327         }
6328     }
6329
6330     if (kvm_enabled()) {
6331         int ret;
6332
6333         ret = kvm_init(smp_cpus);
6334         if (ret < 0) {
6335             fprintf(stderr, "failed to initialize KVM\n");
6336             exit(1);
6337         }
6338     }
6339
6340     machine->init(ram_size, vga_ram_size, boot_devices, ds,
6341                   kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6342
6343     /* init USB devices */
6344     if (usb_enabled) {
6345         for(i = 0; i < usb_devices_index; i++) {
6346             if (usb_device_add(usb_devices[i]) < 0) {
6347                 fprintf(stderr, "Warning: could not add USB device %s\n",
6348                         usb_devices[i]);
6349             }
6350         }
6351     }
6352
6353     if (display_state.dpy_refresh) {
6354         display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
6355         qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
6356     }
6357
6358 #ifdef CONFIG_GDBSTUB
6359     if (use_gdbstub) {
6360         /* XXX: use standard host:port notation and modify options
6361            accordingly. */
6362         if (gdbserver_start(gdbstub_port) < 0) {
6363             fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6364                     gdbstub_port);
6365             exit(1);
6366         }
6367     }
6368 #endif
6369
6370     if (loadvm)
6371         do_loadvm(loadvm);
6372
6373     if (incoming) {
6374         autostart = 0; /* fixme how to deal with -daemonize */
6375         qemu_start_incoming_migration(incoming);
6376     }
6377
6378     {
6379         /* XXX: simplify init */
6380         read_passwords();
6381         if (autostart) {
6382             vm_start();
6383         }
6384     }
6385
6386     if (daemonize) {
6387         uint8_t status = 0;
6388         ssize_t len;
6389         int fd;
6390
6391     again1:
6392         len = write(fds[1], &status, 1);
6393         if (len == -1 && (errno == EINTR))
6394             goto again1;
6395
6396         if (len != 1)
6397             exit(1);
6398
6399         chdir("/");
6400         TFR(fd = open("/dev/null", O_RDWR));
6401         if (fd == -1)
6402             exit(1);
6403
6404         dup2(fd, 0);
6405         dup2(fd, 1);
6406         dup2(fd, 2);
6407
6408         close(fd);
6409     }
6410
6411     main_loop();
6412     quit_timers();
6413     net_cleanup();
6414
6415     return 0;
6416 }