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