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