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