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