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