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