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