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