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