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