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