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