Fix some win32 compile warnings
[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     int use_gdbstub;
4237     const char *gdbstub_port;
4238 #endif
4239     uint32_t boot_devices_bitmap = 0;
4240     int i;
4241     int snapshot, linux_boot, net_boot;
4242     const char *initrd_filename;
4243     const char *kernel_filename, *kernel_cmdline;
4244     const char *boot_devices = "";
4245     DisplayState *ds;
4246     DisplayChangeListener *dcl;
4247     int cyls, heads, secs, translation;
4248     const char *net_clients[MAX_NET_CLIENTS];
4249     int nb_net_clients;
4250     const char *bt_opts[MAX_BT_CMDLINE];
4251     int nb_bt_opts;
4252     int hda_index;
4253     int optind;
4254     const char *r, *optarg;
4255     CharDriverState *monitor_hd = NULL;
4256     const char *monitor_device;
4257     const char *serial_devices[MAX_SERIAL_PORTS];
4258     int serial_device_index;
4259     const char *parallel_devices[MAX_PARALLEL_PORTS];
4260     int parallel_device_index;
4261     const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4262     int virtio_console_index;
4263     const char *loadvm = NULL;
4264     QEMUMachine *machine;
4265     const char *cpu_model;
4266     const char *usb_devices[MAX_USB_CMDLINE];
4267     int usb_devices_index;
4268 #ifndef _WIN32
4269     int fds[2];
4270 #endif
4271     int tb_size;
4272     const char *pid_file = NULL;
4273     const char *incoming = NULL;
4274 #ifndef _WIN32
4275     int fd = 0;
4276     struct passwd *pwd = NULL;
4277     const char *chroot_dir = NULL;
4278     const char *run_as = NULL;
4279 #endif
4280
4281     qemu_cache_utils_init(envp);
4282
4283     LIST_INIT (&vm_change_state_head);
4284 #ifndef _WIN32
4285     {
4286         struct sigaction act;
4287         sigfillset(&act.sa_mask);
4288         act.sa_flags = 0;
4289         act.sa_handler = SIG_IGN;
4290         sigaction(SIGPIPE, &act, NULL);
4291     }
4292 #else
4293     SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4294     /* Note: cpu_interrupt() is currently not SMP safe, so we force
4295        QEMU to run on a single CPU */
4296     {
4297         HANDLE h;
4298         DWORD mask, smask;
4299         int i;
4300         h = GetCurrentProcess();
4301         if (GetProcessAffinityMask(h, &mask, &smask)) {
4302             for(i = 0; i < 32; i++) {
4303                 if (mask & (1 << i))
4304                     break;
4305             }
4306             if (i != 32) {
4307                 mask = 1 << i;
4308                 SetProcessAffinityMask(h, mask);
4309             }
4310         }
4311     }
4312 #endif
4313
4314     register_machines();
4315     machine = first_machine;
4316     cpu_model = NULL;
4317     initrd_filename = NULL;
4318     ram_size = 0;
4319     vga_ram_size = VGA_RAM_SIZE;
4320 #ifdef CONFIG_GDBSTUB
4321     use_gdbstub = 0;
4322     gdbstub_port = DEFAULT_GDBSTUB_PORT;
4323 #endif
4324     snapshot = 0;
4325     nographic = 0;
4326     curses = 0;
4327     kernel_filename = NULL;
4328     kernel_cmdline = "";
4329     cyls = heads = secs = 0;
4330     translation = BIOS_ATA_TRANSLATION_AUTO;
4331     monitor_device = "vc:80Cx24C";
4332
4333     serial_devices[0] = "vc:80Cx24C";
4334     for(i = 1; i < MAX_SERIAL_PORTS; i++)
4335         serial_devices[i] = NULL;
4336     serial_device_index = 0;
4337
4338     parallel_devices[0] = "vc:80Cx24C";
4339     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4340         parallel_devices[i] = NULL;
4341     parallel_device_index = 0;
4342
4343     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4344         virtio_consoles[i] = NULL;
4345     virtio_console_index = 0;
4346
4347     usb_devices_index = 0;
4348
4349     nb_net_clients = 0;
4350     nb_bt_opts = 0;
4351     nb_drives = 0;
4352     nb_drives_opt = 0;
4353     hda_index = -1;
4354
4355     nb_nics = 0;
4356
4357     tb_size = 0;
4358     autostart= 1;
4359
4360     optind = 1;
4361     for(;;) {
4362         if (optind >= argc)
4363             break;
4364         r = argv[optind];
4365         if (r[0] != '-') {
4366             hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4367         } else {
4368             const QEMUOption *popt;
4369
4370             optind++;
4371             /* Treat --foo the same as -foo.  */
4372             if (r[1] == '-')
4373                 r++;
4374             popt = qemu_options;
4375             for(;;) {
4376                 if (!popt->name) {
4377                     fprintf(stderr, "%s: invalid option -- '%s'\n",
4378                             argv[0], r);
4379                     exit(1);
4380                 }
4381                 if (!strcmp(popt->name, r + 1))
4382                     break;
4383                 popt++;
4384             }
4385             if (popt->flags & HAS_ARG) {
4386                 if (optind >= argc) {
4387                     fprintf(stderr, "%s: option '%s' requires an argument\n",
4388                             argv[0], r);
4389                     exit(1);
4390                 }
4391                 optarg = argv[optind++];
4392             } else {
4393                 optarg = NULL;
4394             }
4395
4396             switch(popt->index) {
4397             case QEMU_OPTION_M:
4398                 machine = find_machine(optarg);
4399                 if (!machine) {
4400                     QEMUMachine *m;
4401                     printf("Supported machines are:\n");
4402                     for(m = first_machine; m != NULL; m = m->next) {
4403                         printf("%-10s %s%s\n",
4404                                m->name, m->desc,
4405                                m == first_machine ? " (default)" : "");
4406                     }
4407                     exit(*optarg != '?');
4408                 }
4409                 break;
4410             case QEMU_OPTION_cpu:
4411                 /* hw initialization will check this */
4412                 if (*optarg == '?') {
4413 /* XXX: implement xxx_cpu_list for targets that still miss it */
4414 #if defined(cpu_list)
4415                     cpu_list(stdout, &fprintf);
4416 #endif
4417                     exit(0);
4418                 } else {
4419                     cpu_model = optarg;
4420                 }
4421                 break;
4422             case QEMU_OPTION_initrd:
4423                 initrd_filename = optarg;
4424                 break;
4425             case QEMU_OPTION_hda:
4426                 if (cyls == 0)
4427                     hda_index = drive_add(optarg, HD_ALIAS, 0);
4428                 else
4429                     hda_index = drive_add(optarg, HD_ALIAS
4430                              ",cyls=%d,heads=%d,secs=%d%s",
4431                              0, cyls, heads, secs,
4432                              translation == BIOS_ATA_TRANSLATION_LBA ?
4433                                  ",trans=lba" :
4434                              translation == BIOS_ATA_TRANSLATION_NONE ?
4435                                  ",trans=none" : "");
4436                  break;
4437             case QEMU_OPTION_hdb:
4438             case QEMU_OPTION_hdc:
4439             case QEMU_OPTION_hdd:
4440                 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4441                 break;
4442             case QEMU_OPTION_drive:
4443                 drive_add(NULL, "%s", optarg);
4444                 break;
4445             case QEMU_OPTION_mtdblock:
4446                 drive_add(optarg, MTD_ALIAS);
4447                 break;
4448             case QEMU_OPTION_sd:
4449                 drive_add(optarg, SD_ALIAS);
4450                 break;
4451             case QEMU_OPTION_pflash:
4452                 drive_add(optarg, PFLASH_ALIAS);
4453                 break;
4454             case QEMU_OPTION_snapshot:
4455                 snapshot = 1;
4456                 break;
4457             case QEMU_OPTION_hdachs:
4458                 {
4459                     const char *p;
4460                     p = optarg;
4461                     cyls = strtol(p, (char **)&p, 0);
4462                     if (cyls < 1 || cyls > 16383)
4463                         goto chs_fail;
4464                     if (*p != ',')
4465                         goto chs_fail;
4466                     p++;
4467                     heads = strtol(p, (char **)&p, 0);
4468                     if (heads < 1 || heads > 16)
4469                         goto chs_fail;
4470                     if (*p != ',')
4471                         goto chs_fail;
4472                     p++;
4473                     secs = strtol(p, (char **)&p, 0);
4474                     if (secs < 1 || secs > 63)
4475                         goto chs_fail;
4476                     if (*p == ',') {
4477                         p++;
4478                         if (!strcmp(p, "none"))
4479                             translation = BIOS_ATA_TRANSLATION_NONE;
4480                         else if (!strcmp(p, "lba"))
4481                             translation = BIOS_ATA_TRANSLATION_LBA;
4482                         else if (!strcmp(p, "auto"))
4483                             translation = BIOS_ATA_TRANSLATION_AUTO;
4484                         else
4485                             goto chs_fail;
4486                     } else if (*p != '\0') {
4487                     chs_fail:
4488                         fprintf(stderr, "qemu: invalid physical CHS format\n");
4489                         exit(1);
4490                     }
4491                     if (hda_index != -1)
4492                         snprintf(drives_opt[hda_index].opt,
4493                                  sizeof(drives_opt[hda_index].opt),
4494                                  HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4495                                  0, cyls, heads, secs,
4496                                  translation == BIOS_ATA_TRANSLATION_LBA ?
4497                                     ",trans=lba" :
4498                                  translation == BIOS_ATA_TRANSLATION_NONE ?
4499                                      ",trans=none" : "");
4500                 }
4501                 break;
4502             case QEMU_OPTION_nographic:
4503                 nographic = 1;
4504                 break;
4505 #ifdef CONFIG_CURSES
4506             case QEMU_OPTION_curses:
4507                 curses = 1;
4508                 break;
4509 #endif
4510             case QEMU_OPTION_portrait:
4511                 graphic_rotate = 1;
4512                 break;
4513             case QEMU_OPTION_kernel:
4514                 kernel_filename = optarg;
4515                 break;
4516             case QEMU_OPTION_append:
4517                 kernel_cmdline = optarg;
4518                 break;
4519             case QEMU_OPTION_cdrom:
4520                 drive_add(optarg, CDROM_ALIAS);
4521                 break;
4522             case QEMU_OPTION_boot:
4523                 boot_devices = optarg;
4524                 /* We just do some generic consistency checks */
4525                 {
4526                     /* Could easily be extended to 64 devices if needed */
4527                     const char *p;
4528                     
4529                     boot_devices_bitmap = 0;
4530                     for (p = boot_devices; *p != '\0'; p++) {
4531                         /* Allowed boot devices are:
4532                          * a b     : floppy disk drives
4533                          * c ... f : IDE disk drives
4534                          * g ... m : machine implementation dependant drives
4535                          * n ... p : network devices
4536                          * It's up to each machine implementation to check
4537                          * if the given boot devices match the actual hardware
4538                          * implementation and firmware features.
4539                          */
4540                         if (*p < 'a' || *p > 'q') {
4541                             fprintf(stderr, "Invalid boot device '%c'\n", *p);
4542                             exit(1);
4543                         }
4544                         if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4545                             fprintf(stderr,
4546                                     "Boot device '%c' was given twice\n",*p);
4547                             exit(1);
4548                         }
4549                         boot_devices_bitmap |= 1 << (*p - 'a');
4550                     }
4551                 }
4552                 break;
4553             case QEMU_OPTION_fda:
4554             case QEMU_OPTION_fdb:
4555                 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4556                 break;
4557 #ifdef TARGET_I386
4558             case QEMU_OPTION_no_fd_bootchk:
4559                 fd_bootchk = 0;
4560                 break;
4561 #endif
4562             case QEMU_OPTION_net:
4563                 if (nb_net_clients >= MAX_NET_CLIENTS) {
4564                     fprintf(stderr, "qemu: too many network clients\n");
4565                     exit(1);
4566                 }
4567                 net_clients[nb_net_clients] = optarg;
4568                 nb_net_clients++;
4569                 break;
4570 #ifdef CONFIG_SLIRP
4571             case QEMU_OPTION_tftp:
4572                 tftp_prefix = optarg;
4573                 break;
4574             case QEMU_OPTION_bootp:
4575                 bootp_filename = optarg;
4576                 break;
4577 #ifndef _WIN32
4578             case QEMU_OPTION_smb:
4579                 net_slirp_smb(optarg);
4580                 break;
4581 #endif
4582             case QEMU_OPTION_redir:
4583                 net_slirp_redir(optarg);
4584                 break;
4585 #endif
4586             case QEMU_OPTION_bt:
4587                 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4588                     fprintf(stderr, "qemu: too many bluetooth options\n");
4589                     exit(1);
4590                 }
4591                 bt_opts[nb_bt_opts++] = optarg;
4592                 break;
4593 #ifdef HAS_AUDIO
4594             case QEMU_OPTION_audio_help:
4595                 AUD_help ();
4596                 exit (0);
4597                 break;
4598             case QEMU_OPTION_soundhw:
4599                 select_soundhw (optarg);
4600                 break;
4601 #endif
4602             case QEMU_OPTION_h:
4603                 help(0);
4604                 break;
4605             case QEMU_OPTION_m: {
4606                 uint64_t value;
4607                 char *ptr;
4608
4609                 value = strtoul(optarg, &ptr, 10);
4610                 switch (*ptr) {
4611                 case 0: case 'M': case 'm':
4612                     value <<= 20;
4613                     break;
4614                 case 'G': case 'g':
4615                     value <<= 30;
4616                     break;
4617                 default:
4618                     fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4619                     exit(1);
4620                 }
4621
4622                 /* On 32-bit hosts, QEMU is limited by virtual address space */
4623                 if (value > (2047 << 20)
4624 #ifndef USE_KQEMU
4625                     && HOST_LONG_BITS == 32
4626 #endif
4627                     ) {
4628                     fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4629                     exit(1);
4630                 }
4631                 if (value != (uint64_t)(ram_addr_t)value) {
4632                     fprintf(stderr, "qemu: ram size too large\n");
4633                     exit(1);
4634                 }
4635                 ram_size = value;
4636                 break;
4637             }
4638             case QEMU_OPTION_d:
4639                 {
4640                     int mask;
4641                     const CPULogItem *item;
4642
4643                     mask = cpu_str_to_log_mask(optarg);
4644                     if (!mask) {
4645                         printf("Log items (comma separated):\n");
4646                     for(item = cpu_log_items; item->mask != 0; item++) {
4647                         printf("%-10s %s\n", item->name, item->help);
4648                     }
4649                     exit(1);
4650                     }
4651                     cpu_set_log(mask);
4652                 }
4653                 break;
4654 #ifdef CONFIG_GDBSTUB
4655             case QEMU_OPTION_s:
4656                 use_gdbstub = 1;
4657                 break;
4658             case QEMU_OPTION_p:
4659                 gdbstub_port = optarg;
4660                 break;
4661 #endif
4662             case QEMU_OPTION_L:
4663                 bios_dir = optarg;
4664                 break;
4665             case QEMU_OPTION_bios:
4666                 bios_name = optarg;
4667                 break;
4668             case QEMU_OPTION_S:
4669                 autostart = 0;
4670                 break;
4671 #ifndef _WIN32
4672             case QEMU_OPTION_k:
4673                 keyboard_layout = optarg;
4674                 break;
4675 #endif
4676             case QEMU_OPTION_localtime:
4677                 rtc_utc = 0;
4678                 break;
4679             case QEMU_OPTION_vga:
4680                 select_vgahw (optarg);
4681                 break;
4682 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4683             case QEMU_OPTION_g:
4684                 {
4685                     const char *p;
4686                     int w, h, depth;
4687                     p = optarg;
4688                     w = strtol(p, (char **)&p, 10);
4689                     if (w <= 0) {
4690                     graphic_error:
4691                         fprintf(stderr, "qemu: invalid resolution or depth\n");
4692                         exit(1);
4693                     }
4694                     if (*p != 'x')
4695                         goto graphic_error;
4696                     p++;
4697                     h = strtol(p, (char **)&p, 10);
4698                     if (h <= 0)
4699                         goto graphic_error;
4700                     if (*p == 'x') {
4701                         p++;
4702                         depth = strtol(p, (char **)&p, 10);
4703                         if (depth != 8 && depth != 15 && depth != 16 &&
4704                             depth != 24 && depth != 32)
4705                             goto graphic_error;
4706                     } else if (*p == '\0') {
4707                         depth = graphic_depth;
4708                     } else {
4709                         goto graphic_error;
4710                     }
4711
4712                     graphic_width = w;
4713                     graphic_height = h;
4714                     graphic_depth = depth;
4715                 }
4716                 break;
4717 #endif
4718             case QEMU_OPTION_echr:
4719                 {
4720                     char *r;
4721                     term_escape_char = strtol(optarg, &r, 0);
4722                     if (r == optarg)
4723                         printf("Bad argument to echr\n");
4724                     break;
4725                 }
4726             case QEMU_OPTION_monitor:
4727                 monitor_device = optarg;
4728                 break;
4729             case QEMU_OPTION_serial:
4730                 if (serial_device_index >= MAX_SERIAL_PORTS) {
4731                     fprintf(stderr, "qemu: too many serial ports\n");
4732                     exit(1);
4733                 }
4734                 serial_devices[serial_device_index] = optarg;
4735                 serial_device_index++;
4736                 break;
4737             case QEMU_OPTION_virtiocon:
4738                 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
4739                     fprintf(stderr, "qemu: too many virtio consoles\n");
4740                     exit(1);
4741                 }
4742                 virtio_consoles[virtio_console_index] = optarg;
4743                 virtio_console_index++;
4744                 break;
4745             case QEMU_OPTION_parallel:
4746                 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4747                     fprintf(stderr, "qemu: too many parallel ports\n");
4748                     exit(1);
4749                 }
4750                 parallel_devices[parallel_device_index] = optarg;
4751                 parallel_device_index++;
4752                 break;
4753             case QEMU_OPTION_loadvm:
4754                 loadvm = optarg;
4755                 break;
4756             case QEMU_OPTION_full_screen:
4757                 full_screen = 1;
4758                 break;
4759 #ifdef CONFIG_SDL
4760             case QEMU_OPTION_no_frame:
4761                 no_frame = 1;
4762                 break;
4763             case QEMU_OPTION_alt_grab:
4764                 alt_grab = 1;
4765                 break;
4766             case QEMU_OPTION_no_quit:
4767                 no_quit = 1;
4768                 break;
4769             case QEMU_OPTION_sdl:
4770                 sdl = 1;
4771                 break;
4772 #endif
4773             case QEMU_OPTION_pidfile:
4774                 pid_file = optarg;
4775                 break;
4776 #ifdef TARGET_I386
4777             case QEMU_OPTION_win2k_hack:
4778                 win2k_install_hack = 1;
4779                 break;
4780             case QEMU_OPTION_rtc_td_hack:
4781                 rtc_td_hack = 1;
4782                 break;
4783             case QEMU_OPTION_acpitable:
4784                 if(acpi_table_add(optarg) < 0) {
4785                     fprintf(stderr, "Wrong acpi table provided\n");
4786                     exit(1);
4787                 }
4788                 break;
4789 #endif
4790 #ifdef USE_KQEMU
4791             case QEMU_OPTION_no_kqemu:
4792                 kqemu_allowed = 0;
4793                 break;
4794             case QEMU_OPTION_kernel_kqemu:
4795                 kqemu_allowed = 2;
4796                 break;
4797 #endif
4798 #ifdef CONFIG_KVM
4799             case QEMU_OPTION_enable_kvm:
4800                 kvm_allowed = 1;
4801 #ifdef USE_KQEMU
4802                 kqemu_allowed = 0;
4803 #endif
4804                 break;
4805 #endif
4806             case QEMU_OPTION_usb:
4807                 usb_enabled = 1;
4808                 break;
4809             case QEMU_OPTION_usbdevice:
4810                 usb_enabled = 1;
4811                 if (usb_devices_index >= MAX_USB_CMDLINE) {
4812                     fprintf(stderr, "Too many USB devices\n");
4813                     exit(1);
4814                 }
4815                 usb_devices[usb_devices_index] = optarg;
4816                 usb_devices_index++;
4817                 break;
4818             case QEMU_OPTION_smp:
4819                 smp_cpus = atoi(optarg);
4820                 if (smp_cpus < 1) {
4821                     fprintf(stderr, "Invalid number of CPUs\n");
4822                     exit(1);
4823                 }
4824                 break;
4825             case QEMU_OPTION_vnc:
4826                 vnc_display = optarg;
4827                 break;
4828 #ifdef TARGET_I386
4829             case QEMU_OPTION_no_acpi:
4830                 acpi_enabled = 0;
4831                 break;
4832             case QEMU_OPTION_no_hpet:
4833                 no_hpet = 1;
4834                 break;
4835 #endif
4836             case QEMU_OPTION_no_reboot:
4837                 no_reboot = 1;
4838                 break;
4839             case QEMU_OPTION_no_shutdown:
4840                 no_shutdown = 1;
4841                 break;
4842             case QEMU_OPTION_show_cursor:
4843                 cursor_hide = 0;
4844                 break;
4845             case QEMU_OPTION_uuid:
4846                 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4847                     fprintf(stderr, "Fail to parse UUID string."
4848                             " Wrong format.\n");
4849                     exit(1);
4850                 }
4851                 break;
4852 #ifndef _WIN32
4853             case QEMU_OPTION_daemonize:
4854                 daemonize = 1;
4855                 break;
4856 #endif
4857             case QEMU_OPTION_option_rom:
4858                 if (nb_option_roms >= MAX_OPTION_ROMS) {
4859                     fprintf(stderr, "Too many option ROMs\n");
4860                     exit(1);
4861                 }
4862                 option_rom[nb_option_roms] = optarg;
4863                 nb_option_roms++;
4864                 break;
4865 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4866             case QEMU_OPTION_semihosting:
4867                 semihosting_enabled = 1;
4868                 break;
4869 #endif
4870             case QEMU_OPTION_name:
4871                 qemu_name = optarg;
4872                 break;
4873 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4874             case QEMU_OPTION_prom_env:
4875                 if (nb_prom_envs >= MAX_PROM_ENVS) {
4876                     fprintf(stderr, "Too many prom variables\n");
4877                     exit(1);
4878                 }
4879                 prom_envs[nb_prom_envs] = optarg;
4880                 nb_prom_envs++;
4881                 break;
4882 #endif
4883 #ifdef TARGET_ARM
4884             case QEMU_OPTION_old_param:
4885                 old_param = 1;
4886                 break;
4887 #endif
4888             case QEMU_OPTION_clock:
4889                 configure_alarms(optarg);
4890                 break;
4891             case QEMU_OPTION_startdate:
4892                 {
4893                     struct tm tm;
4894                     time_t rtc_start_date;
4895                     if (!strcmp(optarg, "now")) {
4896                         rtc_date_offset = -1;
4897                     } else {
4898                         if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
4899                                &tm.tm_year,
4900                                &tm.tm_mon,
4901                                &tm.tm_mday,
4902                                &tm.tm_hour,
4903                                &tm.tm_min,
4904                                &tm.tm_sec) == 6) {
4905                             /* OK */
4906                         } else if (sscanf(optarg, "%d-%d-%d",
4907                                           &tm.tm_year,
4908                                           &tm.tm_mon,
4909                                           &tm.tm_mday) == 3) {
4910                             tm.tm_hour = 0;
4911                             tm.tm_min = 0;
4912                             tm.tm_sec = 0;
4913                         } else {
4914                             goto date_fail;
4915                         }
4916                         tm.tm_year -= 1900;
4917                         tm.tm_mon--;
4918                         rtc_start_date = mktimegm(&tm);
4919                         if (rtc_start_date == -1) {
4920                         date_fail:
4921                             fprintf(stderr, "Invalid date format. Valid format are:\n"
4922                                     "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
4923                             exit(1);
4924                         }
4925                         rtc_date_offset = time(NULL) - rtc_start_date;
4926                     }
4927                 }
4928                 break;
4929             case QEMU_OPTION_tb_size:
4930                 tb_size = strtol(optarg, NULL, 0);
4931                 if (tb_size < 0)
4932                     tb_size = 0;
4933                 break;
4934             case QEMU_OPTION_icount:
4935                 use_icount = 1;
4936                 if (strcmp(optarg, "auto") == 0) {
4937                     icount_time_shift = -1;
4938                 } else {
4939                     icount_time_shift = strtol(optarg, NULL, 0);
4940                 }
4941                 break;
4942             case QEMU_OPTION_incoming:
4943                 incoming = optarg;
4944                 break;
4945 #ifndef _WIN32
4946             case QEMU_OPTION_chroot:
4947                 chroot_dir = optarg;
4948                 break;
4949             case QEMU_OPTION_runas:
4950                 run_as = optarg;
4951                 break;
4952 #endif
4953             }
4954         }
4955     }
4956
4957 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
4958     if (kvm_allowed && kqemu_allowed) {
4959         fprintf(stderr,
4960                 "You can not enable both KVM and kqemu at the same time\n");
4961         exit(1);
4962     }
4963 #endif
4964
4965     machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4966     if (smp_cpus > machine->max_cpus) {
4967         fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4968                 "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
4969                 machine->max_cpus);
4970         exit(1);
4971     }
4972
4973     if (nographic) {
4974        if (serial_device_index == 0)
4975            serial_devices[0] = "stdio";
4976        if (parallel_device_index == 0)
4977            parallel_devices[0] = "null";
4978        if (strncmp(monitor_device, "vc", 2) == 0)
4979            monitor_device = "stdio";
4980     }
4981
4982 #ifndef _WIN32
4983     if (daemonize) {
4984         pid_t pid;
4985
4986         if (pipe(fds) == -1)
4987             exit(1);
4988
4989         pid = fork();
4990         if (pid > 0) {
4991             uint8_t status;
4992             ssize_t len;
4993
4994             close(fds[1]);
4995
4996         again:
4997             len = read(fds[0], &status, 1);
4998             if (len == -1 && (errno == EINTR))
4999                 goto again;
5000
5001             if (len != 1)
5002                 exit(1);
5003             else if (status == 1) {
5004                 fprintf(stderr, "Could not acquire pidfile\n");
5005                 exit(1);
5006             } else
5007                 exit(0);
5008         } else if (pid < 0)
5009             exit(1);
5010
5011         setsid();
5012
5013         pid = fork();
5014         if (pid > 0)
5015             exit(0);
5016         else if (pid < 0)
5017             exit(1);
5018
5019         umask(027);
5020
5021         signal(SIGTSTP, SIG_IGN);
5022         signal(SIGTTOU, SIG_IGN);
5023         signal(SIGTTIN, SIG_IGN);
5024     }
5025
5026     if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5027         if (daemonize) {
5028             uint8_t status = 1;
5029             write(fds[1], &status, 1);
5030         } else
5031             fprintf(stderr, "Could not acquire pid file\n");
5032         exit(1);
5033     }
5034 #endif
5035
5036 #ifdef USE_KQEMU
5037     if (smp_cpus > 1)
5038         kqemu_allowed = 0;
5039 #endif
5040     linux_boot = (kernel_filename != NULL);
5041     net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5042
5043     if (!linux_boot && *kernel_cmdline != '\0') {
5044         fprintf(stderr, "-append only allowed with -kernel option\n");
5045         exit(1);
5046     }
5047
5048     if (!linux_boot && initrd_filename != NULL) {
5049         fprintf(stderr, "-initrd only allowed with -kernel option\n");
5050         exit(1);
5051     }
5052
5053     /* boot to floppy or the default cd if no hard disk defined yet */
5054     if (!boot_devices[0]) {
5055         boot_devices = "cad";
5056     }
5057     setvbuf(stdout, NULL, _IOLBF, 0);
5058
5059     init_timers();
5060     if (init_timer_alarm() < 0) {
5061         fprintf(stderr, "could not initialize alarm timer\n");
5062         exit(1);
5063     }
5064     if (use_icount && icount_time_shift < 0) {
5065         use_icount = 2;
5066         /* 125MIPS seems a reasonable initial guess at the guest speed.
5067            It will be corrected fairly quickly anyway.  */
5068         icount_time_shift = 3;
5069         init_icount_adjust();
5070     }
5071
5072 #ifdef _WIN32
5073     socket_init();
5074 #endif
5075
5076     /* init network clients */
5077     if (nb_net_clients == 0) {
5078         /* if no clients, we use a default config */
5079         net_clients[nb_net_clients++] = "nic";
5080 #ifdef CONFIG_SLIRP
5081         net_clients[nb_net_clients++] = "user";
5082 #endif
5083     }
5084
5085     for(i = 0;i < nb_net_clients; i++) {
5086         if (net_client_parse(net_clients[i]) < 0)
5087             exit(1);
5088     }
5089     net_client_check();
5090
5091 #ifdef TARGET_I386
5092     /* XXX: this should be moved in the PC machine instantiation code */
5093     if (net_boot != 0) {
5094         int netroms = 0;
5095         for (i = 0; i < nb_nics && i < 4; i++) {
5096             const char *model = nd_table[i].model;
5097             char buf[1024];
5098             if (net_boot & (1 << i)) {
5099                 if (model == NULL)
5100                     model = "ne2k_pci";
5101                 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5102                 if (get_image_size(buf) > 0) {
5103                     if (nb_option_roms >= MAX_OPTION_ROMS) {
5104                         fprintf(stderr, "Too many option ROMs\n");
5105                         exit(1);
5106                     }
5107                     option_rom[nb_option_roms] = strdup(buf);
5108                     nb_option_roms++;
5109                     netroms++;
5110                 }
5111             }
5112         }
5113         if (netroms == 0) {
5114             fprintf(stderr, "No valid PXE rom found for network device\n");
5115             exit(1);
5116         }
5117     }
5118 #endif
5119
5120     /* init the bluetooth world */
5121     for (i = 0; i < nb_bt_opts; i++)
5122         if (bt_parse(bt_opts[i]))
5123             exit(1);
5124
5125     /* init the memory */
5126     phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5127
5128     if (machine->ram_require & RAMSIZE_FIXED) {
5129         if (ram_size > 0) {
5130             if (ram_size < phys_ram_size) {
5131                 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5132                                 machine->name, (unsigned long long) phys_ram_size);
5133                 exit(-1);
5134             }
5135
5136             phys_ram_size = ram_size;
5137         } else
5138             ram_size = phys_ram_size;
5139     } else {
5140         if (ram_size == 0)
5141             ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5142
5143         phys_ram_size += ram_size;
5144     }
5145
5146     phys_ram_base = qemu_vmalloc(phys_ram_size);
5147     if (!phys_ram_base) {
5148         fprintf(stderr, "Could not allocate physical memory\n");
5149         exit(1);
5150     }
5151
5152     /* init the dynamic translator */
5153     cpu_exec_init_all(tb_size * 1024 * 1024);
5154
5155     bdrv_init();
5156     dma_helper_init();
5157
5158     /* we always create the cdrom drive, even if no disk is there */
5159
5160     if (nb_drives_opt < MAX_DRIVES)
5161         drive_add(NULL, CDROM_ALIAS);
5162
5163     /* we always create at least one floppy */
5164
5165     if (nb_drives_opt < MAX_DRIVES)
5166         drive_add(NULL, FD_ALIAS, 0);
5167
5168     /* we always create one sd slot, even if no card is in it */
5169
5170     if (nb_drives_opt < MAX_DRIVES)
5171         drive_add(NULL, SD_ALIAS);
5172
5173     /* open the virtual block devices */
5174
5175     for(i = 0; i < nb_drives_opt; i++)
5176         if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5177             exit(1);
5178
5179     register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5180     register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5181
5182 #ifndef _WIN32
5183     /* must be after terminal init, SDL library changes signal handlers */
5184     termsig_setup();
5185 #endif
5186
5187     /* Maintain compatibility with multiple stdio monitors */
5188     if (!strcmp(monitor_device,"stdio")) {
5189         for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5190             const char *devname = serial_devices[i];
5191             if (devname && !strcmp(devname,"mon:stdio")) {
5192                 monitor_device = NULL;
5193                 break;
5194             } else if (devname && !strcmp(devname,"stdio")) {
5195                 monitor_device = NULL;
5196                 serial_devices[i] = "mon:stdio";
5197                 break;
5198             }
5199         }
5200     }
5201
5202     if (kvm_enabled()) {
5203         int ret;
5204
5205         ret = kvm_init(smp_cpus);
5206         if (ret < 0) {
5207             fprintf(stderr, "failed to initialize KVM\n");
5208             exit(1);
5209         }
5210     }
5211
5212     if (monitor_device) {
5213         monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5214         if (!monitor_hd) {
5215             fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5216             exit(1);
5217         }
5218     }
5219
5220     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5221         const char *devname = serial_devices[i];
5222         if (devname && strcmp(devname, "none")) {
5223             char label[32];
5224             snprintf(label, sizeof(label), "serial%d", i);
5225             serial_hds[i] = qemu_chr_open(label, devname, NULL);
5226             if (!serial_hds[i]) {
5227                 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5228                         devname);
5229                 exit(1);
5230             }
5231         }
5232     }
5233
5234     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5235         const char *devname = parallel_devices[i];
5236         if (devname && strcmp(devname, "none")) {
5237             char label[32];
5238             snprintf(label, sizeof(label), "parallel%d", i);
5239             parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5240             if (!parallel_hds[i]) {
5241                 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5242                         devname);
5243                 exit(1);
5244             }
5245         }
5246     }
5247
5248     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5249         const char *devname = virtio_consoles[i];
5250         if (devname && strcmp(devname, "none")) {
5251             char label[32];
5252             snprintf(label, sizeof(label), "virtcon%d", i);
5253             virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5254             if (!virtcon_hds[i]) {
5255                 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5256                         devname);
5257                 exit(1);
5258             }
5259         }
5260     }
5261
5262     machine->init(ram_size, vga_ram_size, boot_devices,
5263                   kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5264
5265     current_machine = machine;
5266
5267     /* Set KVM's vcpu state to qemu's initial CPUState. */
5268     if (kvm_enabled()) {
5269         int ret;
5270
5271         ret = kvm_sync_vcpus();
5272         if (ret < 0) {
5273             fprintf(stderr, "failed to initialize vcpus\n");
5274             exit(1);
5275         }
5276     }
5277
5278     /* init USB devices */
5279     if (usb_enabled) {
5280         for(i = 0; i < usb_devices_index; i++) {
5281             if (usb_device_add(usb_devices[i], 0) < 0) {
5282                 fprintf(stderr, "Warning: could not add USB device %s\n",
5283                         usb_devices[i]);
5284             }
5285         }
5286     }
5287
5288     if (!display_state)
5289         dumb_display_init();
5290     /* just use the first displaystate for the moment */
5291     ds = display_state;
5292     /* terminal init */
5293     if (nographic) {
5294         if (curses) {
5295             fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5296             exit(1);
5297         }
5298     } else { 
5299 #if defined(CONFIG_CURSES)
5300             if (curses) {
5301                 /* At the moment curses cannot be used with other displays */
5302                 curses_display_init(ds, full_screen);
5303             } else
5304 #endif
5305             {
5306                 if (vnc_display != NULL) {
5307                     vnc_display_init(ds);
5308                     if (vnc_display_open(ds, vnc_display) < 0)
5309                         exit(1);
5310                 }
5311 #if defined(CONFIG_SDL)
5312                 if (sdl || !vnc_display)
5313                     sdl_display_init(ds, full_screen, no_frame);
5314 #elif defined(CONFIG_COCOA)
5315                 if (sdl || !vnc_display)
5316                     cocoa_display_init(ds, full_screen);
5317 #endif
5318             }
5319     }
5320     dpy_resize(ds);
5321
5322     dcl = ds->listeners;
5323     while (dcl != NULL) {
5324         if (dcl->dpy_refresh != NULL) {
5325             ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5326             qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5327         }
5328         dcl = dcl->next;
5329     }
5330
5331     if (nographic || (vnc_display && !sdl)) {
5332         nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5333         qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5334     }
5335
5336     text_consoles_set_display(display_state);
5337     qemu_chr_initial_reset();
5338
5339     if (monitor_device && monitor_hd)
5340         monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5341
5342     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5343         const char *devname = serial_devices[i];
5344         if (devname && strcmp(devname, "none")) {
5345             char label[32];
5346             snprintf(label, sizeof(label), "serial%d", i);
5347             if (strstart(devname, "vc", 0))
5348                 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5349         }
5350     }
5351
5352     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5353         const char *devname = parallel_devices[i];
5354         if (devname && strcmp(devname, "none")) {
5355             char label[32];
5356             snprintf(label, sizeof(label), "parallel%d", i);
5357             if (strstart(devname, "vc", 0))
5358                 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5359         }
5360     }
5361
5362     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5363         const char *devname = virtio_consoles[i];
5364         if (virtcon_hds[i] && devname) {
5365             char label[32];
5366             snprintf(label, sizeof(label), "virtcon%d", i);
5367             if (strstart(devname, "vc", 0))
5368                 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5369         }
5370     }
5371
5372 #ifdef CONFIG_GDBSTUB
5373     if (use_gdbstub) {
5374         /* XXX: use standard host:port notation and modify options
5375            accordingly. */
5376         if (gdbserver_start(gdbstub_port) < 0) {
5377             fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5378                     gdbstub_port);
5379             exit(1);
5380         }
5381     }
5382 #endif
5383
5384     if (loadvm)
5385         do_loadvm(cur_mon, loadvm);
5386
5387     if (incoming) {
5388         autostart = 0; /* fixme how to deal with -daemonize */
5389         qemu_start_incoming_migration(incoming);
5390     }
5391
5392     if (autostart)
5393         vm_start();
5394
5395 #ifndef _WIN32
5396     if (daemonize) {
5397         uint8_t status = 0;
5398         ssize_t len;
5399
5400     again1:
5401         len = write(fds[1], &status, 1);
5402         if (len == -1 && (errno == EINTR))
5403             goto again1;
5404
5405         if (len != 1)
5406             exit(1);
5407
5408         chdir("/");
5409         TFR(fd = open("/dev/null", O_RDWR));
5410         if (fd == -1)
5411             exit(1);
5412     }
5413
5414     if (run_as) {
5415         pwd = getpwnam(run_as);
5416         if (!pwd) {
5417             fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5418             exit(1);
5419         }
5420     }
5421
5422     if (chroot_dir) {
5423         if (chroot(chroot_dir) < 0) {
5424             fprintf(stderr, "chroot failed\n");
5425             exit(1);
5426         }
5427         chdir("/");
5428     }
5429
5430     if (run_as) {
5431         if (setgid(pwd->pw_gid) < 0) {
5432             fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5433             exit(1);
5434         }
5435         if (setuid(pwd->pw_uid) < 0) {
5436             fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5437             exit(1);
5438         }
5439         if (setuid(0) != -1) {
5440             fprintf(stderr, "Dropping privileges failed\n");
5441             exit(1);
5442         }
5443     }
5444
5445     if (daemonize) {
5446         dup2(fd, 0);
5447         dup2(fd, 1);
5448         dup2(fd, 2);
5449
5450         close(fd);
5451     }
5452 #endif
5453
5454     main_loop();
5455     quit_timers();
5456     net_cleanup();
5457
5458     return 0;
5459 }