Run timers from host alarm timer callback
[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 void try_to_rearm_timer(void *opaque)
1693 {
1694     struct qemu_alarm_timer *t = opaque;
1695     ssize_t len;
1696
1697     /* Drain the notify pipe */
1698     do {
1699         char buffer[512];
1700         len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1701     } while ((len == -1 && errno == EINTR) || len > 0);
1702
1703     /* vm time timers */
1704     if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
1705         qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
1706                         qemu_get_clock(vm_clock));
1707
1708     /* real time timers */
1709     qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
1710                     qemu_get_clock(rt_clock));
1711
1712     if (t->flags & ALARM_FLAG_EXPIRED) {
1713         alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1714         qemu_rearm_alarm_timer(alarm_timer);
1715     }
1716 }
1717
1718 static int init_timer_alarm(void)
1719 {
1720     struct qemu_alarm_timer *t = NULL;
1721     int i, err = -1;
1722     int fds[2];
1723
1724     err = pipe(fds);
1725     if (err == -1)
1726         return -errno;
1727
1728     err = fcntl_setfl(fds[0], O_NONBLOCK);
1729     if (err < 0)
1730         goto fail;
1731
1732     err = fcntl_setfl(fds[1], O_NONBLOCK);
1733     if (err < 0)
1734         goto fail;
1735
1736     alarm_timer_rfd = fds[0];
1737     alarm_timer_wfd = fds[1];
1738
1739     for (i = 0; alarm_timers[i].name; i++) {
1740         t = &alarm_timers[i];
1741
1742         err = t->start(t);
1743         if (!err)
1744             break;
1745     }
1746
1747     if (err) {
1748         err = -ENOENT;
1749         goto fail;
1750     }
1751
1752     qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1753                          try_to_rearm_timer, NULL, t);
1754
1755     alarm_timer = t;
1756
1757     return 0;
1758
1759 fail:
1760     close(fds[0]);
1761     close(fds[1]);
1762     return err;
1763 }
1764
1765 static void quit_timers(void)
1766 {
1767     alarm_timer->stop(alarm_timer);
1768     alarm_timer = NULL;
1769 }
1770
1771 /***********************************************************/
1772 /* host time/date access */
1773 void qemu_get_timedate(struct tm *tm, int offset)
1774 {
1775     time_t ti;
1776     struct tm *ret;
1777
1778     time(&ti);
1779     ti += offset;
1780     if (rtc_date_offset == -1) {
1781         if (rtc_utc)
1782             ret = gmtime(&ti);
1783         else
1784             ret = localtime(&ti);
1785     } else {
1786         ti -= rtc_date_offset;
1787         ret = gmtime(&ti);
1788     }
1789
1790     memcpy(tm, ret, sizeof(struct tm));
1791 }
1792
1793 int qemu_timedate_diff(struct tm *tm)
1794 {
1795     time_t seconds;
1796
1797     if (rtc_date_offset == -1)
1798         if (rtc_utc)
1799             seconds = mktimegm(tm);
1800         else
1801             seconds = mktime(tm);
1802     else
1803         seconds = mktimegm(tm) + rtc_date_offset;
1804
1805     return seconds - time(NULL);
1806 }
1807
1808 #ifdef _WIN32
1809 static void socket_cleanup(void)
1810 {
1811     WSACleanup();
1812 }
1813
1814 static int socket_init(void)
1815 {
1816     WSADATA Data;
1817     int ret, err;
1818
1819     ret = WSAStartup(MAKEWORD(2,2), &Data);
1820     if (ret != 0) {
1821         err = WSAGetLastError();
1822         fprintf(stderr, "WSAStartup: %d\n", err);
1823         return -1;
1824     }
1825     atexit(socket_cleanup);
1826     return 0;
1827 }
1828 #endif
1829
1830 const char *get_opt_name(char *buf, int buf_size, const char *p)
1831 {
1832     char *q;
1833
1834     q = buf;
1835     while (*p != '\0' && *p != '=') {
1836         if (q && (q - buf) < buf_size - 1)
1837             *q++ = *p;
1838         p++;
1839     }
1840     if (q)
1841         *q = '\0';
1842
1843     return p;
1844 }
1845
1846 const char *get_opt_value(char *buf, int buf_size, const char *p)
1847 {
1848     char *q;
1849
1850     q = buf;
1851     while (*p != '\0') {
1852         if (*p == ',') {
1853             if (*(p + 1) != ',')
1854                 break;
1855             p++;
1856         }
1857         if (q && (q - buf) < buf_size - 1)
1858             *q++ = *p;
1859         p++;
1860     }
1861     if (q)
1862         *q = '\0';
1863
1864     return p;
1865 }
1866
1867 int get_param_value(char *buf, int buf_size,
1868                     const char *tag, const char *str)
1869 {
1870     const char *p;
1871     char option[128];
1872
1873     p = str;
1874     for(;;) {
1875         p = get_opt_name(option, sizeof(option), p);
1876         if (*p != '=')
1877             break;
1878         p++;
1879         if (!strcmp(tag, option)) {
1880             (void)get_opt_value(buf, buf_size, p);
1881             return strlen(buf);
1882         } else {
1883             p = get_opt_value(NULL, 0, p);
1884         }
1885         if (*p != ',')
1886             break;
1887         p++;
1888     }
1889     return 0;
1890 }
1891
1892 int check_params(char *buf, int buf_size,
1893                  const char * const *params, const char *str)
1894 {
1895     const char *p;
1896     int i;
1897
1898     p = str;
1899     for(;;) {
1900         p = get_opt_name(buf, buf_size, p);
1901         if (*p != '=')
1902             return -1;
1903         p++;
1904         for(i = 0; params[i] != NULL; i++)
1905             if (!strcmp(params[i], buf))
1906                 break;
1907         if (params[i] == NULL)
1908             return -1;
1909         p = get_opt_value(NULL, 0, p);
1910         if (*p != ',')
1911             break;
1912         p++;
1913     }
1914     return 0;
1915 }
1916
1917 /***********************************************************/
1918 /* Bluetooth support */
1919 static int nb_hcis;
1920 static int cur_hci;
1921 static struct HCIInfo *hci_table[MAX_NICS];
1922 #if 0
1923 static struct bt_vlan_s {
1924     struct bt_scatternet_s net;
1925     int id;
1926     struct bt_vlan_s *next;
1927 } *first_bt_vlan;
1928
1929 /* find or alloc a new bluetooth "VLAN" */
1930 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1931 {
1932     struct bt_vlan_s **pvlan, *vlan;
1933     for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1934         if (vlan->id == id)
1935             return &vlan->net;
1936     }
1937     vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1938     vlan->id = id;
1939     pvlan = &first_bt_vlan;
1940     while (*pvlan != NULL)
1941         pvlan = &(*pvlan)->next;
1942     *pvlan = vlan;
1943     return &vlan->net;
1944 }
1945 #endif
1946
1947 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1948 {
1949 }
1950
1951 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1952 {
1953     return -ENOTSUP;
1954 }
1955
1956 static struct HCIInfo null_hci = {
1957     .cmd_send = null_hci_send,
1958     .sco_send = null_hci_send,
1959     .acl_send = null_hci_send,
1960     .bdaddr_set = null_hci_addr_set,
1961 };
1962
1963 struct HCIInfo *qemu_next_hci(void)
1964 {
1965     if (cur_hci == nb_hcis)
1966         return &null_hci;
1967
1968     return hci_table[cur_hci++];
1969 }
1970
1971 /***********************************************************/
1972 /* QEMU Block devices */
1973
1974 #define HD_ALIAS "index=%d,media=disk"
1975 #ifdef TARGET_PPC
1976 #define CDROM_ALIAS "index=1,media=cdrom"
1977 #else
1978 #define CDROM_ALIAS "index=2,media=cdrom"
1979 #endif
1980 #define FD_ALIAS "index=%d,if=floppy"
1981 #define PFLASH_ALIAS "if=pflash"
1982 #define MTD_ALIAS "if=mtd"
1983 #define SD_ALIAS "index=0,if=sd"
1984
1985 static int drive_add(const char *file, const char *fmt, ...)
1986 {
1987     va_list ap;
1988
1989     if (nb_drives_opt >= MAX_DRIVES) {
1990         fprintf(stderr, "qemu: too many drives\n");
1991         exit(1);
1992     }
1993
1994     drives_opt[nb_drives_opt].file = file;
1995     va_start(ap, fmt);
1996     vsnprintf(drives_opt[nb_drives_opt].opt,
1997               sizeof(drives_opt[0].opt), fmt, ap);
1998     va_end(ap);
1999
2000     return nb_drives_opt++;
2001 }
2002
2003 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2004 {
2005     int index;
2006
2007     /* seek interface, bus and unit */
2008
2009     for (index = 0; index < nb_drives; index++)
2010         if (drives_table[index].type == type &&
2011             drives_table[index].bus == bus &&
2012             drives_table[index].unit == unit)
2013         return index;
2014
2015     return -1;
2016 }
2017
2018 int drive_get_max_bus(BlockInterfaceType type)
2019 {
2020     int max_bus;
2021     int index;
2022
2023     max_bus = -1;
2024     for (index = 0; index < nb_drives; index++) {
2025         if(drives_table[index].type == type &&
2026            drives_table[index].bus > max_bus)
2027             max_bus = drives_table[index].bus;
2028     }
2029     return max_bus;
2030 }
2031
2032 static void bdrv_format_print(void *opaque, const char *name)
2033 {
2034     fprintf(stderr, " %s", name);
2035 }
2036
2037 static int drive_init(struct drive_opt *arg, int snapshot,
2038                       QEMUMachine *machine)
2039 {
2040     char buf[128];
2041     char file[1024];
2042     char devname[128];
2043     const char *mediastr = "";
2044     BlockInterfaceType type;
2045     enum { MEDIA_DISK, MEDIA_CDROM } media;
2046     int bus_id, unit_id;
2047     int cyls, heads, secs, translation;
2048     BlockDriverState *bdrv;
2049     BlockDriver *drv = NULL;
2050     int max_devs;
2051     int index;
2052     int cache;
2053     int bdrv_flags;
2054     char *str = arg->opt;
2055     static const char * const params[] = { "bus", "unit", "if", "index",
2056                                            "cyls", "heads", "secs", "trans",
2057                                            "media", "snapshot", "file",
2058                                            "cache", "format", NULL };
2059
2060     if (check_params(buf, sizeof(buf), params, str) < 0) {
2061          fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2062                          buf, str);
2063          return -1;
2064     }
2065
2066     file[0] = 0;
2067     cyls = heads = secs = 0;
2068     bus_id = 0;
2069     unit_id = -1;
2070     translation = BIOS_ATA_TRANSLATION_AUTO;
2071     index = -1;
2072     cache = 1;
2073
2074     if (machine->use_scsi) {
2075         type = IF_SCSI;
2076         max_devs = MAX_SCSI_DEVS;
2077         pstrcpy(devname, sizeof(devname), "scsi");
2078     } else {
2079         type = IF_IDE;
2080         max_devs = MAX_IDE_DEVS;
2081         pstrcpy(devname, sizeof(devname), "ide");
2082     }
2083     media = MEDIA_DISK;
2084
2085     /* extract parameters */
2086
2087     if (get_param_value(buf, sizeof(buf), "bus", str)) {
2088         bus_id = strtol(buf, NULL, 0);
2089         if (bus_id < 0) {
2090             fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2091             return -1;
2092         }
2093     }
2094
2095     if (get_param_value(buf, sizeof(buf), "unit", str)) {
2096         unit_id = strtol(buf, NULL, 0);
2097         if (unit_id < 0) {
2098             fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2099             return -1;
2100         }
2101     }
2102
2103     if (get_param_value(buf, sizeof(buf), "if", str)) {
2104         pstrcpy(devname, sizeof(devname), buf);
2105         if (!strcmp(buf, "ide")) {
2106             type = IF_IDE;
2107             max_devs = MAX_IDE_DEVS;
2108         } else if (!strcmp(buf, "scsi")) {
2109             type = IF_SCSI;
2110             max_devs = MAX_SCSI_DEVS;
2111         } else if (!strcmp(buf, "floppy")) {
2112             type = IF_FLOPPY;
2113             max_devs = 0;
2114         } else if (!strcmp(buf, "pflash")) {
2115             type = IF_PFLASH;
2116             max_devs = 0;
2117         } else if (!strcmp(buf, "mtd")) {
2118             type = IF_MTD;
2119             max_devs = 0;
2120         } else if (!strcmp(buf, "sd")) {
2121             type = IF_SD;
2122             max_devs = 0;
2123         } else {
2124             fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2125             return -1;
2126         }
2127     }
2128
2129     if (get_param_value(buf, sizeof(buf), "index", str)) {
2130         index = strtol(buf, NULL, 0);
2131         if (index < 0) {
2132             fprintf(stderr, "qemu: '%s' invalid index\n", str);
2133             return -1;
2134         }
2135     }
2136
2137     if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2138         cyls = strtol(buf, NULL, 0);
2139     }
2140
2141     if (get_param_value(buf, sizeof(buf), "heads", str)) {
2142         heads = strtol(buf, NULL, 0);
2143     }
2144
2145     if (get_param_value(buf, sizeof(buf), "secs", str)) {
2146         secs = strtol(buf, NULL, 0);
2147     }
2148
2149     if (cyls || heads || secs) {
2150         if (cyls < 1 || cyls > 16383) {
2151             fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2152             return -1;
2153         }
2154         if (heads < 1 || heads > 16) {
2155             fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2156             return -1;
2157         }
2158         if (secs < 1 || secs > 63) {
2159             fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2160             return -1;
2161         }
2162     }
2163
2164     if (get_param_value(buf, sizeof(buf), "trans", str)) {
2165         if (!cyls) {
2166             fprintf(stderr,
2167                     "qemu: '%s' trans must be used with cyls,heads and secs\n",
2168                     str);
2169             return -1;
2170         }
2171         if (!strcmp(buf, "none"))
2172             translation = BIOS_ATA_TRANSLATION_NONE;
2173         else if (!strcmp(buf, "lba"))
2174             translation = BIOS_ATA_TRANSLATION_LBA;
2175         else if (!strcmp(buf, "auto"))
2176             translation = BIOS_ATA_TRANSLATION_AUTO;
2177         else {
2178             fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2179             return -1;
2180         }
2181     }
2182
2183     if (get_param_value(buf, sizeof(buf), "media", str)) {
2184         if (!strcmp(buf, "disk")) {
2185             media = MEDIA_DISK;
2186         } else if (!strcmp(buf, "cdrom")) {
2187             if (cyls || secs || heads) {
2188                 fprintf(stderr,
2189                         "qemu: '%s' invalid physical CHS format\n", str);
2190                 return -1;
2191             }
2192             media = MEDIA_CDROM;
2193         } else {
2194             fprintf(stderr, "qemu: '%s' invalid media\n", str);
2195             return -1;
2196         }
2197     }
2198
2199     if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2200         if (!strcmp(buf, "on"))
2201             snapshot = 1;
2202         else if (!strcmp(buf, "off"))
2203             snapshot = 0;
2204         else {
2205             fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2206             return -1;
2207         }
2208     }
2209
2210     if (get_param_value(buf, sizeof(buf), "cache", str)) {
2211         if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2212             cache = 0;
2213         else if (!strcmp(buf, "writethrough"))
2214             cache = 1;
2215         else if (!strcmp(buf, "writeback"))
2216             cache = 2;
2217         else {
2218            fprintf(stderr, "qemu: invalid cache option\n");
2219            return -1;
2220         }
2221     }
2222
2223     if (get_param_value(buf, sizeof(buf), "format", str)) {
2224        if (strcmp(buf, "?") == 0) {
2225             fprintf(stderr, "qemu: Supported formats:");
2226             bdrv_iterate_format(bdrv_format_print, NULL);
2227             fprintf(stderr, "\n");
2228             return -1;
2229         }
2230         drv = bdrv_find_format(buf);
2231         if (!drv) {
2232             fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2233             return -1;
2234         }
2235     }
2236
2237     if (arg->file == NULL)
2238         get_param_value(file, sizeof(file), "file", str);
2239     else
2240         pstrcpy(file, sizeof(file), arg->file);
2241
2242     /* compute bus and unit according index */
2243
2244     if (index != -1) {
2245         if (bus_id != 0 || unit_id != -1) {
2246             fprintf(stderr,
2247                     "qemu: '%s' index cannot be used with bus and unit\n", str);
2248             return -1;
2249         }
2250         if (max_devs == 0)
2251         {
2252             unit_id = index;
2253             bus_id = 0;
2254         } else {
2255             unit_id = index % max_devs;
2256             bus_id = index / max_devs;
2257         }
2258     }
2259
2260     /* if user doesn't specify a unit_id,
2261      * try to find the first free
2262      */
2263
2264     if (unit_id == -1) {
2265        unit_id = 0;
2266        while (drive_get_index(type, bus_id, unit_id) != -1) {
2267            unit_id++;
2268            if (max_devs && unit_id >= max_devs) {
2269                unit_id -= max_devs;
2270                bus_id++;
2271            }
2272        }
2273     }
2274
2275     /* check unit id */
2276
2277     if (max_devs && unit_id >= max_devs) {
2278         fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2279                         str, unit_id, max_devs - 1);
2280         return -1;
2281     }
2282
2283     /*
2284      * ignore multiple definitions
2285      */
2286
2287     if (drive_get_index(type, bus_id, unit_id) != -1)
2288         return 0;
2289
2290     /* init */
2291
2292     if (type == IF_IDE || type == IF_SCSI)
2293         mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2294     if (max_devs)
2295         snprintf(buf, sizeof(buf), "%s%i%s%i",
2296                  devname, bus_id, mediastr, unit_id);
2297     else
2298         snprintf(buf, sizeof(buf), "%s%s%i",
2299                  devname, mediastr, unit_id);
2300     bdrv = bdrv_new(buf);
2301     drives_table[nb_drives].bdrv = bdrv;
2302     drives_table[nb_drives].type = type;
2303     drives_table[nb_drives].bus = bus_id;
2304     drives_table[nb_drives].unit = unit_id;
2305     nb_drives++;
2306
2307     switch(type) {
2308     case IF_IDE:
2309     case IF_SCSI:
2310         switch(media) {
2311         case MEDIA_DISK:
2312             if (cyls != 0) {
2313                 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2314                 bdrv_set_translation_hint(bdrv, translation);
2315             }
2316             break;
2317         case MEDIA_CDROM:
2318             bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2319             break;
2320         }
2321         break;
2322     case IF_SD:
2323         /* FIXME: This isn't really a floppy, but it's a reasonable
2324            approximation.  */
2325     case IF_FLOPPY:
2326         bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2327         break;
2328     case IF_PFLASH:
2329     case IF_MTD:
2330         break;
2331     }
2332     if (!file[0])
2333         return 0;
2334     bdrv_flags = 0;
2335     if (snapshot) {
2336         bdrv_flags |= BDRV_O_SNAPSHOT;
2337         cache = 2; /* always use write-back with snapshot */
2338     }
2339     if (cache == 0) /* no caching */
2340         bdrv_flags |= BDRV_O_NOCACHE;
2341     else if (cache == 2) /* write-back */
2342         bdrv_flags |= BDRV_O_CACHE_WB;
2343     if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2344         fprintf(stderr, "qemu: could not open disk image %s\n",
2345                         file);
2346         return -1;
2347     }
2348     return 0;
2349 }
2350
2351 /***********************************************************/
2352 /* USB devices */
2353
2354 static USBPort *used_usb_ports;
2355 static USBPort *free_usb_ports;
2356
2357 /* ??? Maybe change this to register a hub to keep track of the topology.  */
2358 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2359                             usb_attachfn attach)
2360 {
2361     port->opaque = opaque;
2362     port->index = index;
2363     port->attach = attach;
2364     port->next = free_usb_ports;
2365     free_usb_ports = port;
2366 }
2367
2368 int usb_device_add_dev(USBDevice *dev)
2369 {
2370     USBPort *port;
2371
2372     /* Find a USB port to add the device to.  */
2373     port = free_usb_ports;
2374     if (!port->next) {
2375         USBDevice *hub;
2376
2377         /* Create a new hub and chain it on.  */
2378         free_usb_ports = NULL;
2379         port->next = used_usb_ports;
2380         used_usb_ports = port;
2381
2382         hub = usb_hub_init(VM_USB_HUB_SIZE);
2383         usb_attach(port, hub);
2384         port = free_usb_ports;
2385     }
2386
2387     free_usb_ports = port->next;
2388     port->next = used_usb_ports;
2389     used_usb_ports = port;
2390     usb_attach(port, dev);
2391     return 0;
2392 }
2393
2394 static int usb_device_add(const char *devname)
2395 {
2396     const char *p;
2397     USBDevice *dev;
2398
2399     if (!free_usb_ports)
2400         return -1;
2401
2402     if (strstart(devname, "host:", &p)) {
2403         dev = usb_host_device_open(p);
2404     } else if (!strcmp(devname, "mouse")) {
2405         dev = usb_mouse_init();
2406     } else if (!strcmp(devname, "tablet")) {
2407         dev = usb_tablet_init();
2408     } else if (!strcmp(devname, "keyboard")) {
2409         dev = usb_keyboard_init();
2410     } else if (strstart(devname, "disk:", &p)) {
2411         dev = usb_msd_init(p);
2412     } else if (!strcmp(devname, "wacom-tablet")) {
2413         dev = usb_wacom_init();
2414     } else if (strstart(devname, "serial:", &p)) {
2415         dev = usb_serial_init(p);
2416 #ifdef CONFIG_BRLAPI
2417     } else if (!strcmp(devname, "braille")) {
2418         dev = usb_baum_init();
2419 #endif
2420     } else if (strstart(devname, "net:", &p)) {
2421         int nic = nb_nics;
2422
2423         if (net_client_init("nic", p) < 0)
2424             return -1;
2425         nd_table[nic].model = "usb";
2426         dev = usb_net_init(&nd_table[nic]);
2427     } else {
2428         return -1;
2429     }
2430     if (!dev)
2431         return -1;
2432
2433     return usb_device_add_dev(dev);
2434 }
2435
2436 int usb_device_del_addr(int bus_num, int addr)
2437 {
2438     USBPort *port;
2439     USBPort **lastp;
2440     USBDevice *dev;
2441
2442     if (!used_usb_ports)
2443         return -1;
2444
2445     if (bus_num != 0)
2446         return -1;
2447
2448     lastp = &used_usb_ports;
2449     port = used_usb_ports;
2450     while (port && port->dev->addr != addr) {
2451         lastp = &port->next;
2452         port = port->next;
2453     }
2454
2455     if (!port)
2456         return -1;
2457
2458     dev = port->dev;
2459     *lastp = port->next;
2460     usb_attach(port, NULL);
2461     dev->handle_destroy(dev);
2462     port->next = free_usb_ports;
2463     free_usb_ports = port;
2464     return 0;
2465 }
2466
2467 static int usb_device_del(const char *devname)
2468 {
2469     int bus_num, addr;
2470     const char *p;
2471
2472     if (strstart(devname, "host:", &p))
2473         return usb_host_device_close(p);
2474
2475     if (!used_usb_ports)
2476         return -1;
2477
2478     p = strchr(devname, '.');
2479     if (!p)
2480         return -1;
2481     bus_num = strtoul(devname, NULL, 0);
2482     addr = strtoul(p + 1, NULL, 0);
2483
2484     return usb_device_del_addr(bus_num, addr);
2485 }
2486
2487 void do_usb_add(const char *devname)
2488 {
2489     usb_device_add(devname);
2490 }
2491
2492 void do_usb_del(const char *devname)
2493 {
2494     usb_device_del(devname);
2495 }
2496
2497 void usb_info(void)
2498 {
2499     USBDevice *dev;
2500     USBPort *port;
2501     const char *speed_str;
2502
2503     if (!usb_enabled) {
2504         term_printf("USB support not enabled\n");
2505         return;
2506     }
2507
2508     for (port = used_usb_ports; port; port = port->next) {
2509         dev = port->dev;
2510         if (!dev)
2511             continue;
2512         switch(dev->speed) {
2513         case USB_SPEED_LOW:
2514             speed_str = "1.5";
2515             break;
2516         case USB_SPEED_FULL:
2517             speed_str = "12";
2518             break;
2519         case USB_SPEED_HIGH:
2520             speed_str = "480";
2521             break;
2522         default:
2523             speed_str = "?";
2524             break;
2525         }
2526         term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
2527                     0, dev->addr, speed_str, dev->devname);
2528     }
2529 }
2530
2531 /***********************************************************/
2532 /* PCMCIA/Cardbus */
2533
2534 static struct pcmcia_socket_entry_s {
2535     struct pcmcia_socket_s *socket;
2536     struct pcmcia_socket_entry_s *next;
2537 } *pcmcia_sockets = 0;
2538
2539 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2540 {
2541     struct pcmcia_socket_entry_s *entry;
2542
2543     entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2544     entry->socket = socket;
2545     entry->next = pcmcia_sockets;
2546     pcmcia_sockets = entry;
2547 }
2548
2549 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2550 {
2551     struct pcmcia_socket_entry_s *entry, **ptr;
2552
2553     ptr = &pcmcia_sockets;
2554     for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2555         if (entry->socket == socket) {
2556             *ptr = entry->next;
2557             qemu_free(entry);
2558         }
2559 }
2560
2561 void pcmcia_info(void)
2562 {
2563     struct pcmcia_socket_entry_s *iter;
2564     if (!pcmcia_sockets)
2565         term_printf("No PCMCIA sockets\n");
2566
2567     for (iter = pcmcia_sockets; iter; iter = iter->next)
2568         term_printf("%s: %s\n", iter->socket->slot_string,
2569                     iter->socket->attached ? iter->socket->card_string :
2570                     "Empty");
2571 }
2572
2573 /***********************************************************/
2574 /* dumb display */
2575
2576 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2577 {
2578 }
2579
2580 static void dumb_resize(DisplayState *ds, int w, int h)
2581 {
2582 }
2583
2584 static void dumb_display_init(DisplayState *ds)
2585 {
2586     ds->data = NULL;
2587     ds->linesize = 0;
2588     ds->depth = 0;
2589     ds->dpy_update = dumb_update;
2590     ds->dpy_resize = dumb_resize;
2591     ds->dpy_refresh = NULL;
2592     ds->gui_timer_interval = 0;
2593     ds->idle = 1;
2594 }
2595
2596 /***********************************************************/
2597 /* I/O handling */
2598
2599 #define MAX_IO_HANDLERS 64
2600
2601 typedef struct IOHandlerRecord {
2602     int fd;
2603     IOCanRWHandler *fd_read_poll;
2604     IOHandler *fd_read;
2605     IOHandler *fd_write;
2606     int deleted;
2607     void *opaque;
2608     /* temporary data */
2609     struct pollfd *ufd;
2610     struct IOHandlerRecord *next;
2611 } IOHandlerRecord;
2612
2613 static IOHandlerRecord *first_io_handler;
2614
2615 /* XXX: fd_read_poll should be suppressed, but an API change is
2616    necessary in the character devices to suppress fd_can_read(). */
2617 int qemu_set_fd_handler2(int fd,
2618                          IOCanRWHandler *fd_read_poll,
2619                          IOHandler *fd_read,
2620                          IOHandler *fd_write,
2621                          void *opaque)
2622 {
2623     IOHandlerRecord **pioh, *ioh;
2624
2625     if (!fd_read && !fd_write) {
2626         pioh = &first_io_handler;
2627         for(;;) {
2628             ioh = *pioh;
2629             if (ioh == NULL)
2630                 break;
2631             if (ioh->fd == fd) {
2632                 ioh->deleted = 1;
2633                 break;
2634             }
2635             pioh = &ioh->next;
2636         }
2637     } else {
2638         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2639             if (ioh->fd == fd)
2640                 goto found;
2641         }
2642         ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2643         if (!ioh)
2644             return -1;
2645         ioh->next = first_io_handler;
2646         first_io_handler = ioh;
2647     found:
2648         ioh->fd = fd;
2649         ioh->fd_read_poll = fd_read_poll;
2650         ioh->fd_read = fd_read;
2651         ioh->fd_write = fd_write;
2652         ioh->opaque = opaque;
2653         ioh->deleted = 0;
2654     }
2655     return 0;
2656 }
2657
2658 int qemu_set_fd_handler(int fd,
2659                         IOHandler *fd_read,
2660                         IOHandler *fd_write,
2661                         void *opaque)
2662 {
2663     return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2664 }
2665
2666 #ifdef _WIN32
2667 /***********************************************************/
2668 /* Polling handling */
2669
2670 typedef struct PollingEntry {
2671     PollingFunc *func;
2672     void *opaque;
2673     struct PollingEntry *next;
2674 } PollingEntry;
2675
2676 static PollingEntry *first_polling_entry;
2677
2678 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2679 {
2680     PollingEntry **ppe, *pe;
2681     pe = qemu_mallocz(sizeof(PollingEntry));
2682     if (!pe)
2683         return -1;
2684     pe->func = func;
2685     pe->opaque = opaque;
2686     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2687     *ppe = pe;
2688     return 0;
2689 }
2690
2691 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2692 {
2693     PollingEntry **ppe, *pe;
2694     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2695         pe = *ppe;
2696         if (pe->func == func && pe->opaque == opaque) {
2697             *ppe = pe->next;
2698             qemu_free(pe);
2699             break;
2700         }
2701     }
2702 }
2703
2704 /***********************************************************/
2705 /* Wait objects support */
2706 typedef struct WaitObjects {
2707     int num;
2708     HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2709     WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2710     void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2711 } WaitObjects;
2712
2713 static WaitObjects wait_objects = {0};
2714
2715 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2716 {
2717     WaitObjects *w = &wait_objects;
2718
2719     if (w->num >= MAXIMUM_WAIT_OBJECTS)
2720         return -1;
2721     w->events[w->num] = handle;
2722     w->func[w->num] = func;
2723     w->opaque[w->num] = opaque;
2724     w->num++;
2725     return 0;
2726 }
2727
2728 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2729 {
2730     int i, found;
2731     WaitObjects *w = &wait_objects;
2732
2733     found = 0;
2734     for (i = 0; i < w->num; i++) {
2735         if (w->events[i] == handle)
2736             found = 1;
2737         if (found) {
2738             w->events[i] = w->events[i + 1];
2739             w->func[i] = w->func[i + 1];
2740             w->opaque[i] = w->opaque[i + 1];
2741         }
2742     }
2743     if (found)
2744         w->num--;
2745 }
2746 #endif
2747
2748 #define SELF_ANNOUNCE_ROUNDS 5
2749 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
2750 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
2751 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
2752
2753 static int announce_self_create(uint8_t *buf, 
2754                                 uint8_t *mac_addr)
2755 {
2756     uint32_t magic = EXPERIMENTAL_MAGIC;
2757     uint16_t proto = htons(ETH_P_EXPERIMENTAL);
2758
2759     /* FIXME: should we send a different packet (arp/rarp/ping)? */
2760
2761     memset(buf, 0xff, 6);         /* h_dst */
2762     memcpy(buf + 6, mac_addr, 6); /* h_src */
2763     memcpy(buf + 12, &proto, 2);  /* h_proto */
2764     memcpy(buf + 14, &magic, 4);  /* magic */
2765
2766     return 18; /* len */
2767 }
2768
2769 void qemu_announce_self(void)
2770 {
2771     int i, j, len;
2772     VLANState *vlan;
2773     VLANClientState *vc;
2774     uint8_t buf[256];
2775
2776     for (i = 0; i < nb_nics; i++) {
2777         len = announce_self_create(buf, nd_table[i].macaddr);
2778         vlan = nd_table[i].vlan;
2779         for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2780             for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
2781                 vc->fd_read(vc->opaque, buf, len);
2782         }
2783     }
2784 }
2785
2786 /***********************************************************/
2787 /* savevm/loadvm support */
2788
2789 #define IO_BUF_SIZE 32768
2790
2791 struct QEMUFile {
2792     QEMUFilePutBufferFunc *put_buffer;
2793     QEMUFileGetBufferFunc *get_buffer;
2794     QEMUFileCloseFunc *close;
2795     QEMUFileRateLimit *rate_limit;
2796     void *opaque;
2797     int is_write;
2798
2799     int64_t buf_offset; /* start of buffer when writing, end of buffer
2800                            when reading */
2801     int buf_index;
2802     int buf_size; /* 0 when writing */
2803     uint8_t buf[IO_BUF_SIZE];
2804
2805     int has_error;
2806 };
2807
2808 typedef struct QEMUFileSocket
2809 {
2810     int fd;
2811     QEMUFile *file;
2812 } QEMUFileSocket;
2813
2814 static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2815 {
2816     QEMUFileSocket *s = opaque;
2817     ssize_t len;
2818
2819     do {
2820         len = recv(s->fd, buf, size, 0);
2821     } while (len == -1 && socket_error() == EINTR);
2822
2823     if (len == -1)
2824         len = -socket_error();
2825
2826     return len;
2827 }
2828
2829 static int socket_close(void *opaque)
2830 {
2831     QEMUFileSocket *s = opaque;
2832     qemu_free(s);
2833     return 0;
2834 }
2835
2836 QEMUFile *qemu_fopen_socket(int fd)
2837 {
2838     QEMUFileSocket *s = qemu_mallocz(sizeof(QEMUFileSocket));
2839
2840     if (s == NULL)
2841         return NULL;
2842
2843     s->fd = fd;
2844     s->file = qemu_fopen_ops(s, NULL, socket_get_buffer, socket_close, NULL);
2845     return s->file;
2846 }
2847
2848 typedef struct QEMUFileStdio
2849 {
2850     FILE *outfile;
2851 } QEMUFileStdio;
2852
2853 static int file_put_buffer(void *opaque, const uint8_t *buf,
2854                             int64_t pos, int size)
2855 {
2856     QEMUFileStdio *s = opaque;
2857     fseek(s->outfile, pos, SEEK_SET);
2858     fwrite(buf, 1, size, s->outfile);
2859     return size;
2860 }
2861
2862 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2863 {
2864     QEMUFileStdio *s = opaque;
2865     fseek(s->outfile, pos, SEEK_SET);
2866     return fread(buf, 1, size, s->outfile);
2867 }
2868
2869 static int file_close(void *opaque)
2870 {
2871     QEMUFileStdio *s = opaque;
2872     fclose(s->outfile);
2873     qemu_free(s);
2874     return 0;
2875 }
2876
2877 QEMUFile *qemu_fopen(const char *filename, const char *mode)
2878 {
2879     QEMUFileStdio *s;
2880
2881     s = qemu_mallocz(sizeof(QEMUFileStdio));
2882     if (!s)
2883         return NULL;
2884
2885     s->outfile = fopen(filename, mode);
2886     if (!s->outfile)
2887         goto fail;
2888
2889     if (!strcmp(mode, "wb"))
2890         return qemu_fopen_ops(s, file_put_buffer, NULL, file_close, NULL);
2891     else if (!strcmp(mode, "rb"))
2892         return qemu_fopen_ops(s, NULL, file_get_buffer, file_close, NULL);
2893
2894 fail:
2895     if (s->outfile)
2896         fclose(s->outfile);
2897     qemu_free(s);
2898     return NULL;
2899 }
2900
2901 typedef struct QEMUFileBdrv
2902 {
2903     BlockDriverState *bs;
2904     int64_t base_offset;
2905 } QEMUFileBdrv;
2906
2907 static int bdrv_put_buffer(void *opaque, const uint8_t *buf,
2908                            int64_t pos, int size)
2909 {
2910     QEMUFileBdrv *s = opaque;
2911     bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
2912     return size;
2913 }
2914
2915 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2916 {
2917     QEMUFileBdrv *s = opaque;
2918     return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
2919 }
2920
2921 static int bdrv_fclose(void *opaque)
2922 {
2923     QEMUFileBdrv *s = opaque;
2924     qemu_free(s);
2925     return 0;
2926 }
2927
2928 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
2929 {
2930     QEMUFileBdrv *s;
2931
2932     s = qemu_mallocz(sizeof(QEMUFileBdrv));
2933     if (!s)
2934         return NULL;
2935
2936     s->bs = bs;
2937     s->base_offset = offset;
2938
2939     if (is_writable)
2940         return qemu_fopen_ops(s, bdrv_put_buffer, NULL, bdrv_fclose, NULL);
2941
2942     return qemu_fopen_ops(s, NULL, bdrv_get_buffer, bdrv_fclose, NULL);
2943 }
2944
2945 QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
2946                          QEMUFileGetBufferFunc *get_buffer,
2947                          QEMUFileCloseFunc *close,
2948                          QEMUFileRateLimit *rate_limit)
2949 {
2950     QEMUFile *f;
2951
2952     f = qemu_mallocz(sizeof(QEMUFile));
2953     if (!f)
2954         return NULL;
2955
2956     f->opaque = opaque;
2957     f->put_buffer = put_buffer;
2958     f->get_buffer = get_buffer;
2959     f->close = close;
2960     f->rate_limit = rate_limit;
2961     f->is_write = 0;
2962
2963     return f;
2964 }
2965
2966 int qemu_file_has_error(QEMUFile *f)
2967 {
2968     return f->has_error;
2969 }
2970
2971 void qemu_fflush(QEMUFile *f)
2972 {
2973     if (!f->put_buffer)
2974         return;
2975
2976     if (f->is_write && f->buf_index > 0) {
2977         int len;
2978
2979         len = f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
2980         if (len > 0)
2981             f->buf_offset += f->buf_index;
2982         else
2983             f->has_error = 1;
2984         f->buf_index = 0;
2985     }
2986 }
2987
2988 static void qemu_fill_buffer(QEMUFile *f)
2989 {
2990     int len;
2991
2992     if (!f->get_buffer)
2993         return;
2994
2995     if (f->is_write)
2996         abort();
2997
2998     len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
2999     if (len > 0) {
3000         f->buf_index = 0;
3001         f->buf_size = len;
3002         f->buf_offset += len;
3003     } else if (len != -EAGAIN)
3004         f->has_error = 1;
3005 }
3006
3007 int qemu_fclose(QEMUFile *f)
3008 {
3009     int ret = 0;
3010     qemu_fflush(f);
3011     if (f->close)
3012         ret = f->close(f->opaque);
3013     qemu_free(f);
3014     return ret;
3015 }
3016
3017 void qemu_file_put_notify(QEMUFile *f)
3018 {
3019     f->put_buffer(f->opaque, NULL, 0, 0);
3020 }
3021
3022 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3023 {
3024     int l;
3025
3026     if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
3027         fprintf(stderr,
3028                 "Attempted to write to buffer while read buffer is not empty\n");
3029         abort();
3030     }
3031
3032     while (!f->has_error && size > 0) {
3033         l = IO_BUF_SIZE - f->buf_index;
3034         if (l > size)
3035             l = size;
3036         memcpy(f->buf + f->buf_index, buf, l);
3037         f->is_write = 1;
3038         f->buf_index += l;
3039         buf += l;
3040         size -= l;
3041         if (f->buf_index >= IO_BUF_SIZE)
3042             qemu_fflush(f);
3043     }
3044 }
3045
3046 void qemu_put_byte(QEMUFile *f, int v)
3047 {
3048     if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
3049         fprintf(stderr,
3050                 "Attempted to write to buffer while read buffer is not empty\n");
3051         abort();
3052     }
3053
3054     f->buf[f->buf_index++] = v;
3055     f->is_write = 1;
3056     if (f->buf_index >= IO_BUF_SIZE)
3057         qemu_fflush(f);
3058 }
3059
3060 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
3061 {
3062     int size, l;
3063
3064     if (f->is_write)
3065         abort();
3066
3067     size = size1;
3068     while (size > 0) {
3069         l = f->buf_size - f->buf_index;
3070         if (l == 0) {
3071             qemu_fill_buffer(f);
3072             l = f->buf_size - f->buf_index;
3073             if (l == 0)
3074                 break;
3075         }
3076         if (l > size)
3077             l = size;
3078         memcpy(buf, f->buf + f->buf_index, l);
3079         f->buf_index += l;
3080         buf += l;
3081         size -= l;
3082     }
3083     return size1 - size;
3084 }
3085
3086 int qemu_get_byte(QEMUFile *f)
3087 {
3088     if (f->is_write)
3089         abort();
3090
3091     if (f->buf_index >= f->buf_size) {
3092         qemu_fill_buffer(f);
3093         if (f->buf_index >= f->buf_size)
3094             return 0;
3095     }
3096     return f->buf[f->buf_index++];
3097 }
3098
3099 int64_t qemu_ftell(QEMUFile *f)
3100 {
3101     return f->buf_offset - f->buf_size + f->buf_index;
3102 }
3103
3104 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3105 {
3106     if (whence == SEEK_SET) {
3107         /* nothing to do */
3108     } else if (whence == SEEK_CUR) {
3109         pos += qemu_ftell(f);
3110     } else {
3111         /* SEEK_END not supported */
3112         return -1;
3113     }
3114     if (f->put_buffer) {
3115         qemu_fflush(f);
3116         f->buf_offset = pos;
3117     } else {
3118         f->buf_offset = pos;
3119         f->buf_index = 0;
3120         f->buf_size = 0;
3121     }
3122     return pos;
3123 }
3124
3125 int qemu_file_rate_limit(QEMUFile *f)
3126 {
3127     if (f->rate_limit)
3128         return f->rate_limit(f->opaque);
3129
3130     return 0;
3131 }
3132
3133 void qemu_put_be16(QEMUFile *f, unsigned int v)
3134 {
3135     qemu_put_byte(f, v >> 8);
3136     qemu_put_byte(f, v);
3137 }
3138
3139 void qemu_put_be32(QEMUFile *f, unsigned int v)
3140 {
3141     qemu_put_byte(f, v >> 24);
3142     qemu_put_byte(f, v >> 16);
3143     qemu_put_byte(f, v >> 8);
3144     qemu_put_byte(f, v);
3145 }
3146
3147 void qemu_put_be64(QEMUFile *f, uint64_t v)
3148 {
3149     qemu_put_be32(f, v >> 32);
3150     qemu_put_be32(f, v);
3151 }
3152
3153 unsigned int qemu_get_be16(QEMUFile *f)
3154 {
3155     unsigned int v;
3156     v = qemu_get_byte(f) << 8;
3157     v |= qemu_get_byte(f);
3158     return v;
3159 }
3160
3161 unsigned int qemu_get_be32(QEMUFile *f)
3162 {
3163     unsigned int v;
3164     v = qemu_get_byte(f) << 24;
3165     v |= qemu_get_byte(f) << 16;
3166     v |= qemu_get_byte(f) << 8;
3167     v |= qemu_get_byte(f);
3168     return v;
3169 }
3170
3171 uint64_t qemu_get_be64(QEMUFile *f)
3172 {
3173     uint64_t v;
3174     v = (uint64_t)qemu_get_be32(f) << 32;
3175     v |= qemu_get_be32(f);
3176     return v;
3177 }
3178
3179 typedef struct SaveStateEntry {
3180     char idstr[256];
3181     int instance_id;
3182     int version_id;
3183     int section_id;
3184     SaveLiveStateHandler *save_live_state;
3185     SaveStateHandler *save_state;
3186     LoadStateHandler *load_state;
3187     void *opaque;
3188     struct SaveStateEntry *next;
3189 } SaveStateEntry;
3190
3191 static SaveStateEntry *first_se;
3192
3193 /* TODO: Individual devices generally have very little idea about the rest
3194    of the system, so instance_id should be removed/replaced.
3195    Meanwhile pass -1 as instance_id if you do not already have a clearly
3196    distinguishing id for all instances of your device class. */
3197 int register_savevm_live(const char *idstr,
3198                          int instance_id,
3199                          int version_id,
3200                          SaveLiveStateHandler *save_live_state,
3201                          SaveStateHandler *save_state,
3202                          LoadStateHandler *load_state,
3203                          void *opaque)
3204 {
3205     SaveStateEntry *se, **pse;
3206     static int global_section_id;
3207
3208     se = qemu_malloc(sizeof(SaveStateEntry));
3209     if (!se)
3210         return -1;
3211     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3212     se->instance_id = (instance_id == -1) ? 0 : instance_id;
3213     se->version_id = version_id;
3214     se->section_id = global_section_id++;
3215     se->save_live_state = save_live_state;
3216     se->save_state = save_state;
3217     se->load_state = load_state;
3218     se->opaque = opaque;
3219     se->next = NULL;
3220
3221     /* add at the end of list */
3222     pse = &first_se;
3223     while (*pse != NULL) {
3224         if (instance_id == -1
3225                 && strcmp(se->idstr, (*pse)->idstr) == 0
3226                 && se->instance_id <= (*pse)->instance_id)
3227             se->instance_id = (*pse)->instance_id + 1;
3228         pse = &(*pse)->next;
3229     }
3230     *pse = se;
3231     return 0;
3232 }
3233
3234 int register_savevm(const char *idstr,
3235                     int instance_id,
3236                     int version_id,
3237                     SaveStateHandler *save_state,
3238                     LoadStateHandler *load_state,
3239                     void *opaque)
3240 {
3241     return register_savevm_live(idstr, instance_id, version_id,
3242                                 NULL, save_state, load_state, opaque);
3243 }
3244
3245 #define QEMU_VM_FILE_MAGIC           0x5145564d
3246 #define QEMU_VM_FILE_VERSION_COMPAT  0x00000002
3247 #define QEMU_VM_FILE_VERSION         0x00000003
3248
3249 #define QEMU_VM_EOF                  0x00
3250 #define QEMU_VM_SECTION_START        0x01
3251 #define QEMU_VM_SECTION_PART         0x02
3252 #define QEMU_VM_SECTION_END          0x03
3253 #define QEMU_VM_SECTION_FULL         0x04
3254
3255 int qemu_savevm_state_begin(QEMUFile *f)
3256 {
3257     SaveStateEntry *se;
3258
3259     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3260     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3261
3262     for (se = first_se; se != NULL; se = se->next) {
3263         int len;
3264
3265         if (se->save_live_state == NULL)
3266             continue;
3267
3268         /* Section type */
3269         qemu_put_byte(f, QEMU_VM_SECTION_START);
3270         qemu_put_be32(f, se->section_id);
3271
3272         /* ID string */
3273         len = strlen(se->idstr);
3274         qemu_put_byte(f, len);
3275         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3276
3277         qemu_put_be32(f, se->instance_id);
3278         qemu_put_be32(f, se->version_id);
3279
3280         se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
3281     }
3282
3283     if (qemu_file_has_error(f))
3284         return -EIO;
3285
3286     return 0;
3287 }
3288
3289 int qemu_savevm_state_iterate(QEMUFile *f)
3290 {
3291     SaveStateEntry *se;
3292     int ret = 1;
3293
3294     for (se = first_se; se != NULL; se = se->next) {
3295         if (se->save_live_state == NULL)
3296             continue;
3297
3298         /* Section type */
3299         qemu_put_byte(f, QEMU_VM_SECTION_PART);
3300         qemu_put_be32(f, se->section_id);
3301
3302         ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
3303     }
3304
3305     if (ret)
3306         return 1;
3307
3308     if (qemu_file_has_error(f))
3309         return -EIO;
3310
3311     return 0;
3312 }
3313
3314 int qemu_savevm_state_complete(QEMUFile *f)
3315 {
3316     SaveStateEntry *se;
3317
3318     for (se = first_se; se != NULL; se = se->next) {
3319         if (se->save_live_state == NULL)
3320             continue;
3321
3322         /* Section type */
3323         qemu_put_byte(f, QEMU_VM_SECTION_END);
3324         qemu_put_be32(f, se->section_id);
3325
3326         se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
3327     }
3328
3329     for(se = first_se; se != NULL; se = se->next) {
3330         int len;
3331
3332         if (se->save_state == NULL)
3333             continue;
3334
3335         /* Section type */
3336         qemu_put_byte(f, QEMU_VM_SECTION_FULL);
3337         qemu_put_be32(f, se->section_id);
3338
3339         /* ID string */
3340         len = strlen(se->idstr);
3341         qemu_put_byte(f, len);
3342         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3343
3344         qemu_put_be32(f, se->instance_id);
3345         qemu_put_be32(f, se->version_id);
3346
3347         se->save_state(f, se->opaque);
3348     }
3349
3350     qemu_put_byte(f, QEMU_VM_EOF);
3351
3352     if (qemu_file_has_error(f))
3353         return -EIO;
3354
3355     return 0;
3356 }
3357
3358 int qemu_savevm_state(QEMUFile *f)
3359 {
3360     int saved_vm_running;
3361     int ret;
3362
3363     saved_vm_running = vm_running;
3364     vm_stop(0);
3365
3366     bdrv_flush_all();
3367
3368     ret = qemu_savevm_state_begin(f);
3369     if (ret < 0)
3370         goto out;
3371
3372     do {
3373         ret = qemu_savevm_state_iterate(f);
3374         if (ret < 0)
3375             goto out;
3376     } while (ret == 0);
3377
3378     ret = qemu_savevm_state_complete(f);
3379
3380 out:
3381     if (qemu_file_has_error(f))
3382         ret = -EIO;
3383
3384     if (!ret && saved_vm_running)
3385         vm_start();
3386
3387     return ret;
3388 }
3389
3390 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3391 {
3392     SaveStateEntry *se;
3393
3394     for(se = first_se; se != NULL; se = se->next) {
3395         if (!strcmp(se->idstr, idstr) &&
3396             instance_id == se->instance_id)
3397             return se;
3398     }
3399     return NULL;
3400 }
3401
3402 typedef struct LoadStateEntry {
3403     SaveStateEntry *se;
3404     int section_id;
3405     int version_id;
3406     struct LoadStateEntry *next;
3407 } LoadStateEntry;
3408
3409 static int qemu_loadvm_state_v2(QEMUFile *f)
3410 {
3411     SaveStateEntry *se;
3412     int len, ret, instance_id, record_len, version_id;
3413     int64_t total_len, end_pos, cur_pos;
3414     char idstr[256];
3415
3416     total_len = qemu_get_be64(f);
3417     end_pos = total_len + qemu_ftell(f);
3418     for(;;) {
3419         if (qemu_ftell(f) >= end_pos)
3420             break;
3421         len = qemu_get_byte(f);
3422         qemu_get_buffer(f, (uint8_t *)idstr, len);
3423         idstr[len] = '\0';
3424         instance_id = qemu_get_be32(f);
3425         version_id = qemu_get_be32(f);
3426         record_len = qemu_get_be32(f);
3427         cur_pos = qemu_ftell(f);
3428         se = find_se(idstr, instance_id);
3429         if (!se) {
3430             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3431                     instance_id, idstr);
3432         } else {
3433             ret = se->load_state(f, se->opaque, version_id);
3434             if (ret < 0) {
3435                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3436                         instance_id, idstr);
3437             }
3438         }
3439         /* always seek to exact end of record */
3440         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3441     }
3442
3443     if (qemu_file_has_error(f))
3444         return -EIO;
3445
3446     return 0;
3447 }
3448
3449 int qemu_loadvm_state(QEMUFile *f)
3450 {
3451     LoadStateEntry *first_le = NULL;
3452     uint8_t section_type;
3453     unsigned int v;
3454     int ret;
3455
3456     v = qemu_get_be32(f);
3457     if (v != QEMU_VM_FILE_MAGIC)
3458         return -EINVAL;
3459
3460     v = qemu_get_be32(f);
3461     if (v == QEMU_VM_FILE_VERSION_COMPAT)
3462         return qemu_loadvm_state_v2(f);
3463     if (v != QEMU_VM_FILE_VERSION)
3464         return -ENOTSUP;
3465
3466     while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
3467         uint32_t instance_id, version_id, section_id;
3468         LoadStateEntry *le;
3469         SaveStateEntry *se;
3470         char idstr[257];
3471         int len;
3472
3473         switch (section_type) {
3474         case QEMU_VM_SECTION_START:
3475         case QEMU_VM_SECTION_FULL:
3476             /* Read section start */
3477             section_id = qemu_get_be32(f);
3478             len = qemu_get_byte(f);
3479             qemu_get_buffer(f, (uint8_t *)idstr, len);
3480             idstr[len] = 0;
3481             instance_id = qemu_get_be32(f);
3482             version_id = qemu_get_be32(f);
3483
3484             /* Find savevm section */
3485             se = find_se(idstr, instance_id);
3486             if (se == NULL) {
3487                 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
3488                 ret = -EINVAL;
3489                 goto out;
3490             }
3491
3492             /* Validate version */
3493             if (version_id > se->version_id) {
3494                 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
3495                         version_id, idstr, se->version_id);
3496                 ret = -EINVAL;
3497                 goto out;
3498             }
3499
3500             /* Add entry */
3501             le = qemu_mallocz(sizeof(*le));
3502             if (le == NULL) {
3503                 ret = -ENOMEM;
3504                 goto out;
3505             }
3506
3507             le->se = se;
3508             le->section_id = section_id;
3509             le->version_id = version_id;
3510             le->next = first_le;
3511             first_le = le;
3512
3513             le->se->load_state(f, le->se->opaque, le->version_id);
3514             break;
3515         case QEMU_VM_SECTION_PART:
3516         case QEMU_VM_SECTION_END:
3517             section_id = qemu_get_be32(f);
3518
3519             for (le = first_le; le && le->section_id != section_id; le = le->next);
3520             if (le == NULL) {
3521                 fprintf(stderr, "Unknown savevm section %d\n", section_id);
3522                 ret = -EINVAL;
3523                 goto out;
3524             }
3525
3526             le->se->load_state(f, le->se->opaque, le->version_id);
3527             break;
3528         default:
3529             fprintf(stderr, "Unknown savevm section type %d\n", section_type);
3530             ret = -EINVAL;
3531             goto out;
3532         }
3533     }
3534
3535     ret = 0;
3536
3537 out:
3538     while (first_le) {
3539         LoadStateEntry *le = first_le;
3540         first_le = first_le->next;
3541         qemu_free(le);
3542     }
3543
3544     if (qemu_file_has_error(f))
3545         ret = -EIO;
3546
3547     return ret;
3548 }
3549
3550 /* device can contain snapshots */
3551 static int bdrv_can_snapshot(BlockDriverState *bs)
3552 {
3553     return (bs &&
3554             !bdrv_is_removable(bs) &&
3555             !bdrv_is_read_only(bs));
3556 }
3557
3558 /* device must be snapshots in order to have a reliable snapshot */
3559 static int bdrv_has_snapshot(BlockDriverState *bs)
3560 {
3561     return (bs &&
3562             !bdrv_is_removable(bs) &&
3563             !bdrv_is_read_only(bs));
3564 }
3565
3566 static BlockDriverState *get_bs_snapshots(void)
3567 {
3568     BlockDriverState *bs;
3569     int i;
3570
3571     if (bs_snapshots)
3572         return bs_snapshots;
3573     for(i = 0; i <= nb_drives; i++) {
3574         bs = drives_table[i].bdrv;
3575         if (bdrv_can_snapshot(bs))
3576             goto ok;
3577     }
3578     return NULL;
3579  ok:
3580     bs_snapshots = bs;
3581     return bs;
3582 }
3583
3584 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
3585                               const char *name)
3586 {
3587     QEMUSnapshotInfo *sn_tab, *sn;
3588     int nb_sns, i, ret;
3589
3590     ret = -ENOENT;
3591     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3592     if (nb_sns < 0)
3593         return ret;
3594     for(i = 0; i < nb_sns; i++) {
3595         sn = &sn_tab[i];
3596         if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
3597             *sn_info = *sn;
3598             ret = 0;
3599             break;
3600         }
3601     }
3602     qemu_free(sn_tab);
3603     return ret;
3604 }
3605
3606 void do_savevm(const char *name)
3607 {
3608     BlockDriverState *bs, *bs1;
3609     QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
3610     int must_delete, ret, i;
3611     BlockDriverInfo bdi1, *bdi = &bdi1;
3612     QEMUFile *f;
3613     int saved_vm_running;
3614 #ifdef _WIN32
3615     struct _timeb tb;
3616 #else
3617     struct timeval tv;
3618 #endif
3619
3620     bs = get_bs_snapshots();
3621     if (!bs) {
3622         term_printf("No block device can accept snapshots\n");
3623         return;
3624     }
3625
3626     /* ??? Should this occur after vm_stop?  */
3627     qemu_aio_flush();
3628
3629     saved_vm_running = vm_running;
3630     vm_stop(0);
3631
3632     must_delete = 0;
3633     if (name) {
3634         ret = bdrv_snapshot_find(bs, old_sn, name);
3635         if (ret >= 0) {
3636             must_delete = 1;
3637         }
3638     }
3639     memset(sn, 0, sizeof(*sn));
3640     if (must_delete) {
3641         pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
3642         pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
3643     } else {
3644         if (name)
3645             pstrcpy(sn->name, sizeof(sn->name), name);
3646     }
3647
3648     /* fill auxiliary fields */
3649 #ifdef _WIN32
3650     _ftime(&tb);
3651     sn->date_sec = tb.time;
3652     sn->date_nsec = tb.millitm * 1000000;
3653 #else
3654     gettimeofday(&tv, NULL);
3655     sn->date_sec = tv.tv_sec;
3656     sn->date_nsec = tv.tv_usec * 1000;
3657 #endif
3658     sn->vm_clock_nsec = qemu_get_clock(vm_clock);
3659
3660     if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3661         term_printf("Device %s does not support VM state snapshots\n",
3662                     bdrv_get_device_name(bs));
3663         goto the_end;
3664     }
3665
3666     /* save the VM state */
3667     f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
3668     if (!f) {
3669         term_printf("Could not open VM state file\n");
3670         goto the_end;
3671     }
3672     ret = qemu_savevm_state(f);
3673     sn->vm_state_size = qemu_ftell(f);
3674     qemu_fclose(f);
3675     if (ret < 0) {
3676         term_printf("Error %d while writing VM\n", ret);
3677         goto the_end;
3678     }
3679
3680     /* create the snapshots */
3681
3682     for(i = 0; i < nb_drives; i++) {
3683         bs1 = drives_table[i].bdrv;
3684         if (bdrv_has_snapshot(bs1)) {
3685             if (must_delete) {
3686                 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
3687                 if (ret < 0) {
3688                     term_printf("Error while deleting snapshot on '%s'\n",
3689                                 bdrv_get_device_name(bs1));
3690                 }
3691             }
3692             ret = bdrv_snapshot_create(bs1, sn);
3693             if (ret < 0) {
3694                 term_printf("Error while creating snapshot on '%s'\n",
3695                             bdrv_get_device_name(bs1));
3696             }
3697         }
3698     }
3699
3700  the_end:
3701     if (saved_vm_running)
3702         vm_start();
3703 }
3704
3705 void do_loadvm(const char *name)
3706 {
3707     BlockDriverState *bs, *bs1;
3708     BlockDriverInfo bdi1, *bdi = &bdi1;
3709     QEMUFile *f;
3710     int i, ret;
3711     int saved_vm_running;
3712
3713     bs = get_bs_snapshots();
3714     if (!bs) {
3715         term_printf("No block device supports snapshots\n");
3716         return;
3717     }
3718
3719     /* Flush all IO requests so they don't interfere with the new state.  */
3720     qemu_aio_flush();
3721
3722     saved_vm_running = vm_running;
3723     vm_stop(0);
3724
3725     for(i = 0; i <= nb_drives; i++) {
3726         bs1 = drives_table[i].bdrv;
3727         if (bdrv_has_snapshot(bs1)) {
3728             ret = bdrv_snapshot_goto(bs1, name);
3729             if (ret < 0) {
3730                 if (bs != bs1)
3731                     term_printf("Warning: ");
3732                 switch(ret) {
3733                 case -ENOTSUP:
3734                     term_printf("Snapshots not supported on device '%s'\n",
3735                                 bdrv_get_device_name(bs1));
3736                     break;
3737                 case -ENOENT:
3738                     term_printf("Could not find snapshot '%s' on device '%s'\n",
3739                                 name, bdrv_get_device_name(bs1));
3740                     break;
3741                 default:
3742                     term_printf("Error %d while activating snapshot on '%s'\n",
3743                                 ret, bdrv_get_device_name(bs1));
3744                     break;
3745                 }
3746                 /* fatal on snapshot block device */
3747                 if (bs == bs1)
3748                     goto the_end;
3749             }
3750         }
3751     }
3752
3753     if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3754         term_printf("Device %s does not support VM state snapshots\n",
3755                     bdrv_get_device_name(bs));
3756         return;
3757     }
3758
3759     /* restore the VM state */
3760     f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
3761     if (!f) {
3762         term_printf("Could not open VM state file\n");
3763         goto the_end;
3764     }
3765     ret = qemu_loadvm_state(f);
3766     qemu_fclose(f);
3767     if (ret < 0) {
3768         term_printf("Error %d while loading VM state\n", ret);
3769     }
3770  the_end:
3771     if (saved_vm_running)
3772         vm_start();
3773 }
3774
3775 void do_delvm(const char *name)
3776 {
3777     BlockDriverState *bs, *bs1;
3778     int i, ret;
3779
3780     bs = get_bs_snapshots();
3781     if (!bs) {
3782         term_printf("No block device supports snapshots\n");
3783         return;
3784     }
3785
3786     for(i = 0; i <= nb_drives; i++) {
3787         bs1 = drives_table[i].bdrv;
3788         if (bdrv_has_snapshot(bs1)) {
3789             ret = bdrv_snapshot_delete(bs1, name);
3790             if (ret < 0) {
3791                 if (ret == -ENOTSUP)
3792                     term_printf("Snapshots not supported on device '%s'\n",
3793                                 bdrv_get_device_name(bs1));
3794                 else
3795                     term_printf("Error %d while deleting snapshot on '%s'\n",
3796                                 ret, bdrv_get_device_name(bs1));
3797             }
3798         }
3799     }
3800 }
3801
3802 void do_info_snapshots(void)
3803 {
3804     BlockDriverState *bs, *bs1;
3805     QEMUSnapshotInfo *sn_tab, *sn;
3806     int nb_sns, i;
3807     char buf[256];
3808
3809     bs = get_bs_snapshots();
3810     if (!bs) {
3811         term_printf("No available block device supports snapshots\n");
3812         return;
3813     }
3814     term_printf("Snapshot devices:");
3815     for(i = 0; i <= nb_drives; i++) {
3816         bs1 = drives_table[i].bdrv;
3817         if (bdrv_has_snapshot(bs1)) {
3818             if (bs == bs1)
3819                 term_printf(" %s", bdrv_get_device_name(bs1));
3820         }
3821     }
3822     term_printf("\n");
3823
3824     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3825     if (nb_sns < 0) {
3826         term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
3827         return;
3828     }
3829     term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
3830     term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
3831     for(i = 0; i < nb_sns; i++) {
3832         sn = &sn_tab[i];
3833         term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
3834     }
3835     qemu_free(sn_tab);
3836 }
3837
3838 /***********************************************************/
3839 /* ram save/restore */
3840
3841 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3842 {
3843     int v;
3844
3845     v = qemu_get_byte(f);
3846     switch(v) {
3847     case 0:
3848         if (qemu_get_buffer(f, buf, len) != len)
3849             return -EIO;
3850         break;
3851     case 1:
3852         v = qemu_get_byte(f);
3853         memset(buf, v, len);
3854         break;
3855     default:
3856         return -EINVAL;
3857     }
3858
3859     if (qemu_file_has_error(f))
3860         return -EIO;
3861
3862     return 0;
3863 }
3864
3865 static int ram_load_v1(QEMUFile *f, void *opaque)
3866 {
3867     int ret;
3868     ram_addr_t i;
3869
3870     if (qemu_get_be32(f) != phys_ram_size)
3871         return -EINVAL;
3872     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3873         ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3874         if (ret)
3875             return ret;
3876     }
3877     return 0;
3878 }
3879
3880 #define BDRV_HASH_BLOCK_SIZE 1024
3881 #define IOBUF_SIZE 4096
3882 #define RAM_CBLOCK_MAGIC 0xfabe
3883
3884 typedef struct RamDecompressState {
3885     z_stream zstream;
3886     QEMUFile *f;
3887     uint8_t buf[IOBUF_SIZE];
3888 } RamDecompressState;
3889
3890 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3891 {
3892     int ret;
3893     memset(s, 0, sizeof(*s));
3894     s->f = f;
3895     ret = inflateInit(&s->zstream);
3896     if (ret != Z_OK)
3897         return -1;
3898     return 0;
3899 }
3900
3901 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3902 {
3903     int ret, clen;
3904
3905     s->zstream.avail_out = len;
3906     s->zstream.next_out = buf;
3907     while (s->zstream.avail_out > 0) {
3908         if (s->zstream.avail_in == 0) {
3909             if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3910                 return -1;
3911             clen = qemu_get_be16(s->f);
3912             if (clen > IOBUF_SIZE)
3913                 return -1;
3914             qemu_get_buffer(s->f, s->buf, clen);
3915             s->zstream.avail_in = clen;
3916             s->zstream.next_in = s->buf;
3917         }
3918         ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3919         if (ret != Z_OK && ret != Z_STREAM_END) {
3920             return -1;
3921         }
3922     }
3923     return 0;
3924 }
3925
3926 static void ram_decompress_close(RamDecompressState *s)
3927 {
3928     inflateEnd(&s->zstream);
3929 }
3930
3931 #define RAM_SAVE_FLAG_FULL      0x01
3932 #define RAM_SAVE_FLAG_COMPRESS  0x02
3933 #define RAM_SAVE_FLAG_MEM_SIZE  0x04
3934 #define RAM_SAVE_FLAG_PAGE      0x08
3935 #define RAM_SAVE_FLAG_EOS       0x10
3936
3937 static int is_dup_page(uint8_t *page, uint8_t ch)
3938 {
3939     uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3940     uint32_t *array = (uint32_t *)page;
3941     int i;
3942
3943     for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3944         if (array[i] != val)
3945             return 0;
3946     }
3947
3948     return 1;
3949 }
3950
3951 static int ram_save_block(QEMUFile *f)
3952 {
3953     static ram_addr_t current_addr = 0;
3954     ram_addr_t saved_addr = current_addr;
3955     ram_addr_t addr = 0;
3956     int found = 0;
3957
3958     while (addr < phys_ram_size) {
3959         if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3960             uint8_t ch;
3961
3962             cpu_physical_memory_reset_dirty(current_addr,
3963                                             current_addr + TARGET_PAGE_SIZE,
3964                                             MIGRATION_DIRTY_FLAG);
3965
3966             ch = *(phys_ram_base + current_addr);
3967
3968             if (is_dup_page(phys_ram_base + current_addr, ch)) {
3969                 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3970                 qemu_put_byte(f, ch);
3971             } else {
3972                 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3973                 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3974             }
3975
3976             found = 1;
3977             break;
3978         }
3979         addr += TARGET_PAGE_SIZE;
3980         current_addr = (saved_addr + addr) % phys_ram_size;
3981     }
3982
3983     return found;
3984 }
3985
3986 static ram_addr_t ram_save_threshold = 10;
3987
3988 static ram_addr_t ram_save_remaining(void)
3989 {
3990     ram_addr_t addr;
3991     ram_addr_t count = 0;
3992
3993     for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3994         if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3995             count++;
3996     }
3997
3998     return count;
3999 }
4000
4001 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
4002 {
4003     ram_addr_t addr;
4004
4005     if (stage == 1) {
4006         /* Make sure all dirty bits are set */
4007         for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
4008             if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
4009                 cpu_physical_memory_set_dirty(addr);
4010         }
4011         
4012         /* Enable dirty memory tracking */
4013         cpu_physical_memory_set_dirty_tracking(1);
4014
4015         qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
4016     }
4017
4018     while (!qemu_file_rate_limit(f)) {
4019         int ret;
4020
4021         ret = ram_save_block(f);
4022         if (ret == 0) /* no more blocks */
4023             break;
4024     }
4025
4026     /* try transferring iterative blocks of memory */
4027
4028     if (stage == 3) {
4029         cpu_physical_memory_set_dirty_tracking(0);
4030
4031         /* flush all remaining blocks regardless of rate limiting */
4032         while (ram_save_block(f) != 0);
4033     }
4034
4035     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
4036
4037     return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
4038 }
4039
4040 static int ram_load_dead(QEMUFile *f, void *opaque)
4041 {
4042     RamDecompressState s1, *s = &s1;
4043     uint8_t buf[10];
4044     ram_addr_t i;
4045
4046     if (ram_decompress_open(s, f) < 0)
4047         return -EINVAL;
4048     for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
4049         if (ram_decompress_buf(s, buf, 1) < 0) {
4050             fprintf(stderr, "Error while reading ram block header\n");
4051             goto error;
4052         }
4053         if (buf[0] == 0) {
4054             if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
4055                 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
4056                 goto error;
4057             }
4058         } else {
4059         error:
4060             printf("Error block header\n");
4061             return -EINVAL;
4062         }
4063     }
4064     ram_decompress_close(s);
4065
4066     return 0;
4067 }
4068
4069 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4070 {
4071     ram_addr_t addr;
4072     int flags;
4073
4074     if (version_id == 1)
4075         return ram_load_v1(f, opaque);
4076
4077     if (version_id == 2) {
4078         if (qemu_get_be32(f) != phys_ram_size)
4079             return -EINVAL;
4080         return ram_load_dead(f, opaque);
4081     }
4082
4083     if (version_id != 3)
4084         return -EINVAL;
4085
4086     do {
4087         addr = qemu_get_be64(f);
4088
4089         flags = addr & ~TARGET_PAGE_MASK;
4090         addr &= TARGET_PAGE_MASK;
4091
4092         if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
4093             if (addr != phys_ram_size)
4094                 return -EINVAL;
4095         }
4096
4097         if (flags & RAM_SAVE_FLAG_FULL) {
4098             if (ram_load_dead(f, opaque) < 0)
4099                 return -EINVAL;
4100         }
4101         
4102         if (flags & RAM_SAVE_FLAG_COMPRESS) {
4103             uint8_t ch = qemu_get_byte(f);
4104             memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
4105         } else if (flags & RAM_SAVE_FLAG_PAGE)
4106             qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
4107     } while (!(flags & RAM_SAVE_FLAG_EOS));
4108
4109     return 0;
4110 }
4111
4112 void qemu_service_io(void)
4113 {
4114     CPUState *env = cpu_single_env;
4115     if (env) {
4116         cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4117 #ifdef USE_KQEMU
4118         if (env->kqemu_enabled) {
4119             kqemu_cpu_interrupt(env);
4120         }
4121 #endif
4122     }
4123 }
4124
4125 /***********************************************************/
4126 /* bottom halves (can be seen as timers which expire ASAP) */
4127
4128 struct QEMUBH {
4129     QEMUBHFunc *cb;
4130     void *opaque;
4131     int scheduled;
4132     int idle;
4133     int deleted;
4134     QEMUBH *next;
4135 };
4136
4137 static QEMUBH *first_bh = NULL;
4138
4139 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
4140 {
4141     QEMUBH *bh;
4142     bh = qemu_mallocz(sizeof(QEMUBH));
4143     if (!bh)
4144         return NULL;
4145     bh->cb = cb;
4146     bh->opaque = opaque;
4147     bh->next = first_bh;
4148     first_bh = bh;
4149     return bh;
4150 }
4151
4152 int qemu_bh_poll(void)
4153 {
4154     QEMUBH *bh, **bhp;
4155     int ret;
4156
4157     ret = 0;
4158     for (bh = first_bh; bh; bh = bh->next) {
4159         if (!bh->deleted && bh->scheduled) {
4160             bh->scheduled = 0;
4161             if (!bh->idle)
4162                 ret = 1;
4163             bh->idle = 0;
4164             bh->cb(bh->opaque);
4165         }
4166     }
4167
4168     /* remove deleted bhs */
4169     bhp = &first_bh;
4170     while (*bhp) {
4171         bh = *bhp;
4172         if (bh->deleted) {
4173             *bhp = bh->next;
4174             qemu_free(bh);
4175         } else
4176             bhp = &bh->next;
4177     }
4178
4179     return ret;
4180 }
4181
4182 void qemu_bh_schedule_idle(QEMUBH *bh)
4183 {
4184     if (bh->scheduled)
4185         return;
4186     bh->scheduled = 1;
4187     bh->idle = 1;
4188 }
4189
4190 void qemu_bh_schedule(QEMUBH *bh)
4191 {
4192     CPUState *env = cpu_single_env;
4193     if (bh->scheduled)
4194         return;
4195     bh->scheduled = 1;
4196     bh->idle = 0;
4197     /* stop the currently executing CPU to execute the BH ASAP */
4198     if (env) {
4199         cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4200     }
4201 }
4202
4203 void qemu_bh_cancel(QEMUBH *bh)
4204 {
4205     bh->scheduled = 0;
4206 }
4207
4208 void qemu_bh_delete(QEMUBH *bh)
4209 {
4210     bh->scheduled = 0;
4211     bh->deleted = 1;
4212 }
4213
4214 static void qemu_bh_update_timeout(int *timeout)
4215 {
4216     QEMUBH *bh;
4217
4218     for (bh = first_bh; bh; bh = bh->next) {
4219         if (!bh->deleted && bh->scheduled) {
4220             if (bh->idle) {
4221                 /* idle bottom halves will be polled at least
4222                  * every 10ms */
4223                 *timeout = MIN(10, *timeout);
4224             } else {
4225                 /* non-idle bottom halves will be executed
4226                  * immediately */
4227                 *timeout = 0;
4228                 break;
4229             }
4230         }
4231     }
4232 }
4233
4234 /***********************************************************/
4235 /* machine registration */
4236
4237 static QEMUMachine *first_machine = NULL;
4238
4239 int qemu_register_machine(QEMUMachine *m)
4240 {
4241     QEMUMachine **pm;
4242     pm = &first_machine;
4243     while (*pm != NULL)
4244         pm = &(*pm)->next;
4245     m->next = NULL;
4246     *pm = m;
4247     return 0;
4248 }
4249
4250 static QEMUMachine *find_machine(const char *name)
4251 {
4252     QEMUMachine *m;
4253
4254     for(m = first_machine; m != NULL; m = m->next) {
4255         if (!strcmp(m->name, name))
4256             return m;
4257     }
4258     return NULL;
4259 }
4260
4261 /***********************************************************/
4262 /* main execution loop */
4263
4264 static void gui_update(void *opaque)
4265 {
4266     DisplayState *ds = opaque;
4267     ds->dpy_refresh(ds);
4268     qemu_mod_timer(ds->gui_timer,
4269         (ds->gui_timer_interval ?
4270             ds->gui_timer_interval :
4271             GUI_REFRESH_INTERVAL)
4272         + qemu_get_clock(rt_clock));
4273 }
4274
4275 struct vm_change_state_entry {
4276     VMChangeStateHandler *cb;
4277     void *opaque;
4278     LIST_ENTRY (vm_change_state_entry) entries;
4279 };
4280
4281 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4282
4283 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4284                                                      void *opaque)
4285 {
4286     VMChangeStateEntry *e;
4287
4288     e = qemu_mallocz(sizeof (*e));
4289     if (!e)
4290         return NULL;
4291
4292     e->cb = cb;
4293     e->opaque = opaque;
4294     LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4295     return e;
4296 }
4297
4298 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4299 {
4300     LIST_REMOVE (e, entries);
4301     qemu_free (e);
4302 }
4303
4304 static void vm_state_notify(int running)
4305 {
4306     VMChangeStateEntry *e;
4307
4308     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4309         e->cb(e->opaque, running);
4310     }
4311 }
4312
4313 /* XXX: support several handlers */
4314 static VMStopHandler *vm_stop_cb;
4315 static void *vm_stop_opaque;
4316
4317 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4318 {
4319     vm_stop_cb = cb;
4320     vm_stop_opaque = opaque;
4321     return 0;
4322 }
4323
4324 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4325 {
4326     vm_stop_cb = NULL;
4327 }
4328
4329 void vm_start(void)
4330 {
4331     if (!vm_running) {
4332         cpu_enable_ticks();
4333         vm_running = 1;
4334         vm_state_notify(1);
4335         qemu_rearm_alarm_timer(alarm_timer);
4336     }
4337 }
4338
4339 void vm_stop(int reason)
4340 {
4341     if (vm_running) {
4342         cpu_disable_ticks();
4343         vm_running = 0;
4344         if (reason != 0) {
4345             if (vm_stop_cb) {
4346                 vm_stop_cb(vm_stop_opaque, reason);
4347             }
4348         }
4349         vm_state_notify(0);
4350     }
4351 }
4352
4353 /* reset/shutdown handler */
4354
4355 typedef struct QEMUResetEntry {
4356     QEMUResetHandler *func;
4357     void *opaque;
4358     struct QEMUResetEntry *next;
4359 } QEMUResetEntry;
4360
4361 static QEMUResetEntry *first_reset_entry;
4362 static int reset_requested;
4363 static int shutdown_requested;
4364 static int powerdown_requested;
4365
4366 int qemu_shutdown_requested(void)
4367 {
4368     int r = shutdown_requested;
4369     shutdown_requested = 0;
4370     return r;
4371 }
4372
4373 int qemu_reset_requested(void)
4374 {
4375     int r = reset_requested;
4376     reset_requested = 0;
4377     return r;
4378 }
4379
4380 int qemu_powerdown_requested(void)
4381 {
4382     int r = powerdown_requested;
4383     powerdown_requested = 0;
4384     return r;
4385 }
4386
4387 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4388 {
4389     QEMUResetEntry **pre, *re;
4390
4391     pre = &first_reset_entry;
4392     while (*pre != NULL)
4393         pre = &(*pre)->next;
4394     re = qemu_mallocz(sizeof(QEMUResetEntry));
4395     re->func = func;
4396     re->opaque = opaque;
4397     re->next = NULL;
4398     *pre = re;
4399 }
4400
4401 void qemu_system_reset(void)
4402 {
4403     QEMUResetEntry *re;
4404
4405     /* reset all devices */
4406     for(re = first_reset_entry; re != NULL; re = re->next) {
4407         re->func(re->opaque);
4408     }
4409 }
4410
4411 void qemu_system_reset_request(void)
4412 {
4413     if (no_reboot) {
4414         shutdown_requested = 1;
4415     } else {
4416         reset_requested = 1;
4417     }
4418     if (cpu_single_env)
4419         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4420 }
4421
4422 void qemu_system_shutdown_request(void)
4423 {
4424     shutdown_requested = 1;
4425     if (cpu_single_env)
4426         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4427 }
4428
4429 void qemu_system_powerdown_request(void)
4430 {
4431     powerdown_requested = 1;
4432     if (cpu_single_env)
4433         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4434 }
4435
4436 #ifdef _WIN32
4437 void host_main_loop_wait(int *timeout)
4438 {
4439     int ret, ret2, i;
4440     PollingEntry *pe;
4441
4442
4443     /* XXX: need to suppress polling by better using win32 events */
4444     ret = 0;
4445     for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4446         ret |= pe->func(pe->opaque);
4447     }
4448     if (ret == 0) {
4449         int err;
4450         WaitObjects *w = &wait_objects;
4451
4452         ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4453         if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4454             if (w->func[ret - WAIT_OBJECT_0])
4455                 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4456
4457             /* Check for additional signaled events */
4458             for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4459
4460                 /* Check if event is signaled */
4461                 ret2 = WaitForSingleObject(w->events[i], 0);
4462                 if(ret2 == WAIT_OBJECT_0) {
4463                     if (w->func[i])
4464                         w->func[i](w->opaque[i]);
4465                 } else if (ret2 == WAIT_TIMEOUT) {
4466                 } else {
4467                     err = GetLastError();
4468                     fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4469                 }
4470             }
4471         } else if (ret == WAIT_TIMEOUT) {
4472         } else {
4473             err = GetLastError();
4474             fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4475         }
4476     }
4477
4478     *timeout = 0;
4479 }
4480 #else
4481 void host_main_loop_wait(int *timeout)
4482 {
4483 }
4484 #endif
4485
4486 void main_loop_wait(int timeout)
4487 {
4488     IOHandlerRecord *ioh;
4489     fd_set rfds, wfds, xfds;
4490     int ret, nfds;
4491     struct timeval tv;
4492
4493     qemu_bh_update_timeout(&timeout);
4494
4495     host_main_loop_wait(&timeout);
4496
4497     /* poll any events */
4498     /* XXX: separate device handlers from system ones */
4499     nfds = -1;
4500     FD_ZERO(&rfds);
4501     FD_ZERO(&wfds);
4502     FD_ZERO(&xfds);
4503     for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4504         if (ioh->deleted)
4505             continue;
4506         if (ioh->fd_read &&
4507             (!ioh->fd_read_poll ||
4508              ioh->fd_read_poll(ioh->opaque) != 0)) {
4509             FD_SET(ioh->fd, &rfds);
4510             if (ioh->fd > nfds)
4511                 nfds = ioh->fd;
4512         }
4513         if (ioh->fd_write) {
4514             FD_SET(ioh->fd, &wfds);
4515             if (ioh->fd > nfds)
4516                 nfds = ioh->fd;
4517         }
4518     }
4519
4520     tv.tv_sec = timeout / 1000;
4521     tv.tv_usec = (timeout % 1000) * 1000;
4522
4523 #if defined(CONFIG_SLIRP)
4524     if (slirp_is_inited()) {
4525         slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4526     }
4527 #endif
4528     ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4529     if (ret > 0) {
4530         IOHandlerRecord **pioh;
4531
4532         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4533             if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4534                 ioh->fd_read(ioh->opaque);
4535             }
4536             if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4537                 ioh->fd_write(ioh->opaque);
4538             }
4539         }
4540
4541         /* remove deleted IO handlers */
4542         pioh = &first_io_handler;
4543         while (*pioh) {
4544             ioh = *pioh;
4545             if (ioh->deleted) {
4546                 *pioh = ioh->next;
4547                 qemu_free(ioh);
4548             } else
4549                 pioh = &ioh->next;
4550         }
4551     }
4552 #if defined(CONFIG_SLIRP)
4553     if (slirp_is_inited()) {
4554         if (ret < 0) {
4555             FD_ZERO(&rfds);
4556             FD_ZERO(&wfds);
4557             FD_ZERO(&xfds);
4558         }
4559         slirp_select_poll(&rfds, &wfds, &xfds);
4560     }
4561 #endif
4562
4563     /* Check bottom-halves last in case any of the earlier events triggered
4564        them.  */
4565     qemu_bh_poll();
4566
4567 }
4568
4569 static int main_loop(void)
4570 {
4571     int ret, timeout;
4572 #ifdef CONFIG_PROFILER
4573     int64_t ti;
4574 #endif
4575     CPUState *env;
4576
4577     cur_cpu = first_cpu;
4578     next_cpu = cur_cpu->next_cpu ?: first_cpu;
4579     for(;;) {
4580         if (vm_running) {
4581
4582             for(;;) {
4583                 /* get next cpu */
4584                 env = next_cpu;
4585 #ifdef CONFIG_PROFILER
4586                 ti = profile_getclock();
4587 #endif
4588                 if (use_icount) {
4589                     int64_t count;
4590                     int decr;
4591                     qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4592                     env->icount_decr.u16.low = 0;
4593                     env->icount_extra = 0;
4594                     count = qemu_next_deadline();
4595                     count = (count + (1 << icount_time_shift) - 1)
4596                             >> icount_time_shift;
4597                     qemu_icount += count;
4598                     decr = (count > 0xffff) ? 0xffff : count;
4599                     count -= decr;
4600                     env->icount_decr.u16.low = decr;
4601                     env->icount_extra = count;
4602                 }
4603                 ret = cpu_exec(env);
4604 #ifdef CONFIG_PROFILER
4605                 qemu_time += profile_getclock() - ti;
4606 #endif
4607                 if (use_icount) {
4608                     /* Fold pending instructions back into the
4609                        instruction counter, and clear the interrupt flag.  */
4610                     qemu_icount -= (env->icount_decr.u16.low
4611                                     + env->icount_extra);
4612                     env->icount_decr.u32 = 0;
4613                     env->icount_extra = 0;
4614                 }
4615                 next_cpu = env->next_cpu ?: first_cpu;
4616                 if (event_pending && likely(ret != EXCP_DEBUG)) {
4617                     ret = EXCP_INTERRUPT;
4618                     event_pending = 0;
4619                     break;
4620                 }
4621                 if (ret == EXCP_HLT) {
4622                     /* Give the next CPU a chance to run.  */
4623                     cur_cpu = env;
4624                     continue;
4625                 }
4626                 if (ret != EXCP_HALTED)
4627                     break;
4628                 /* all CPUs are halted ? */
4629                 if (env == cur_cpu)
4630                     break;
4631             }
4632             cur_cpu = env;
4633
4634             if (shutdown_requested) {
4635                 ret = EXCP_INTERRUPT;
4636                 if (no_shutdown) {
4637                     vm_stop(0);
4638                     no_shutdown = 0;
4639                 }
4640                 else
4641                     break;
4642             }
4643             if (reset_requested) {
4644                 reset_requested = 0;
4645                 qemu_system_reset();
4646                 ret = EXCP_INTERRUPT;
4647             }
4648             if (powerdown_requested) {
4649                 powerdown_requested = 0;
4650                 qemu_system_powerdown();
4651                 ret = EXCP_INTERRUPT;
4652             }
4653             if (unlikely(ret == EXCP_DEBUG)) {
4654                 vm_stop(EXCP_DEBUG);
4655             }
4656             /* If all cpus are halted then wait until the next IRQ */
4657             /* XXX: use timeout computed from timers */
4658             if (ret == EXCP_HALTED) {
4659                 if (use_icount) {
4660                     int64_t add;
4661                     int64_t delta;
4662                     /* Advance virtual time to the next event.  */
4663                     if (use_icount == 1) {
4664                         /* When not using an adaptive execution frequency
4665                            we tend to get badly out of sync with real time,
4666                            so just delay for a reasonable amount of time.  */
4667                         delta = 0;
4668                     } else {
4669                         delta = cpu_get_icount() - cpu_get_clock();
4670                     }
4671                     if (delta > 0) {
4672                         /* If virtual time is ahead of real time then just
4673                            wait for IO.  */
4674                         timeout = (delta / 1000000) + 1;
4675                     } else {
4676                         /* Wait for either IO to occur or the next
4677                            timer event.  */
4678                         add = qemu_next_deadline();
4679                         /* We advance the timer before checking for IO.
4680                            Limit the amount we advance so that early IO
4681                            activity won't get the guest too far ahead.  */
4682                         if (add > 10000000)
4683                             add = 10000000;
4684                         delta += add;
4685                         add = (add + (1 << icount_time_shift) - 1)
4686                               >> icount_time_shift;
4687                         qemu_icount += add;
4688                         timeout = delta / 1000000;
4689                         if (timeout < 0)
4690                             timeout = 0;
4691                     }
4692                 } else {
4693                     timeout = 5000;
4694                 }
4695             } else {
4696                 timeout = 0;
4697             }
4698         } else {
4699             if (shutdown_requested) {
4700                 ret = EXCP_INTERRUPT;
4701                 break;
4702             }
4703             timeout = 5000;
4704         }
4705 #ifdef CONFIG_PROFILER
4706         ti = profile_getclock();
4707 #endif
4708         main_loop_wait(timeout);
4709 #ifdef CONFIG_PROFILER
4710         dev_time += profile_getclock() - ti;
4711 #endif
4712     }
4713     cpu_disable_ticks();
4714     return ret;
4715 }
4716
4717 static void help(int exitcode)
4718 {
4719     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4720            "usage: %s [options] [disk_image]\n"
4721            "\n"
4722            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4723            "\n"
4724            "Standard options:\n"
4725            "-M machine      select emulated machine (-M ? for list)\n"
4726            "-cpu cpu        select CPU (-cpu ? for list)\n"
4727            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
4728            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
4729            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
4730            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4731            "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
4732            "       [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
4733            "       [,cache=writethrough|writeback|none][,format=f]\n"
4734            "                use 'file' as a drive image\n"
4735            "-mtdblock file  use 'file' as on-board Flash memory image\n"
4736            "-sd file        use 'file' as SecureDigital card image\n"
4737            "-pflash file    use 'file' as a parallel flash image\n"
4738            "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
4739            "-snapshot       write to temporary files instead of disk image files\n"
4740 #ifdef CONFIG_SDL
4741            "-no-frame       open SDL window without a frame and window decorations\n"
4742            "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4743            "-no-quit        disable SDL window close capability\n"
4744 #endif
4745 #ifdef TARGET_I386
4746            "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
4747 #endif
4748            "-m megs         set virtual RAM size to megs MB [default=%d]\n"
4749            "-smp n          set the number of CPUs to 'n' [default=1]\n"
4750            "-nographic      disable graphical output and redirect serial I/Os to console\n"
4751            "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
4752 #ifndef _WIN32
4753            "-k language     use keyboard layout (for example \"fr\" for French)\n"
4754 #endif
4755 #ifdef HAS_AUDIO
4756            "-audio-help     print list of audio drivers and their options\n"
4757            "-soundhw c1,... enable audio support\n"
4758            "                and only specified sound cards (comma separated list)\n"
4759            "                use -soundhw ? to get the list of supported cards\n"
4760            "                use -soundhw all to enable all of them\n"
4761 #endif
4762            "-vga [std|cirrus|vmware]\n"
4763            "                select video card type\n"
4764            "-localtime      set the real time clock to local time [default=utc]\n"
4765            "-full-screen    start in full screen\n"
4766 #ifdef TARGET_I386
4767            "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
4768 #endif
4769            "-usb            enable the USB driver (will be the default soon)\n"
4770            "-usbdevice name add the host or guest USB device 'name'\n"
4771 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4772            "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
4773 #endif
4774            "-name string    set the name of the guest\n"
4775            "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4776            "\n"
4777            "Network options:\n"
4778            "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4779            "                create a new Network Interface Card and connect it to VLAN 'n'\n"
4780 #ifdef CONFIG_SLIRP
4781            "-net user[,vlan=n][,hostname=host]\n"
4782            "                connect the user mode network stack to VLAN 'n' and send\n"
4783            "                hostname 'host' to DHCP clients\n"
4784 #endif
4785 #ifdef _WIN32
4786            "-net tap[,vlan=n],ifname=name\n"
4787            "                connect the host TAP network interface to VLAN 'n'\n"
4788 #else
4789            "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4790            "                connect the host TAP network interface to VLAN 'n' and use the\n"
4791            "                network scripts 'file' (default=%s)\n"
4792            "                and 'dfile' (default=%s);\n"
4793            "                use '[down]script=no' to disable script execution;\n"
4794            "                use 'fd=h' to connect to an already opened TAP interface\n"
4795 #endif
4796            "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4797            "                connect the vlan 'n' to another VLAN using a socket connection\n"
4798            "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4799            "                connect the vlan 'n' to multicast maddr and port\n"
4800 #ifdef CONFIG_VDE
4801            "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4802            "                connect the vlan 'n' to port 'n' of a vde switch running\n"
4803            "                on host and listening for incoming connections on 'socketpath'.\n"
4804            "                Use group 'groupname' and mode 'octalmode' to change default\n"
4805            "                ownership and permissions for communication port.\n"
4806 #endif
4807            "-net none       use it alone to have zero network devices; if no -net option\n"
4808            "                is provided, the default is '-net nic -net user'\n"
4809            "\n"
4810 #ifdef CONFIG_SLIRP
4811            "-tftp dir       allow tftp access to files in dir [-net user]\n"
4812            "-bootp file     advertise file in BOOTP replies\n"
4813 #ifndef _WIN32
4814            "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
4815 #endif
4816            "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4817            "                redirect TCP or UDP connections from host to guest [-net user]\n"
4818 #endif
4819            "\n"
4820            "Linux boot specific:\n"
4821            "-kernel bzImage use 'bzImage' as kernel image\n"
4822            "-append cmdline use 'cmdline' as kernel command line\n"
4823            "-initrd file    use 'file' as initial ram disk\n"
4824            "\n"
4825            "Debug/Expert options:\n"
4826            "-monitor dev    redirect the monitor to char device 'dev'\n"
4827            "-serial dev     redirect the serial port to char device 'dev'\n"
4828            "-parallel dev   redirect the parallel port to char device 'dev'\n"
4829            "-pidfile file   Write PID to 'file'\n"
4830            "-S              freeze CPU at startup (use 'c' to start execution)\n"
4831            "-s              wait gdb connection to port\n"
4832            "-p port         set gdb connection port [default=%s]\n"
4833            "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
4834            "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
4835            "                translation (t=none or lba) (usually qemu can guess them)\n"
4836            "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
4837 #ifdef USE_KQEMU
4838            "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
4839            "-no-kqemu       disable KQEMU kernel module usage\n"
4840 #endif
4841 #ifdef CONFIG_KVM
4842            "-enable-kvm     enable KVM full virtualization support\n"
4843 #endif
4844 #ifdef TARGET_I386
4845            "-no-acpi        disable ACPI\n"
4846 #endif
4847 #ifdef CONFIG_CURSES
4848            "-curses         use a curses/ncurses interface instead of SDL\n"
4849 #endif
4850            "-no-reboot      exit instead of rebooting\n"
4851            "-no-shutdown    stop before shutdown\n"
4852            "-loadvm [tag|id]  start right away with a saved state (loadvm in monitor)\n"
4853            "-vnc display    start a VNC server on display\n"
4854 #ifndef _WIN32
4855            "-daemonize      daemonize QEMU after initializing\n"
4856 #endif
4857            "-option-rom rom load a file, rom, into the option ROM space\n"
4858 #ifdef TARGET_SPARC
4859            "-prom-env variable=value  set OpenBIOS nvram variables\n"
4860 #endif
4861            "-clock          force the use of the given methods for timer alarm.\n"
4862            "                To see what timers are available use -clock ?\n"
4863            "-startdate      select initial date of the clock\n"
4864            "-icount [N|auto]\n"
4865            "                Enable virtual instruction counter with 2^N clock ticks per instruction\n"
4866            "\n"
4867            "During emulation, the following keys are useful:\n"
4868            "ctrl-alt-f      toggle full screen\n"
4869            "ctrl-alt-n      switch to virtual console 'n'\n"
4870            "ctrl-alt        toggle mouse and keyboard grab\n"
4871            "\n"
4872            "When using -nographic, press 'ctrl-a h' to get some help.\n"
4873            ,
4874            "qemu",
4875            DEFAULT_RAM_SIZE,
4876 #ifndef _WIN32
4877            DEFAULT_NETWORK_SCRIPT,
4878            DEFAULT_NETWORK_DOWN_SCRIPT,
4879 #endif
4880            DEFAULT_GDBSTUB_PORT,
4881            "/tmp/qemu.log");
4882     exit(exitcode);
4883 }
4884
4885 #define HAS_ARG 0x0001
4886
4887 enum {
4888     QEMU_OPTION_h,
4889
4890     QEMU_OPTION_M,
4891     QEMU_OPTION_cpu,
4892     QEMU_OPTION_fda,
4893     QEMU_OPTION_fdb,
4894     QEMU_OPTION_hda,
4895     QEMU_OPTION_hdb,
4896     QEMU_OPTION_hdc,
4897     QEMU_OPTION_hdd,
4898     QEMU_OPTION_drive,
4899     QEMU_OPTION_cdrom,
4900     QEMU_OPTION_mtdblock,
4901     QEMU_OPTION_sd,
4902     QEMU_OPTION_pflash,
4903     QEMU_OPTION_boot,
4904     QEMU_OPTION_snapshot,
4905 #ifdef TARGET_I386
4906     QEMU_OPTION_no_fd_bootchk,
4907 #endif
4908     QEMU_OPTION_m,
4909     QEMU_OPTION_nographic,
4910     QEMU_OPTION_portrait,
4911 #ifdef HAS_AUDIO
4912     QEMU_OPTION_audio_help,
4913     QEMU_OPTION_soundhw,
4914 #endif
4915
4916     QEMU_OPTION_net,
4917     QEMU_OPTION_tftp,
4918     QEMU_OPTION_bootp,
4919     QEMU_OPTION_smb,
4920     QEMU_OPTION_redir,
4921
4922     QEMU_OPTION_kernel,
4923     QEMU_OPTION_append,
4924     QEMU_OPTION_initrd,
4925
4926     QEMU_OPTION_S,
4927     QEMU_OPTION_s,
4928     QEMU_OPTION_p,
4929     QEMU_OPTION_d,
4930     QEMU_OPTION_hdachs,
4931     QEMU_OPTION_L,
4932     QEMU_OPTION_bios,
4933     QEMU_OPTION_k,
4934     QEMU_OPTION_localtime,
4935     QEMU_OPTION_g,
4936     QEMU_OPTION_vga,
4937     QEMU_OPTION_echr,
4938     QEMU_OPTION_monitor,
4939     QEMU_OPTION_serial,
4940     QEMU_OPTION_parallel,
4941     QEMU_OPTION_loadvm,
4942     QEMU_OPTION_full_screen,
4943     QEMU_OPTION_no_frame,
4944     QEMU_OPTION_alt_grab,
4945     QEMU_OPTION_no_quit,
4946     QEMU_OPTION_pidfile,
4947     QEMU_OPTION_no_kqemu,
4948     QEMU_OPTION_kernel_kqemu,
4949     QEMU_OPTION_enable_kvm,
4950     QEMU_OPTION_win2k_hack,
4951     QEMU_OPTION_usb,
4952     QEMU_OPTION_usbdevice,
4953     QEMU_OPTION_smp,
4954     QEMU_OPTION_vnc,
4955     QEMU_OPTION_no_acpi,
4956     QEMU_OPTION_curses,
4957     QEMU_OPTION_no_reboot,
4958     QEMU_OPTION_no_shutdown,
4959     QEMU_OPTION_show_cursor,
4960     QEMU_OPTION_daemonize,
4961     QEMU_OPTION_option_rom,
4962     QEMU_OPTION_semihosting,
4963     QEMU_OPTION_name,
4964     QEMU_OPTION_prom_env,
4965     QEMU_OPTION_old_param,
4966     QEMU_OPTION_clock,
4967     QEMU_OPTION_startdate,
4968     QEMU_OPTION_tb_size,
4969     QEMU_OPTION_icount,
4970     QEMU_OPTION_uuid,
4971     QEMU_OPTION_incoming,
4972 };
4973
4974 typedef struct QEMUOption {
4975     const char *name;
4976     int flags;
4977     int index;
4978 } QEMUOption;
4979
4980 static const QEMUOption qemu_options[] = {
4981     { "h", 0, QEMU_OPTION_h },
4982     { "help", 0, QEMU_OPTION_h },
4983
4984     { "M", HAS_ARG, QEMU_OPTION_M },
4985     { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4986     { "fda", HAS_ARG, QEMU_OPTION_fda },
4987     { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4988     { "hda", HAS_ARG, QEMU_OPTION_hda },
4989     { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4990     { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4991     { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4992     { "drive", HAS_ARG, QEMU_OPTION_drive },
4993     { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4994     { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4995     { "sd", HAS_ARG, QEMU_OPTION_sd },
4996     { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4997     { "boot", HAS_ARG, QEMU_OPTION_boot },
4998     { "snapshot", 0, QEMU_OPTION_snapshot },
4999 #ifdef TARGET_I386
5000     { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5001 #endif
5002     { "m", HAS_ARG, QEMU_OPTION_m },
5003     { "nographic", 0, QEMU_OPTION_nographic },
5004     { "portrait", 0, QEMU_OPTION_portrait },
5005     { "k", HAS_ARG, QEMU_OPTION_k },
5006 #ifdef HAS_AUDIO
5007     { "audio-help", 0, QEMU_OPTION_audio_help },
5008     { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5009 #endif
5010
5011     { "net", HAS_ARG, QEMU_OPTION_net},
5012 #ifdef CONFIG_SLIRP
5013     { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5014     { "bootp", HAS_ARG, QEMU_OPTION_bootp },
5015 #ifndef _WIN32
5016     { "smb", HAS_ARG, QEMU_OPTION_smb },
5017 #endif
5018     { "redir", HAS_ARG, QEMU_OPTION_redir },
5019 #endif
5020
5021     { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5022     { "append", HAS_ARG, QEMU_OPTION_append },
5023     { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5024
5025     { "S", 0, QEMU_OPTION_S },
5026     { "s", 0, QEMU_OPTION_s },
5027     { "p", HAS_ARG, QEMU_OPTION_p },
5028     { "d", HAS_ARG, QEMU_OPTION_d },
5029     { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5030     { "L", HAS_ARG, QEMU_OPTION_L },
5031     { "bios", HAS_ARG, QEMU_OPTION_bios },
5032 #ifdef USE_KQEMU
5033     { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5034     { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5035 #endif
5036 #ifdef CONFIG_KVM
5037     { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
5038 #endif
5039 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5040     { "g", 1, QEMU_OPTION_g },
5041 #endif
5042     { "localtime", 0, QEMU_OPTION_localtime },
5043     { "vga", HAS_ARG, QEMU_OPTION_vga },
5044     { "echr", HAS_ARG, QEMU_OPTION_echr },
5045     { "monitor", HAS_ARG, QEMU_OPTION_monitor },
5046     { "serial", HAS_ARG, QEMU_OPTION_serial },
5047     { "parallel", HAS_ARG, QEMU_OPTION_parallel },
5048     { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5049     { "full-screen", 0, QEMU_OPTION_full_screen },
5050 #ifdef CONFIG_SDL
5051     { "no-frame", 0, QEMU_OPTION_no_frame },
5052     { "alt-grab", 0, QEMU_OPTION_alt_grab },
5053     { "no-quit", 0, QEMU_OPTION_no_quit },
5054 #endif
5055     { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5056     { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5057     { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5058     { "smp", HAS_ARG, QEMU_OPTION_smp },
5059     { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5060 #ifdef CONFIG_CURSES
5061     { "curses", 0, QEMU_OPTION_curses },
5062 #endif
5063     { "uuid", HAS_ARG, QEMU_OPTION_uuid },
5064
5065     /* temporary options */
5066     { "usb", 0, QEMU_OPTION_usb },
5067     { "no-acpi", 0, QEMU_OPTION_no_acpi },
5068     { "no-reboot", 0, QEMU_OPTION_no_reboot },
5069     { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
5070     { "show-cursor", 0, QEMU_OPTION_show_cursor },
5071     { "daemonize", 0, QEMU_OPTION_daemonize },
5072     { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
5073 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5074     { "semihosting", 0, QEMU_OPTION_semihosting },
5075 #endif
5076     { "name", HAS_ARG, QEMU_OPTION_name },
5077 #if defined(TARGET_SPARC)
5078     { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
5079 #endif
5080 #if defined(TARGET_ARM)
5081     { "old-param", 0, QEMU_OPTION_old_param },
5082 #endif
5083     { "clock", HAS_ARG, QEMU_OPTION_clock },
5084     { "startdate", HAS_ARG, QEMU_OPTION_startdate },
5085     { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
5086     { "icount", HAS_ARG, QEMU_OPTION_icount },
5087     { "incoming", HAS_ARG, QEMU_OPTION_incoming },
5088     { NULL },
5089 };
5090
5091 /* password input */
5092
5093 int qemu_key_check(BlockDriverState *bs, const char *name)
5094 {
5095     char password[256];
5096     int i;
5097
5098     if (!bdrv_is_encrypted(bs))
5099         return 0;
5100
5101     term_printf("%s is encrypted.\n", name);
5102     for(i = 0; i < 3; i++) {
5103         monitor_readline("Password: ", 1, password, sizeof(password));
5104         if (bdrv_set_key(bs, password) == 0)
5105             return 0;
5106         term_printf("invalid password\n");
5107     }
5108     return -EPERM;
5109 }
5110
5111 static BlockDriverState *get_bdrv(int index)
5112 {
5113     if (index > nb_drives)
5114         return NULL;
5115     return drives_table[index].bdrv;
5116 }
5117
5118 static void read_passwords(void)
5119 {
5120     BlockDriverState *bs;
5121     int i;
5122
5123     for(i = 0; i < 6; i++) {
5124         bs = get_bdrv(i);
5125         if (bs)
5126             qemu_key_check(bs, bdrv_get_device_name(bs));
5127     }
5128 }
5129
5130 #ifdef HAS_AUDIO
5131 struct soundhw soundhw[] = {
5132 #ifdef HAS_AUDIO_CHOICE
5133 #if defined(TARGET_I386) || defined(TARGET_MIPS)
5134     {
5135         "pcspk",
5136         "PC speaker",
5137         0,
5138         1,
5139         { .init_isa = pcspk_audio_init }
5140     },
5141 #endif
5142     {
5143         "sb16",
5144         "Creative Sound Blaster 16",
5145         0,
5146         1,
5147         { .init_isa = SB16_init }
5148     },
5149
5150 #ifdef CONFIG_CS4231A
5151     {
5152         "cs4231a",
5153         "CS4231A",
5154         0,
5155         1,
5156         { .init_isa = cs4231a_init }
5157     },
5158 #endif
5159
5160 #ifdef CONFIG_ADLIB
5161     {
5162         "adlib",
5163 #ifdef HAS_YMF262
5164         "Yamaha YMF262 (OPL3)",
5165 #else
5166         "Yamaha YM3812 (OPL2)",
5167 #endif
5168         0,
5169         1,
5170         { .init_isa = Adlib_init }
5171     },
5172 #endif
5173
5174 #ifdef CONFIG_GUS
5175     {
5176         "gus",
5177         "Gravis Ultrasound GF1",
5178         0,
5179         1,
5180         { .init_isa = GUS_init }
5181     },
5182 #endif
5183
5184 #ifdef CONFIG_AC97
5185     {
5186         "ac97",
5187         "Intel 82801AA AC97 Audio",
5188         0,
5189         0,
5190         { .init_pci = ac97_init }
5191     },
5192 #endif
5193
5194     {
5195         "es1370",
5196         "ENSONIQ AudioPCI ES1370",
5197         0,
5198         0,
5199         { .init_pci = es1370_init }
5200     },
5201 #endif
5202
5203     { NULL, NULL, 0, 0, { NULL } }
5204 };
5205
5206 static void select_soundhw (const char *optarg)
5207 {
5208     struct soundhw *c;
5209
5210     if (*optarg == '?') {
5211     show_valid_cards:
5212
5213         printf ("Valid sound card names (comma separated):\n");
5214         for (c = soundhw; c->name; ++c) {
5215             printf ("%-11s %s\n", c->name, c->descr);
5216         }
5217         printf ("\n-soundhw all will enable all of the above\n");
5218         exit (*optarg != '?');
5219     }
5220     else {
5221         size_t l;
5222         const char *p;
5223         char *e;
5224         int bad_card = 0;
5225
5226         if (!strcmp (optarg, "all")) {
5227             for (c = soundhw; c->name; ++c) {
5228                 c->enabled = 1;
5229             }
5230             return;
5231         }
5232
5233         p = optarg;
5234         while (*p) {
5235             e = strchr (p, ',');
5236             l = !e ? strlen (p) : (size_t) (e - p);
5237
5238             for (c = soundhw; c->name; ++c) {
5239                 if (!strncmp (c->name, p, l)) {
5240                     c->enabled = 1;
5241                     break;
5242                 }
5243             }
5244
5245             if (!c->name) {
5246                 if (l > 80) {
5247                     fprintf (stderr,
5248                              "Unknown sound card name (too big to show)\n");
5249                 }
5250                 else {
5251                     fprintf (stderr, "Unknown sound card name `%.*s'\n",
5252                              (int) l, p);
5253                 }
5254                 bad_card = 1;
5255             }
5256             p += l + (e != NULL);
5257         }
5258
5259         if (bad_card)
5260             goto show_valid_cards;
5261     }
5262 }
5263 #endif
5264
5265 static void select_vgahw (const char *p)
5266 {
5267     const char *opts;
5268
5269     if (strstart(p, "std", &opts)) {
5270         cirrus_vga_enabled = 0;
5271         vmsvga_enabled = 0;
5272     } else if (strstart(p, "cirrus", &opts)) {
5273         cirrus_vga_enabled = 1;
5274         vmsvga_enabled = 0;
5275     } else if (strstart(p, "vmware", &opts)) {
5276         cirrus_vga_enabled = 0;
5277         vmsvga_enabled = 1;
5278     } else {
5279     invalid_vga:
5280         fprintf(stderr, "Unknown vga type: %s\n", p);
5281         exit(1);
5282     }
5283     while (*opts) {
5284         const char *nextopt;
5285
5286         if (strstart(opts, ",retrace=", &nextopt)) {
5287             opts = nextopt;
5288             if (strstart(opts, "dumb", &nextopt))
5289                 vga_retrace_method = VGA_RETRACE_DUMB;
5290             else if (strstart(opts, "precise", &nextopt))
5291                 vga_retrace_method = VGA_RETRACE_PRECISE;
5292             else goto invalid_vga;
5293         } else goto invalid_vga;
5294         opts = nextopt;
5295     }
5296 }
5297
5298 #ifdef _WIN32
5299 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5300 {
5301     exit(STATUS_CONTROL_C_EXIT);
5302     return TRUE;
5303 }
5304 #endif
5305
5306 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
5307 {
5308     int ret;
5309
5310     if(strlen(str) != 36)
5311         return -1;
5312
5313     ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
5314             &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
5315             &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
5316
5317     if(ret != 16)
5318         return -1;
5319
5320     return 0;
5321 }
5322
5323 #define MAX_NET_CLIENTS 32
5324
5325 #ifndef _WIN32
5326
5327 static void termsig_handler(int signal)
5328 {
5329     qemu_system_shutdown_request();
5330 }
5331
5332 static void termsig_setup(void)
5333 {
5334     struct sigaction act;
5335
5336     memset(&act, 0, sizeof(act));
5337     act.sa_handler = termsig_handler;
5338     sigaction(SIGINT,  &act, NULL);
5339     sigaction(SIGHUP,  &act, NULL);
5340     sigaction(SIGTERM, &act, NULL);
5341 }
5342
5343 #endif
5344
5345 int main(int argc, char **argv)
5346 {
5347 #ifdef CONFIG_GDBSTUB
5348     int use_gdbstub;
5349     const char *gdbstub_port;
5350 #endif
5351     uint32_t boot_devices_bitmap = 0;
5352     int i;
5353     int snapshot, linux_boot, net_boot;
5354     const char *initrd_filename;
5355     const char *kernel_filename, *kernel_cmdline;
5356     const char *boot_devices = "";
5357     DisplayState *ds = &display_state;
5358     int cyls, heads, secs, translation;
5359     const char *net_clients[MAX_NET_CLIENTS];
5360     int nb_net_clients;
5361     int hda_index;
5362     int optind;
5363     const char *r, *optarg;
5364     CharDriverState *monitor_hd;
5365     const char *monitor_device;
5366     const char *serial_devices[MAX_SERIAL_PORTS];
5367     int serial_device_index;
5368     const char *parallel_devices[MAX_PARALLEL_PORTS];
5369     int parallel_device_index;
5370     const char *loadvm = NULL;
5371     QEMUMachine *machine;
5372     const char *cpu_model;
5373     const char *usb_devices[MAX_USB_CMDLINE];
5374     int usb_devices_index;
5375     int fds[2];
5376     int tb_size;
5377     const char *pid_file = NULL;
5378     int autostart;
5379     const char *incoming = NULL;
5380
5381     LIST_INIT (&vm_change_state_head);
5382 #ifndef _WIN32
5383     {
5384         struct sigaction act;
5385         sigfillset(&act.sa_mask);
5386         act.sa_flags = 0;
5387         act.sa_handler = SIG_IGN;
5388         sigaction(SIGPIPE, &act, NULL);
5389     }
5390 #else
5391     SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5392     /* Note: cpu_interrupt() is currently not SMP safe, so we force
5393        QEMU to run on a single CPU */
5394     {
5395         HANDLE h;
5396         DWORD mask, smask;
5397         int i;
5398         h = GetCurrentProcess();
5399         if (GetProcessAffinityMask(h, &mask, &smask)) {
5400             for(i = 0; i < 32; i++) {
5401                 if (mask & (1 << i))
5402                     break;
5403             }
5404             if (i != 32) {
5405                 mask = 1 << i;
5406                 SetProcessAffinityMask(h, mask);
5407             }
5408         }
5409     }
5410 #endif
5411
5412     register_machines();
5413     machine = first_machine;
5414     cpu_model = NULL;
5415     initrd_filename = NULL;
5416     ram_size = 0;
5417     vga_ram_size = VGA_RAM_SIZE;
5418 #ifdef CONFIG_GDBSTUB
5419     use_gdbstub = 0;
5420     gdbstub_port = DEFAULT_GDBSTUB_PORT;
5421 #endif
5422     snapshot = 0;
5423     nographic = 0;
5424     curses = 0;
5425     kernel_filename = NULL;
5426     kernel_cmdline = "";
5427     cyls = heads = secs = 0;
5428     translation = BIOS_ATA_TRANSLATION_AUTO;
5429     monitor_device = "vc";
5430
5431     serial_devices[0] = "vc:80Cx24C";
5432     for(i = 1; i < MAX_SERIAL_PORTS; i++)
5433         serial_devices[i] = NULL;
5434     serial_device_index = 0;
5435
5436     parallel_devices[0] = "vc:640x480";
5437     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5438         parallel_devices[i] = NULL;
5439     parallel_device_index = 0;
5440
5441     usb_devices_index = 0;
5442
5443     nb_net_clients = 0;
5444     nb_drives = 0;
5445     nb_drives_opt = 0;
5446     hda_index = -1;
5447
5448     nb_nics = 0;
5449
5450     tb_size = 0;
5451     autostart= 1;
5452
5453     optind = 1;
5454     for(;;) {
5455         if (optind >= argc)
5456             break;
5457         r = argv[optind];
5458         if (r[0] != '-') {
5459             hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5460         } else {
5461             const QEMUOption *popt;
5462
5463             optind++;
5464             /* Treat --foo the same as -foo.  */
5465             if (r[1] == '-')
5466                 r++;
5467             popt = qemu_options;
5468             for(;;) {
5469                 if (!popt->name) {
5470                     fprintf(stderr, "%s: invalid option -- '%s'\n",
5471                             argv[0], r);
5472                     exit(1);
5473                 }
5474                 if (!strcmp(popt->name, r + 1))
5475                     break;
5476                 popt++;
5477             }
5478             if (popt->flags & HAS_ARG) {
5479                 if (optind >= argc) {
5480                     fprintf(stderr, "%s: option '%s' requires an argument\n",
5481                             argv[0], r);
5482                     exit(1);
5483                 }
5484                 optarg = argv[optind++];
5485             } else {
5486                 optarg = NULL;
5487             }
5488
5489             switch(popt->index) {
5490             case QEMU_OPTION_M:
5491                 machine = find_machine(optarg);
5492                 if (!machine) {
5493                     QEMUMachine *m;
5494                     printf("Supported machines are:\n");
5495                     for(m = first_machine; m != NULL; m = m->next) {
5496                         printf("%-10s %s%s\n",
5497                                m->name, m->desc,
5498                                m == first_machine ? " (default)" : "");
5499                     }
5500                     exit(*optarg != '?');
5501                 }
5502                 break;
5503             case QEMU_OPTION_cpu:
5504                 /* hw initialization will check this */
5505                 if (*optarg == '?') {
5506 /* XXX: implement xxx_cpu_list for targets that still miss it */
5507 #if defined(cpu_list)
5508                     cpu_list(stdout, &fprintf);
5509 #endif
5510                     exit(0);
5511                 } else {
5512                     cpu_model = optarg;
5513                 }
5514                 break;
5515             case QEMU_OPTION_initrd:
5516                 initrd_filename = optarg;
5517                 break;
5518             case QEMU_OPTION_hda:
5519                 if (cyls == 0)
5520                     hda_index = drive_add(optarg, HD_ALIAS, 0);
5521                 else
5522                     hda_index = drive_add(optarg, HD_ALIAS
5523                              ",cyls=%d,heads=%d,secs=%d%s",
5524                              0, cyls, heads, secs,
5525                              translation == BIOS_ATA_TRANSLATION_LBA ?
5526                                  ",trans=lba" :
5527                              translation == BIOS_ATA_TRANSLATION_NONE ?
5528                                  ",trans=none" : "");
5529                  break;
5530             case QEMU_OPTION_hdb:
5531             case QEMU_OPTION_hdc:
5532             case QEMU_OPTION_hdd:
5533                 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5534                 break;
5535             case QEMU_OPTION_drive:
5536                 drive_add(NULL, "%s", optarg);
5537                 break;
5538             case QEMU_OPTION_mtdblock:
5539                 drive_add(optarg, MTD_ALIAS);
5540                 break;
5541             case QEMU_OPTION_sd:
5542                 drive_add(optarg, SD_ALIAS);
5543                 break;
5544             case QEMU_OPTION_pflash:
5545                 drive_add(optarg, PFLASH_ALIAS);
5546                 break;
5547             case QEMU_OPTION_snapshot:
5548                 snapshot = 1;
5549                 break;
5550             case QEMU_OPTION_hdachs:
5551                 {
5552                     const char *p;
5553                     p = optarg;
5554                     cyls = strtol(p, (char **)&p, 0);
5555                     if (cyls < 1 || cyls > 16383)
5556                         goto chs_fail;
5557                     if (*p != ',')
5558                         goto chs_fail;
5559                     p++;
5560                     heads = strtol(p, (char **)&p, 0);
5561                     if (heads < 1 || heads > 16)
5562                         goto chs_fail;
5563                     if (*p != ',')
5564                         goto chs_fail;
5565                     p++;
5566                     secs = strtol(p, (char **)&p, 0);
5567                     if (secs < 1 || secs > 63)
5568                         goto chs_fail;
5569                     if (*p == ',') {
5570                         p++;
5571                         if (!strcmp(p, "none"))
5572                             translation = BIOS_ATA_TRANSLATION_NONE;
5573                         else if (!strcmp(p, "lba"))
5574                             translation = BIOS_ATA_TRANSLATION_LBA;
5575                         else if (!strcmp(p, "auto"))
5576                             translation = BIOS_ATA_TRANSLATION_AUTO;
5577                         else
5578                             goto chs_fail;
5579                     } else if (*p != '\0') {
5580                     chs_fail:
5581                         fprintf(stderr, "qemu: invalid physical CHS format\n");
5582                         exit(1);
5583                     }
5584                     if (hda_index != -1)
5585                         snprintf(drives_opt[hda_index].opt,
5586                                  sizeof(drives_opt[hda_index].opt),
5587                                  HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5588                                  0, cyls, heads, secs,
5589                                  translation == BIOS_ATA_TRANSLATION_LBA ?
5590                                     ",trans=lba" :
5591                                  translation == BIOS_ATA_TRANSLATION_NONE ?
5592                                      ",trans=none" : "");
5593                 }
5594                 break;
5595             case QEMU_OPTION_nographic:
5596                 nographic = 1;
5597                 break;
5598 #ifdef CONFIG_CURSES
5599             case QEMU_OPTION_curses:
5600                 curses = 1;
5601                 break;
5602 #endif
5603             case QEMU_OPTION_portrait:
5604                 graphic_rotate = 1;
5605                 break;
5606             case QEMU_OPTION_kernel:
5607                 kernel_filename = optarg;
5608                 break;
5609             case QEMU_OPTION_append:
5610                 kernel_cmdline = optarg;
5611                 break;
5612             case QEMU_OPTION_cdrom:
5613                 drive_add(optarg, CDROM_ALIAS);
5614                 break;
5615             case QEMU_OPTION_boot:
5616                 boot_devices = optarg;
5617                 /* We just do some generic consistency checks */
5618                 {
5619                     /* Could easily be extended to 64 devices if needed */
5620                     const char *p;
5621                     
5622                     boot_devices_bitmap = 0;
5623                     for (p = boot_devices; *p != '\0'; p++) {
5624                         /* Allowed boot devices are:
5625                          * a b     : floppy disk drives
5626                          * c ... f : IDE disk drives
5627                          * g ... m : machine implementation dependant drives
5628                          * n ... p : network devices
5629                          * It's up to each machine implementation to check
5630                          * if the given boot devices match the actual hardware
5631                          * implementation and firmware features.
5632                          */
5633                         if (*p < 'a' || *p > 'q') {
5634                             fprintf(stderr, "Invalid boot device '%c'\n", *p);
5635                             exit(1);
5636                         }
5637                         if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5638                             fprintf(stderr,
5639                                     "Boot device '%c' was given twice\n",*p);
5640                             exit(1);
5641                         }
5642                         boot_devices_bitmap |= 1 << (*p - 'a');
5643                     }
5644                 }
5645                 break;
5646             case QEMU_OPTION_fda:
5647             case QEMU_OPTION_fdb:
5648                 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5649                 break;
5650 #ifdef TARGET_I386
5651             case QEMU_OPTION_no_fd_bootchk:
5652                 fd_bootchk = 0;
5653                 break;
5654 #endif
5655             case QEMU_OPTION_net:
5656                 if (nb_net_clients >= MAX_NET_CLIENTS) {
5657                     fprintf(stderr, "qemu: too many network clients\n");
5658                     exit(1);
5659                 }
5660                 net_clients[nb_net_clients] = optarg;
5661                 nb_net_clients++;
5662                 break;
5663 #ifdef CONFIG_SLIRP
5664             case QEMU_OPTION_tftp:
5665                 tftp_prefix = optarg;
5666                 break;
5667             case QEMU_OPTION_bootp:
5668                 bootp_filename = optarg;
5669                 break;
5670 #ifndef _WIN32
5671             case QEMU_OPTION_smb:
5672                 net_slirp_smb(optarg);
5673                 break;
5674 #endif
5675             case QEMU_OPTION_redir:
5676                 net_slirp_redir(optarg);
5677                 break;
5678 #endif
5679 #ifdef HAS_AUDIO
5680             case QEMU_OPTION_audio_help:
5681                 AUD_help ();
5682                 exit (0);
5683                 break;
5684             case QEMU_OPTION_soundhw:
5685                 select_soundhw (optarg);
5686                 break;
5687 #endif
5688             case QEMU_OPTION_h:
5689                 help(0);
5690                 break;
5691             case QEMU_OPTION_m: {
5692                 uint64_t value;
5693                 char *ptr;
5694
5695                 value = strtoul(optarg, &ptr, 10);
5696                 switch (*ptr) {
5697                 case 0: case 'M': case 'm':
5698                     value <<= 20;
5699                     break;
5700                 case 'G': case 'g':
5701                     value <<= 30;
5702                     break;
5703                 default:
5704                     fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5705                     exit(1);
5706                 }
5707
5708                 /* On 32-bit hosts, QEMU is limited by virtual address space */
5709                 if (value > (2047 << 20)
5710 #ifndef USE_KQEMU
5711                     && HOST_LONG_BITS == 32
5712 #endif
5713                     ) {
5714                     fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5715                     exit(1);
5716                 }
5717                 if (value != (uint64_t)(ram_addr_t)value) {
5718                     fprintf(stderr, "qemu: ram size too large\n");
5719                     exit(1);
5720                 }
5721                 ram_size = value;
5722                 break;
5723             }
5724             case QEMU_OPTION_d:
5725                 {
5726                     int mask;
5727                     const CPULogItem *item;
5728
5729                     mask = cpu_str_to_log_mask(optarg);
5730                     if (!mask) {
5731                         printf("Log items (comma separated):\n");
5732                     for(item = cpu_log_items; item->mask != 0; item++) {
5733                         printf("%-10s %s\n", item->name, item->help);
5734                     }
5735                     exit(1);
5736                     }
5737                     cpu_set_log(mask);
5738                 }
5739                 break;
5740 #ifdef CONFIG_GDBSTUB
5741             case QEMU_OPTION_s:
5742                 use_gdbstub = 1;
5743                 break;
5744             case QEMU_OPTION_p:
5745                 gdbstub_port = optarg;
5746                 break;
5747 #endif
5748             case QEMU_OPTION_L:
5749                 bios_dir = optarg;
5750                 break;
5751             case QEMU_OPTION_bios:
5752                 bios_name = optarg;
5753                 break;
5754             case QEMU_OPTION_S:
5755                 autostart = 0;
5756                 break;
5757             case QEMU_OPTION_k:
5758                 keyboard_layout = optarg;
5759                 break;
5760             case QEMU_OPTION_localtime:
5761                 rtc_utc = 0;
5762                 break;
5763             case QEMU_OPTION_vga:
5764                 select_vgahw (optarg);
5765                 break;
5766             case QEMU_OPTION_g:
5767                 {
5768                     const char *p;
5769                     int w, h, depth;
5770                     p = optarg;
5771                     w = strtol(p, (char **)&p, 10);
5772                     if (w <= 0) {
5773                     graphic_error:
5774                         fprintf(stderr, "qemu: invalid resolution or depth\n");
5775                         exit(1);
5776                     }
5777                     if (*p != 'x')
5778                         goto graphic_error;
5779                     p++;
5780                     h = strtol(p, (char **)&p, 10);
5781                     if (h <= 0)
5782                         goto graphic_error;
5783                     if (*p == 'x') {
5784                         p++;
5785                         depth = strtol(p, (char **)&p, 10);
5786                         if (depth != 8 && depth != 15 && depth != 16 &&
5787                             depth != 24 && depth != 32)
5788                             goto graphic_error;
5789                     } else if (*p == '\0') {
5790                         depth = graphic_depth;
5791                     } else {
5792                         goto graphic_error;
5793                     }
5794
5795                     graphic_width = w;
5796                     graphic_height = h;
5797                     graphic_depth = depth;
5798                 }
5799                 break;
5800             case QEMU_OPTION_echr:
5801                 {
5802                     char *r;
5803                     term_escape_char = strtol(optarg, &r, 0);
5804                     if (r == optarg)
5805                         printf("Bad argument to echr\n");
5806                     break;
5807                 }
5808             case QEMU_OPTION_monitor:
5809                 monitor_device = optarg;
5810                 break;
5811             case QEMU_OPTION_serial:
5812                 if (serial_device_index >= MAX_SERIAL_PORTS) {
5813                     fprintf(stderr, "qemu: too many serial ports\n");
5814                     exit(1);
5815                 }
5816                 serial_devices[serial_device_index] = optarg;
5817                 serial_device_index++;
5818                 break;
5819             case QEMU_OPTION_parallel:
5820                 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5821                     fprintf(stderr, "qemu: too many parallel ports\n");
5822                     exit(1);
5823                 }
5824                 parallel_devices[parallel_device_index] = optarg;
5825                 parallel_device_index++;
5826                 break;
5827             case QEMU_OPTION_loadvm:
5828                 loadvm = optarg;
5829                 break;
5830             case QEMU_OPTION_full_screen:
5831                 full_screen = 1;
5832                 break;
5833 #ifdef CONFIG_SDL
5834             case QEMU_OPTION_no_frame:
5835                 no_frame = 1;
5836                 break;
5837             case QEMU_OPTION_alt_grab:
5838                 alt_grab = 1;
5839                 break;
5840             case QEMU_OPTION_no_quit:
5841                 no_quit = 1;
5842                 break;
5843 #endif
5844             case QEMU_OPTION_pidfile:
5845                 pid_file = optarg;
5846                 break;
5847 #ifdef TARGET_I386
5848             case QEMU_OPTION_win2k_hack:
5849                 win2k_install_hack = 1;
5850                 break;
5851 #endif
5852 #ifdef USE_KQEMU
5853             case QEMU_OPTION_no_kqemu:
5854                 kqemu_allowed = 0;
5855                 break;
5856             case QEMU_OPTION_kernel_kqemu:
5857                 kqemu_allowed = 2;
5858                 break;
5859 #endif
5860 #ifdef CONFIG_KVM
5861             case QEMU_OPTION_enable_kvm:
5862                 kvm_allowed = 1;
5863 #ifdef USE_KQEMU
5864                 kqemu_allowed = 0;
5865 #endif
5866                 break;
5867 #endif
5868             case QEMU_OPTION_usb:
5869                 usb_enabled = 1;
5870                 break;
5871             case QEMU_OPTION_usbdevice:
5872                 usb_enabled = 1;
5873                 if (usb_devices_index >= MAX_USB_CMDLINE) {
5874                     fprintf(stderr, "Too many USB devices\n");
5875                     exit(1);
5876                 }
5877                 usb_devices[usb_devices_index] = optarg;
5878                 usb_devices_index++;
5879                 break;
5880             case QEMU_OPTION_smp:
5881                 smp_cpus = atoi(optarg);
5882                 if (smp_cpus < 1) {
5883                     fprintf(stderr, "Invalid number of CPUs\n");
5884                     exit(1);
5885                 }
5886                 break;
5887             case QEMU_OPTION_vnc:
5888                 vnc_display = optarg;
5889                 break;
5890             case QEMU_OPTION_no_acpi:
5891                 acpi_enabled = 0;
5892                 break;
5893             case QEMU_OPTION_no_reboot:
5894                 no_reboot = 1;
5895                 break;
5896             case QEMU_OPTION_no_shutdown:
5897                 no_shutdown = 1;
5898                 break;
5899             case QEMU_OPTION_show_cursor:
5900                 cursor_hide = 0;
5901                 break;
5902             case QEMU_OPTION_uuid:
5903                 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5904                     fprintf(stderr, "Fail to parse UUID string."
5905                             " Wrong format.\n");
5906                     exit(1);
5907                 }
5908                 break;
5909             case QEMU_OPTION_daemonize:
5910                 daemonize = 1;
5911                 break;
5912             case QEMU_OPTION_option_rom:
5913                 if (nb_option_roms >= MAX_OPTION_ROMS) {
5914                     fprintf(stderr, "Too many option ROMs\n");
5915                     exit(1);
5916                 }
5917                 option_rom[nb_option_roms] = optarg;
5918                 nb_option_roms++;
5919                 break;
5920             case QEMU_OPTION_semihosting:
5921                 semihosting_enabled = 1;
5922                 break;
5923             case QEMU_OPTION_name:
5924                 qemu_name = optarg;
5925                 break;
5926 #ifdef TARGET_SPARC
5927             case QEMU_OPTION_prom_env:
5928                 if (nb_prom_envs >= MAX_PROM_ENVS) {
5929                     fprintf(stderr, "Too many prom variables\n");
5930                     exit(1);
5931                 }
5932                 prom_envs[nb_prom_envs] = optarg;
5933                 nb_prom_envs++;
5934                 break;
5935 #endif
5936 #ifdef TARGET_ARM
5937             case QEMU_OPTION_old_param:
5938                 old_param = 1;
5939                 break;
5940 #endif
5941             case QEMU_OPTION_clock:
5942                 configure_alarms(optarg);
5943                 break;
5944             case QEMU_OPTION_startdate:
5945                 {
5946                     struct tm tm;
5947                     time_t rtc_start_date;
5948                     if (!strcmp(optarg, "now")) {
5949                         rtc_date_offset = -1;
5950                     } else {
5951                         if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5952                                &tm.tm_year,
5953                                &tm.tm_mon,
5954                                &tm.tm_mday,
5955                                &tm.tm_hour,
5956                                &tm.tm_min,
5957                                &tm.tm_sec) == 6) {
5958                             /* OK */
5959                         } else if (sscanf(optarg, "%d-%d-%d",
5960                                           &tm.tm_year,
5961                                           &tm.tm_mon,
5962                                           &tm.tm_mday) == 3) {
5963                             tm.tm_hour = 0;
5964                             tm.tm_min = 0;
5965                             tm.tm_sec = 0;
5966                         } else {
5967                             goto date_fail;
5968                         }
5969                         tm.tm_year -= 1900;
5970                         tm.tm_mon--;
5971                         rtc_start_date = mktimegm(&tm);
5972                         if (rtc_start_date == -1) {
5973                         date_fail:
5974                             fprintf(stderr, "Invalid date format. Valid format are:\n"
5975                                     "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5976                             exit(1);
5977                         }
5978                         rtc_date_offset = time(NULL) - rtc_start_date;
5979                     }
5980                 }
5981                 break;
5982             case QEMU_OPTION_tb_size:
5983                 tb_size = strtol(optarg, NULL, 0);
5984                 if (tb_size < 0)
5985                     tb_size = 0;
5986                 break;
5987             case QEMU_OPTION_icount:
5988                 use_icount = 1;
5989                 if (strcmp(optarg, "auto") == 0) {
5990                     icount_time_shift = -1;
5991                 } else {
5992                     icount_time_shift = strtol(optarg, NULL, 0);
5993                 }
5994                 break;
5995             case QEMU_OPTION_incoming:
5996                 incoming = optarg;
5997                 break;
5998             }
5999         }
6000     }
6001
6002 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
6003     if (kvm_allowed && kqemu_allowed) {
6004         fprintf(stderr,
6005                 "You can not enable both KVM and kqemu at the same time\n");
6006         exit(1);
6007     }
6008 #endif
6009
6010     machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
6011     if (smp_cpus > machine->max_cpus) {
6012         fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
6013                 "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
6014                 machine->max_cpus);
6015         exit(1);
6016     }
6017
6018     if (nographic) {
6019        if (serial_device_index == 0)
6020            serial_devices[0] = "stdio";
6021        if (parallel_device_index == 0)
6022            parallel_devices[0] = "null";
6023        if (strncmp(monitor_device, "vc", 2) == 0)
6024            monitor_device = "stdio";
6025     }
6026
6027 #ifndef _WIN32
6028     if (daemonize) {
6029         pid_t pid;
6030
6031         if (pipe(fds) == -1)
6032             exit(1);
6033
6034         pid = fork();
6035         if (pid > 0) {
6036             uint8_t status;
6037             ssize_t len;
6038
6039             close(fds[1]);
6040
6041         again:
6042             len = read(fds[0], &status, 1);
6043             if (len == -1 && (errno == EINTR))
6044                 goto again;
6045
6046             if (len != 1)
6047                 exit(1);
6048             else if (status == 1) {
6049                 fprintf(stderr, "Could not acquire pidfile\n");
6050                 exit(1);
6051             } else
6052                 exit(0);
6053         } else if (pid < 0)
6054             exit(1);
6055
6056         setsid();
6057
6058         pid = fork();
6059         if (pid > 0)
6060             exit(0);
6061         else if (pid < 0)
6062             exit(1);
6063
6064         umask(027);
6065
6066         signal(SIGTSTP, SIG_IGN);
6067         signal(SIGTTOU, SIG_IGN);
6068         signal(SIGTTIN, SIG_IGN);
6069     }
6070 #endif
6071
6072     if (pid_file && qemu_create_pidfile(pid_file) != 0) {
6073         if (daemonize) {
6074             uint8_t status = 1;
6075             write(fds[1], &status, 1);
6076         } else
6077             fprintf(stderr, "Could not acquire pid file\n");
6078         exit(1);
6079     }
6080
6081 #ifdef USE_KQEMU
6082     if (smp_cpus > 1)
6083         kqemu_allowed = 0;
6084 #endif
6085     linux_boot = (kernel_filename != NULL);
6086     net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6087
6088     if (!linux_boot && net_boot == 0 &&
6089         !machine->nodisk_ok && nb_drives_opt == 0)
6090         help(1);
6091
6092     if (!linux_boot && *kernel_cmdline != '\0') {
6093         fprintf(stderr, "-append only allowed with -kernel option\n");
6094         exit(1);
6095     }
6096
6097     if (!linux_boot && initrd_filename != NULL) {
6098         fprintf(stderr, "-initrd only allowed with -kernel option\n");
6099         exit(1);
6100     }
6101
6102     /* boot to floppy or the default cd if no hard disk defined yet */
6103     if (!boot_devices[0]) {
6104         boot_devices = "cad";
6105     }
6106     setvbuf(stdout, NULL, _IOLBF, 0);
6107
6108     init_timers();
6109     if (init_timer_alarm() < 0) {
6110         fprintf(stderr, "could not initialize alarm timer\n");
6111         exit(1);
6112     }
6113     if (use_icount && icount_time_shift < 0) {
6114         use_icount = 2;
6115         /* 125MIPS seems a reasonable initial guess at the guest speed.
6116            It will be corrected fairly quickly anyway.  */
6117         icount_time_shift = 3;
6118         init_icount_adjust();
6119     }
6120
6121 #ifdef _WIN32
6122     socket_init();
6123 #endif
6124
6125     /* init network clients */
6126     if (nb_net_clients == 0) {
6127         /* if no clients, we use a default config */
6128         net_clients[nb_net_clients++] = "nic";
6129 #ifdef CONFIG_SLIRP
6130         net_clients[nb_net_clients++] = "user";
6131 #endif
6132     }
6133
6134     for(i = 0;i < nb_net_clients; i++) {
6135         if (net_client_parse(net_clients[i]) < 0)
6136             exit(1);
6137     }
6138     net_client_check();
6139
6140 #ifdef TARGET_I386
6141     /* XXX: this should be moved in the PC machine instantiation code */
6142     if (net_boot != 0) {
6143         int netroms = 0;
6144         for (i = 0; i < nb_nics && i < 4; i++) {
6145             const char *model = nd_table[i].model;
6146             char buf[1024];
6147             if (net_boot & (1 << i)) {
6148                 if (model == NULL)
6149                     model = "ne2k_pci";
6150                 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
6151                 if (get_image_size(buf) > 0) {
6152                     if (nb_option_roms >= MAX_OPTION_ROMS) {
6153                         fprintf(stderr, "Too many option ROMs\n");
6154                         exit(1);
6155                     }
6156                     option_rom[nb_option_roms] = strdup(buf);
6157                     nb_option_roms++;
6158                     netroms++;
6159                 }
6160             }
6161         }
6162         if (netroms == 0) {
6163             fprintf(stderr, "No valid PXE rom found for network device\n");
6164             exit(1);
6165         }
6166     }
6167 #endif
6168
6169     /* init the memory */
6170     phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
6171
6172     if (machine->ram_require & RAMSIZE_FIXED) {
6173         if (ram_size > 0) {
6174             if (ram_size < phys_ram_size) {
6175                 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
6176                                 machine->name, (unsigned long long) phys_ram_size);
6177                 exit(-1);
6178             }
6179
6180             phys_ram_size = ram_size;
6181         } else
6182             ram_size = phys_ram_size;
6183     } else {
6184         if (ram_size == 0)
6185             ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6186
6187         phys_ram_size += ram_size;
6188     }
6189
6190     phys_ram_base = qemu_vmalloc(phys_ram_size);
6191     if (!phys_ram_base) {
6192         fprintf(stderr, "Could not allocate physical memory\n");
6193         exit(1);
6194     }
6195
6196     /* init the dynamic translator */
6197     cpu_exec_init_all(tb_size * 1024 * 1024);
6198
6199     bdrv_init();
6200
6201     /* we always create the cdrom drive, even if no disk is there */
6202
6203     if (nb_drives_opt < MAX_DRIVES)
6204         drive_add(NULL, CDROM_ALIAS);
6205
6206     /* we always create at least one floppy */
6207
6208     if (nb_drives_opt < MAX_DRIVES)
6209         drive_add(NULL, FD_ALIAS, 0);
6210
6211     /* we always create one sd slot, even if no card is in it */
6212
6213     if (nb_drives_opt < MAX_DRIVES)
6214         drive_add(NULL, SD_ALIAS);
6215
6216     /* open the virtual block devices */
6217
6218     for(i = 0; i < nb_drives_opt; i++)
6219         if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6220             exit(1);
6221
6222     register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6223     register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6224
6225     /* terminal init */
6226     memset(&display_state, 0, sizeof(display_state));
6227     if (nographic) {
6228         if (curses) {
6229             fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
6230             exit(1);
6231         }
6232         /* nearly nothing to do */
6233         dumb_display_init(ds);
6234     } else if (vnc_display != NULL) {
6235         vnc_display_init(ds);
6236         if (vnc_display_open(ds, vnc_display) < 0)
6237             exit(1);
6238     } else
6239 #if defined(CONFIG_CURSES)
6240     if (curses) {
6241         curses_display_init(ds, full_screen);
6242     } else
6243 #endif
6244     {
6245 #if defined(CONFIG_SDL)
6246         sdl_display_init(ds, full_screen, no_frame);
6247 #elif defined(CONFIG_COCOA)
6248         cocoa_display_init(ds, full_screen);
6249 #else
6250         dumb_display_init(ds);
6251 #endif
6252     }
6253
6254 #ifndef _WIN32
6255     /* must be after terminal init, SDL library changes signal handlers */
6256     termsig_setup();
6257 #endif
6258
6259     /* Maintain compatibility with multiple stdio monitors */
6260     if (!strcmp(monitor_device,"stdio")) {
6261         for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6262             const char *devname = serial_devices[i];
6263             if (devname && !strcmp(devname,"mon:stdio")) {
6264                 monitor_device = NULL;
6265                 break;
6266             } else if (devname && !strcmp(devname,"stdio")) {
6267                 monitor_device = NULL;
6268                 serial_devices[i] = "mon:stdio";
6269                 break;
6270             }
6271         }
6272     }
6273     if (monitor_device) {
6274         monitor_hd = qemu_chr_open("monitor", monitor_device);
6275         if (!monitor_hd) {
6276             fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6277             exit(1);
6278         }
6279         monitor_init(monitor_hd, !nographic);
6280     }
6281
6282     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6283         const char *devname = serial_devices[i];
6284         if (devname && strcmp(devname, "none")) {
6285             char label[32];
6286             snprintf(label, sizeof(label), "serial%d", i);
6287             serial_hds[i] = qemu_chr_open(label, devname);
6288             if (!serial_hds[i]) {
6289                 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6290                         devname);
6291                 exit(1);
6292             }
6293             if (strstart(devname, "vc", 0))
6294                 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6295         }
6296     }
6297
6298     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6299         const char *devname = parallel_devices[i];
6300         if (devname && strcmp(devname, "none")) {
6301             char label[32];
6302             snprintf(label, sizeof(label), "parallel%d", i);
6303             parallel_hds[i] = qemu_chr_open(label, devname);
6304             if (!parallel_hds[i]) {
6305                 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6306                         devname);
6307                 exit(1);
6308             }
6309             if (strstart(devname, "vc", 0))
6310                 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6311         }
6312     }
6313
6314     if (kvm_enabled()) {
6315         int ret;
6316
6317         ret = kvm_init(smp_cpus);
6318         if (ret < 0) {
6319             fprintf(stderr, "failed to initialize KVM\n");
6320             exit(1);
6321         }
6322     }
6323
6324     machine->init(ram_size, vga_ram_size, boot_devices, ds,
6325                   kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6326
6327     /* init USB devices */
6328     if (usb_enabled) {
6329         for(i = 0; i < usb_devices_index; i++) {
6330             if (usb_device_add(usb_devices[i]) < 0) {
6331                 fprintf(stderr, "Warning: could not add USB device %s\n",
6332                         usb_devices[i]);
6333             }
6334         }
6335     }
6336
6337     if (display_state.dpy_refresh) {
6338         display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
6339         qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
6340     }
6341
6342 #ifdef CONFIG_GDBSTUB
6343     if (use_gdbstub) {
6344         /* XXX: use standard host:port notation and modify options
6345            accordingly. */
6346         if (gdbserver_start(gdbstub_port) < 0) {
6347             fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6348                     gdbstub_port);
6349             exit(1);
6350         }
6351     }
6352 #endif
6353
6354     if (loadvm)
6355         do_loadvm(loadvm);
6356
6357     if (incoming) {
6358         autostart = 0; /* fixme how to deal with -daemonize */
6359         qemu_start_incoming_migration(incoming);
6360     }
6361
6362     {
6363         /* XXX: simplify init */
6364         read_passwords();
6365         if (autostart) {
6366             vm_start();
6367         }
6368     }
6369
6370     if (daemonize) {
6371         uint8_t status = 0;
6372         ssize_t len;
6373         int fd;
6374
6375     again1:
6376         len = write(fds[1], &status, 1);
6377         if (len == -1 && (errno == EINTR))
6378             goto again1;
6379
6380         if (len != 1)
6381             exit(1);
6382
6383         chdir("/");
6384         TFR(fd = open("/dev/null", O_RDWR));
6385         if (fd == -1)
6386             exit(1);
6387
6388         dup2(fd, 0);
6389         dup2(fd, 1);
6390         dup2(fd, 2);
6391
6392         close(fd);
6393     }
6394
6395     main_loop();
6396     quit_timers();
6397     net_cleanup();
6398
6399     return 0;
6400 }