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