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