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