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