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