Merge commit 'f6f3fbcab0c36f17ea63573ed4d21816a09c978e' into upstream-merge
[qemu-kvm/amd-iommu.git] / vl.c
blobef840d7adf03037c0fd99ee2307f2c5a6389bc02
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
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>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
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>
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"
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
94 #if defined(__OpenBSD__)
95 #include <util.h>
96 #endif
98 #if defined(CONFIG_VDE)
99 #include <libvdeplug.h>
100 #endif
102 #ifdef _WIN32
103 #include <windows.h>
104 #include <mmsystem.h>
105 #endif
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)
113 return qemu_main(argc, argv, NULL);
115 #undef main
116 #define main qemu_main
117 #endif
118 #endif /* CONFIG_SDL */
120 #ifdef CONFIG_COCOA
121 #undef main
122 #define main qemu_main
123 #endif /* CONFIG_COCOA */
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 #include "qemu-kvm.h"
161 #include "hw/device-assignment.h"
163 #include "disas.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
171 #include "qemu-queue.h"
173 //#define DEBUG_NET
174 //#define DEBUG_SLIRP
176 #define DEFAULT_RAM_SIZE 128
178 #define MAX_VIRTIO_CONSOLES 1
180 static const char *data_dir;
181 const char *bios_name = NULL;
182 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
183 to store the VM snapshots */
184 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
185 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
186 DriveInfo *extboot_drive = NULL;
187 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
188 static DisplayState *display_state;
189 DisplayType display_type = DT_DEFAULT;
190 const char* keyboard_layout = NULL;
191 ram_addr_t ram_size;
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 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
224 int assigned_devices_index;
225 int smp_cpus = 1;
226 int max_cpus = 0;
227 int smp_cores = 1;
228 int smp_threads = 1;
229 const char *vnc_display;
230 int acpi_enabled = 1;
231 #ifdef TARGET_I386
232 int no_hpet = 0;
233 #endif
234 int fd_bootchk = 1;
235 int no_reboot = 0;
236 int no_shutdown = 0;
237 int cursor_hide = 1;
238 int graphic_rotate = 0;
239 uint8_t irq0override = 1;
240 #ifndef _WIN32
241 int daemonize = 0;
242 #endif
243 const char *watchdog;
244 const char *option_rom[MAX_OPTION_ROMS];
245 int nb_option_roms;
246 int semihosting_enabled = 0;
247 int time_drift_fix = 0;
248 unsigned int kvm_shadow_memory = 0;
249 const char *mem_path = NULL;
250 #ifdef MAP_POPULATE
251 int mem_prealloc = 1; /* force preallocation of physical target memory */
252 #endif
253 #ifdef TARGET_ARM
254 int old_param = 0;
255 #endif
256 const char *qemu_name;
257 int alt_grab = 0;
258 int ctrl_grab = 0;
259 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
260 unsigned int nb_prom_envs = 0;
261 const char *prom_envs[MAX_PROM_ENVS];
262 #endif
263 const char *nvram = NULL;
264 int boot_menu;
266 int nb_numa_nodes;
267 uint64_t node_mem[MAX_NODES];
268 uint64_t node_cpumask[MAX_NODES];
270 static CPUState *cur_cpu;
271 static CPUState *next_cpu;
272 static int timer_alarm_pending = 1;
273 /* Conversion factor from emulated instructions to virtual clock ticks. */
274 static int icount_time_shift;
275 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
276 #define MAX_ICOUNT_SHIFT 10
277 /* Compensate for varying guest execution speed. */
278 static int64_t qemu_icount_bias;
279 static QEMUTimer *icount_rt_timer;
280 static QEMUTimer *icount_vm_timer;
281 static QEMUTimer *nographic_timer;
283 uint8_t qemu_uuid[16];
285 static QEMUBootSetHandler *boot_set_handler;
286 static void *boot_set_opaque;
288 static int default_serial = 1;
289 static int default_parallel = 1;
290 static int default_virtcon = 1;
291 static int default_monitor = 1;
292 static int default_vga = 1;
293 static int default_floppy = 1;
294 static int default_cdrom = 1;
295 static int default_sdcard = 1;
297 static struct {
298 const char *driver;
299 int *flag;
300 } default_list[] = {
301 { .driver = "isa-serial", .flag = &default_serial },
302 { .driver = "isa-parallel", .flag = &default_parallel },
303 { .driver = "isa-fdc", .flag = &default_floppy },
304 { .driver = "ide-drive", .flag = &default_cdrom },
305 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
306 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
307 { .driver = "virtio-serial", .flag = &default_virtcon },
308 { .driver = "VGA", .flag = &default_vga },
309 { .driver = "cirrus-vga", .flag = &default_vga },
310 { .driver = "vmware-svga", .flag = &default_vga },
313 static int default_driver_check(QemuOpts *opts, void *opaque)
315 const char *driver = qemu_opt_get(opts, "driver");
316 int i;
318 if (!driver)
319 return 0;
320 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
321 if (strcmp(default_list[i].driver, driver) != 0)
322 continue;
323 *(default_list[i].flag) = 0;
325 return 0;
328 /***********************************************************/
329 /* x86 ISA bus support */
331 target_phys_addr_t isa_mem_base = 0;
332 PicState2 *isa_pic;
334 /***********************************************************/
335 void hw_error(const char *fmt, ...)
337 va_list ap;
338 CPUState *env;
340 va_start(ap, fmt);
341 fprintf(stderr, "qemu: hardware error: ");
342 vfprintf(stderr, fmt, ap);
343 fprintf(stderr, "\n");
344 for(env = first_cpu; env != NULL; env = env->next_cpu) {
345 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
346 #ifdef TARGET_I386
347 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
348 #else
349 cpu_dump_state(env, stderr, fprintf, 0);
350 #endif
352 va_end(ap);
353 abort();
356 static void set_proc_name(const char *s)
358 #if defined(__linux__) && defined(PR_SET_NAME)
359 char name[16];
360 if (!s)
361 return;
362 name[sizeof(name) - 1] = 0;
363 strncpy(name, s, sizeof(name));
364 /* Could rewrite argv[0] too, but that's a bit more complicated.
365 This simple way is enough for `top'. */
366 prctl(PR_SET_NAME, name);
367 #endif
370 /***************/
371 /* ballooning */
373 static QEMUBalloonEvent *qemu_balloon_event;
374 void *qemu_balloon_event_opaque;
376 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
378 qemu_balloon_event = func;
379 qemu_balloon_event_opaque = opaque;
382 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
384 if (qemu_balloon_event) {
385 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
386 return 1;
387 } else {
388 return 0;
392 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
394 if (qemu_balloon_event) {
395 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
396 return 1;
397 } else {
398 return 0;
403 /***********************************************************/
404 /* real time host monotonic timer */
406 /* compute with 96 bit intermediate result: (a*b)/c */
407 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
409 union {
410 uint64_t ll;
411 struct {
412 #ifdef HOST_WORDS_BIGENDIAN
413 uint32_t high, low;
414 #else
415 uint32_t low, high;
416 #endif
417 } l;
418 } u, res;
419 uint64_t rl, rh;
421 u.ll = a;
422 rl = (uint64_t)u.l.low * (uint64_t)b;
423 rh = (uint64_t)u.l.high * (uint64_t)b;
424 rh += (rl >> 32);
425 res.l.high = rh / c;
426 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
427 return res.ll;
430 static int64_t get_clock_realtime(void)
432 struct timeval tv;
434 gettimeofday(&tv, NULL);
435 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
438 #ifdef WIN32
440 static int64_t clock_freq;
442 static void init_get_clock(void)
444 LARGE_INTEGER freq;
445 int ret;
446 ret = QueryPerformanceFrequency(&freq);
447 if (ret == 0) {
448 fprintf(stderr, "Could not calibrate ticks\n");
449 exit(1);
451 clock_freq = freq.QuadPart;
454 static int64_t get_clock(void)
456 LARGE_INTEGER ti;
457 QueryPerformanceCounter(&ti);
458 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
461 #else
463 static int use_rt_clock;
465 static void init_get_clock(void)
467 use_rt_clock = 0;
468 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
469 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
471 struct timespec ts;
472 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
473 use_rt_clock = 1;
476 #endif
479 static int64_t get_clock(void)
481 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
482 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
483 if (use_rt_clock) {
484 struct timespec ts;
485 clock_gettime(CLOCK_MONOTONIC, &ts);
486 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
487 } else
488 #endif
490 /* XXX: using gettimeofday leads to problems if the date
491 changes, so it should be avoided. */
492 return get_clock_realtime();
495 #endif
497 /* Return the virtual CPU time, based on the instruction counter. */
498 static int64_t cpu_get_icount(void)
500 int64_t icount;
501 CPUState *env = cpu_single_env;;
502 icount = qemu_icount;
503 if (env) {
504 if (!can_do_io(env))
505 fprintf(stderr, "Bad clock read\n");
506 icount -= (env->icount_decr.u16.low + env->icount_extra);
508 return qemu_icount_bias + (icount << icount_time_shift);
511 /***********************************************************/
512 /* guest cycle counter */
514 typedef struct TimersState {
515 int64_t cpu_ticks_prev;
516 int64_t cpu_ticks_offset;
517 int64_t cpu_clock_offset;
518 int32_t cpu_ticks_enabled;
519 int64_t dummy;
520 } TimersState;
522 TimersState timers_state;
524 /* return the host CPU cycle counter and handle stop/restart */
525 int64_t cpu_get_ticks(void)
527 if (use_icount) {
528 return cpu_get_icount();
530 if (!timers_state.cpu_ticks_enabled) {
531 return timers_state.cpu_ticks_offset;
532 } else {
533 int64_t ticks;
534 ticks = cpu_get_real_ticks();
535 if (timers_state.cpu_ticks_prev > ticks) {
536 /* Note: non increasing ticks may happen if the host uses
537 software suspend */
538 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
540 timers_state.cpu_ticks_prev = ticks;
541 return ticks + timers_state.cpu_ticks_offset;
545 /* return the host CPU monotonic timer and handle stop/restart */
546 static int64_t cpu_get_clock(void)
548 int64_t ti;
549 if (!timers_state.cpu_ticks_enabled) {
550 return timers_state.cpu_clock_offset;
551 } else {
552 ti = get_clock();
553 return ti + timers_state.cpu_clock_offset;
557 /* enable cpu_get_ticks() */
558 void cpu_enable_ticks(void)
560 if (!timers_state.cpu_ticks_enabled) {
561 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
562 timers_state.cpu_clock_offset -= get_clock();
563 timers_state.cpu_ticks_enabled = 1;
567 /* disable cpu_get_ticks() : the clock is stopped. You must not call
568 cpu_get_ticks() after that. */
569 void cpu_disable_ticks(void)
571 if (timers_state.cpu_ticks_enabled) {
572 timers_state.cpu_ticks_offset = cpu_get_ticks();
573 timers_state.cpu_clock_offset = cpu_get_clock();
574 timers_state.cpu_ticks_enabled = 0;
578 /***********************************************************/
579 /* timers */
581 #define QEMU_CLOCK_REALTIME 0
582 #define QEMU_CLOCK_VIRTUAL 1
583 #define QEMU_CLOCK_HOST 2
585 struct QEMUClock {
586 int type;
587 /* XXX: add frequency */
590 struct QEMUTimer {
591 QEMUClock *clock;
592 int64_t expire_time;
593 QEMUTimerCB *cb;
594 void *opaque;
595 struct QEMUTimer *next;
598 struct qemu_alarm_timer {
599 char const *name;
600 unsigned int flags;
602 int (*start)(struct qemu_alarm_timer *t);
603 void (*stop)(struct qemu_alarm_timer *t);
604 void (*rearm)(struct qemu_alarm_timer *t);
605 void *priv;
608 #define ALARM_FLAG_DYNTICKS 0x1
609 #define ALARM_FLAG_EXPIRED 0x2
611 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
613 return t && (t->flags & ALARM_FLAG_DYNTICKS);
616 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
618 if (!alarm_has_dynticks(t))
619 return;
621 t->rearm(t);
624 /* TODO: MIN_TIMER_REARM_US should be optimized */
625 #define MIN_TIMER_REARM_US 250
627 static struct qemu_alarm_timer *alarm_timer;
629 #ifdef _WIN32
631 struct qemu_alarm_win32 {
632 MMRESULT timerId;
633 unsigned int period;
634 } alarm_win32_data = {0, -1};
636 static int win32_start_timer(struct qemu_alarm_timer *t);
637 static void win32_stop_timer(struct qemu_alarm_timer *t);
638 static void win32_rearm_timer(struct qemu_alarm_timer *t);
640 #else
642 static int unix_start_timer(struct qemu_alarm_timer *t);
643 static void unix_stop_timer(struct qemu_alarm_timer *t);
645 #ifdef __linux__
647 static int dynticks_start_timer(struct qemu_alarm_timer *t);
648 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
649 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
651 static int hpet_start_timer(struct qemu_alarm_timer *t);
652 static void hpet_stop_timer(struct qemu_alarm_timer *t);
654 static int rtc_start_timer(struct qemu_alarm_timer *t);
655 static void rtc_stop_timer(struct qemu_alarm_timer *t);
657 #endif /* __linux__ */
659 #endif /* _WIN32 */
661 /* Correlation between real and virtual time is always going to be
662 fairly approximate, so ignore small variation.
663 When the guest is idle real and virtual time will be aligned in
664 the IO wait loop. */
665 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
667 static void icount_adjust(void)
669 int64_t cur_time;
670 int64_t cur_icount;
671 int64_t delta;
672 static int64_t last_delta;
673 /* If the VM is not running, then do nothing. */
674 if (!vm_running)
675 return;
677 cur_time = cpu_get_clock();
678 cur_icount = qemu_get_clock(vm_clock);
679 delta = cur_icount - cur_time;
680 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
681 if (delta > 0
682 && last_delta + ICOUNT_WOBBLE < delta * 2
683 && icount_time_shift > 0) {
684 /* The guest is getting too far ahead. Slow time down. */
685 icount_time_shift--;
687 if (delta < 0
688 && last_delta - ICOUNT_WOBBLE > delta * 2
689 && icount_time_shift < MAX_ICOUNT_SHIFT) {
690 /* The guest is getting too far behind. Speed time up. */
691 icount_time_shift++;
693 last_delta = delta;
694 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
697 static void icount_adjust_rt(void * opaque)
699 qemu_mod_timer(icount_rt_timer,
700 qemu_get_clock(rt_clock) + 1000);
701 icount_adjust();
704 static void icount_adjust_vm(void * opaque)
706 qemu_mod_timer(icount_vm_timer,
707 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
708 icount_adjust();
711 static void init_icount_adjust(void)
713 /* Have both realtime and virtual time triggers for speed adjustment.
714 The realtime trigger catches emulated time passing too slowly,
715 the virtual time trigger catches emulated time passing too fast.
716 Realtime triggers occur even when idle, so use them less frequently
717 than VM triggers. */
718 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
719 qemu_mod_timer(icount_rt_timer,
720 qemu_get_clock(rt_clock) + 1000);
721 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
722 qemu_mod_timer(icount_vm_timer,
723 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
726 static struct qemu_alarm_timer alarm_timers[] = {
727 #ifndef _WIN32
728 #ifdef __linux__
729 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
730 dynticks_stop_timer, dynticks_rearm_timer, NULL},
731 /* HPET - if available - is preferred */
732 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
733 /* ...otherwise try RTC */
734 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
735 #endif
736 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
737 #else
738 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
739 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
740 {"win32", 0, win32_start_timer,
741 win32_stop_timer, NULL, &alarm_win32_data},
742 #endif
743 {NULL, }
746 static void show_available_alarms(void)
748 int i;
750 printf("Available alarm timers, in order of precedence:\n");
751 for (i = 0; alarm_timers[i].name; i++)
752 printf("%s\n", alarm_timers[i].name);
755 static void configure_alarms(char const *opt)
757 int i;
758 int cur = 0;
759 int count = ARRAY_SIZE(alarm_timers) - 1;
760 char *arg;
761 char *name;
762 struct qemu_alarm_timer tmp;
764 if (!strcmp(opt, "?")) {
765 show_available_alarms();
766 exit(0);
769 arg = qemu_strdup(opt);
771 /* Reorder the array */
772 name = strtok(arg, ",");
773 while (name) {
774 for (i = 0; i < count && alarm_timers[i].name; i++) {
775 if (!strcmp(alarm_timers[i].name, name))
776 break;
779 if (i == count) {
780 fprintf(stderr, "Unknown clock %s\n", name);
781 goto next;
784 if (i < cur)
785 /* Ignore */
786 goto next;
788 /* Swap */
789 tmp = alarm_timers[i];
790 alarm_timers[i] = alarm_timers[cur];
791 alarm_timers[cur] = tmp;
793 cur++;
794 next:
795 name = strtok(NULL, ",");
798 qemu_free(arg);
800 if (cur) {
801 /* Disable remaining timers */
802 for (i = cur; i < count; i++)
803 alarm_timers[i].name = NULL;
804 } else {
805 show_available_alarms();
806 exit(1);
810 #define QEMU_NUM_CLOCKS 3
812 QEMUClock *rt_clock;
813 QEMUClock *vm_clock;
814 QEMUClock *host_clock;
816 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
818 static QEMUClock *qemu_new_clock(int type)
820 QEMUClock *clock;
821 clock = qemu_mallocz(sizeof(QEMUClock));
822 clock->type = type;
823 return clock;
826 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
828 QEMUTimer *ts;
830 ts = qemu_mallocz(sizeof(QEMUTimer));
831 ts->clock = clock;
832 ts->cb = cb;
833 ts->opaque = opaque;
834 return ts;
837 void qemu_free_timer(QEMUTimer *ts)
839 qemu_free(ts);
842 /* stop a timer, but do not dealloc it */
843 void qemu_del_timer(QEMUTimer *ts)
845 QEMUTimer **pt, *t;
847 /* NOTE: this code must be signal safe because
848 qemu_timer_expired() can be called from a signal. */
849 pt = &active_timers[ts->clock->type];
850 for(;;) {
851 t = *pt;
852 if (!t)
853 break;
854 if (t == ts) {
855 *pt = t->next;
856 break;
858 pt = &t->next;
862 /* modify the current timer so that it will be fired when current_time
863 >= expire_time. The corresponding callback will be called. */
864 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
866 QEMUTimer **pt, *t;
868 qemu_del_timer(ts);
870 /* add the timer in the sorted list */
871 /* NOTE: this code must be signal safe because
872 qemu_timer_expired() can be called from a signal. */
873 pt = &active_timers[ts->clock->type];
874 for(;;) {
875 t = *pt;
876 if (!t)
877 break;
878 if (t->expire_time > expire_time)
879 break;
880 pt = &t->next;
882 ts->expire_time = expire_time;
883 ts->next = *pt;
884 *pt = ts;
886 /* Rearm if necessary */
887 if (pt == &active_timers[ts->clock->type]) {
888 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
889 qemu_rearm_alarm_timer(alarm_timer);
891 /* Interrupt execution to force deadline recalculation. */
892 if (use_icount)
893 qemu_notify_event();
897 int qemu_timer_pending(QEMUTimer *ts)
899 QEMUTimer *t;
900 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
901 if (t == ts)
902 return 1;
904 return 0;
907 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
909 if (!timer_head)
910 return 0;
911 return (timer_head->expire_time <= current_time);
914 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
916 QEMUTimer *ts;
918 for(;;) {
919 ts = *ptimer_head;
920 if (!ts || ts->expire_time > current_time)
921 break;
922 /* remove timer from the list before calling the callback */
923 *ptimer_head = ts->next;
924 ts->next = NULL;
926 /* run the callback (the timer list can be modified) */
927 ts->cb(ts->opaque);
931 int64_t qemu_get_clock(QEMUClock *clock)
933 switch(clock->type) {
934 case QEMU_CLOCK_REALTIME:
935 return get_clock() / 1000000;
936 default:
937 case QEMU_CLOCK_VIRTUAL:
938 if (use_icount) {
939 return cpu_get_icount();
940 } else {
941 return cpu_get_clock();
943 case QEMU_CLOCK_HOST:
944 return get_clock_realtime();
948 static void init_clocks(void)
950 init_get_clock();
951 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
952 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
953 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
955 rtc_clock = host_clock;
958 /* save a timer */
959 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
961 uint64_t expire_time;
963 if (qemu_timer_pending(ts)) {
964 expire_time = ts->expire_time;
965 } else {
966 expire_time = -1;
968 qemu_put_be64(f, expire_time);
971 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
973 uint64_t expire_time;
975 expire_time = qemu_get_be64(f);
976 if (expire_time != -1) {
977 qemu_mod_timer(ts, expire_time);
978 } else {
979 qemu_del_timer(ts);
983 static const VMStateDescription vmstate_timers = {
984 .name = "timer",
985 .version_id = 2,
986 .minimum_version_id = 1,
987 .minimum_version_id_old = 1,
988 .fields = (VMStateField []) {
989 VMSTATE_INT64(cpu_ticks_offset, TimersState),
990 VMSTATE_INT64(dummy, TimersState),
991 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
992 VMSTATE_END_OF_LIST()
996 static void qemu_event_increment(void);
998 #ifdef _WIN32
999 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1000 DWORD_PTR dwUser, DWORD_PTR dw1,
1001 DWORD_PTR dw2)
1002 #else
1003 static void host_alarm_handler(int host_signum)
1004 #endif
1006 #if 0
1007 #define DISP_FREQ 1000
1009 static int64_t delta_min = INT64_MAX;
1010 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1011 static int count;
1012 ti = qemu_get_clock(vm_clock);
1013 if (last_clock != 0) {
1014 delta = ti - last_clock;
1015 if (delta < delta_min)
1016 delta_min = delta;
1017 if (delta > delta_max)
1018 delta_max = delta;
1019 delta_cum += delta;
1020 if (++count == DISP_FREQ) {
1021 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1022 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1023 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1024 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1025 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1026 count = 0;
1027 delta_min = INT64_MAX;
1028 delta_max = 0;
1029 delta_cum = 0;
1032 last_clock = ti;
1034 #endif
1035 if (alarm_has_dynticks(alarm_timer) ||
1036 (!use_icount &&
1037 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1038 qemu_get_clock(vm_clock))) ||
1039 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1040 qemu_get_clock(rt_clock)) ||
1041 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1042 qemu_get_clock(host_clock))) {
1043 qemu_event_increment();
1044 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1046 #ifndef CONFIG_IOTHREAD
1047 if (next_cpu) {
1048 /* stop the currently executing cpu because a timer occured */
1049 cpu_exit(next_cpu);
1051 #endif
1052 timer_alarm_pending = 1;
1053 qemu_notify_event();
1057 static int64_t qemu_next_deadline(void)
1059 /* To avoid problems with overflow limit this to 2^32. */
1060 int64_t delta = INT32_MAX;
1062 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1063 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1064 qemu_get_clock(vm_clock);
1066 if (active_timers[QEMU_CLOCK_HOST]) {
1067 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1068 qemu_get_clock(host_clock);
1069 if (hdelta < delta)
1070 delta = hdelta;
1073 if (delta < 0)
1074 delta = 0;
1076 return delta;
1079 #if defined(__linux__)
1080 static uint64_t qemu_next_deadline_dyntick(void)
1082 int64_t delta;
1083 int64_t rtdelta;
1085 if (use_icount)
1086 delta = INT32_MAX;
1087 else
1088 delta = (qemu_next_deadline() + 999) / 1000;
1090 if (active_timers[QEMU_CLOCK_REALTIME]) {
1091 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1092 qemu_get_clock(rt_clock))*1000;
1093 if (rtdelta < delta)
1094 delta = rtdelta;
1097 if (delta < MIN_TIMER_REARM_US)
1098 delta = MIN_TIMER_REARM_US;
1100 return delta;
1102 #endif
1104 #ifndef _WIN32
1106 /* Sets a specific flag */
1107 static int fcntl_setfl(int fd, int flag)
1109 int flags;
1111 flags = fcntl(fd, F_GETFL);
1112 if (flags == -1)
1113 return -errno;
1115 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1116 return -errno;
1118 return 0;
1121 #if defined(__linux__)
1123 #define RTC_FREQ 1024
1125 static void enable_sigio_timer(int fd)
1127 struct sigaction act;
1129 /* timer signal */
1130 sigfillset(&act.sa_mask);
1131 act.sa_flags = 0;
1132 act.sa_handler = host_alarm_handler;
1134 sigaction(SIGIO, &act, NULL);
1135 fcntl_setfl(fd, O_ASYNC);
1136 fcntl(fd, F_SETOWN, getpid());
1139 static int hpet_start_timer(struct qemu_alarm_timer *t)
1141 struct hpet_info info;
1142 int r, fd;
1144 fd = qemu_open("/dev/hpet", O_RDONLY);
1145 if (fd < 0)
1146 return -1;
1148 /* Set frequency */
1149 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1150 if (r < 0) {
1151 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1152 "error, but for better emulation accuracy type:\n"
1153 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1154 goto fail;
1157 /* Check capabilities */
1158 r = ioctl(fd, HPET_INFO, &info);
1159 if (r < 0)
1160 goto fail;
1162 /* Enable periodic mode */
1163 r = ioctl(fd, HPET_EPI, 0);
1164 if (info.hi_flags && (r < 0))
1165 goto fail;
1167 /* Enable interrupt */
1168 r = ioctl(fd, HPET_IE_ON, 0);
1169 if (r < 0)
1170 goto fail;
1172 enable_sigio_timer(fd);
1173 t->priv = (void *)(long)fd;
1175 return 0;
1176 fail:
1177 close(fd);
1178 return -1;
1181 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1183 int fd = (long)t->priv;
1185 close(fd);
1188 static int rtc_start_timer(struct qemu_alarm_timer *t)
1190 int rtc_fd;
1191 unsigned long current_rtc_freq = 0;
1193 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1194 if (rtc_fd < 0)
1195 return -1;
1196 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1197 if (current_rtc_freq != RTC_FREQ &&
1198 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1199 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1200 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1201 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1202 goto fail;
1204 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1205 fail:
1206 close(rtc_fd);
1207 return -1;
1210 enable_sigio_timer(rtc_fd);
1212 t->priv = (void *)(long)rtc_fd;
1214 return 0;
1217 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1219 int rtc_fd = (long)t->priv;
1221 close(rtc_fd);
1224 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1226 struct sigevent ev;
1227 timer_t host_timer;
1228 struct sigaction act;
1230 sigfillset(&act.sa_mask);
1231 act.sa_flags = 0;
1232 act.sa_handler = host_alarm_handler;
1234 sigaction(SIGALRM, &act, NULL);
1237 * Initialize ev struct to 0 to avoid valgrind complaining
1238 * about uninitialized data in timer_create call
1240 memset(&ev, 0, sizeof(ev));
1241 ev.sigev_value.sival_int = 0;
1242 ev.sigev_notify = SIGEV_SIGNAL;
1243 ev.sigev_signo = SIGALRM;
1245 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1246 perror("timer_create");
1248 /* disable dynticks */
1249 fprintf(stderr, "Dynamic Ticks disabled\n");
1251 return -1;
1254 t->priv = (void *)(long)host_timer;
1256 return 0;
1259 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1261 timer_t host_timer = (timer_t)(long)t->priv;
1263 timer_delete(host_timer);
1266 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1268 timer_t host_timer = (timer_t)(long)t->priv;
1269 struct itimerspec timeout;
1270 int64_t nearest_delta_us = INT64_MAX;
1271 int64_t current_us;
1273 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1274 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1275 !active_timers[QEMU_CLOCK_HOST])
1276 return;
1278 nearest_delta_us = qemu_next_deadline_dyntick();
1280 /* check whether a timer is already running */
1281 if (timer_gettime(host_timer, &timeout)) {
1282 perror("gettime");
1283 fprintf(stderr, "Internal timer error: aborting\n");
1284 exit(1);
1286 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1287 if (current_us && current_us <= nearest_delta_us)
1288 return;
1290 timeout.it_interval.tv_sec = 0;
1291 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1292 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1293 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1294 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1295 perror("settime");
1296 fprintf(stderr, "Internal timer error: aborting\n");
1297 exit(1);
1301 #endif /* defined(__linux__) */
1303 static int unix_start_timer(struct qemu_alarm_timer *t)
1305 struct sigaction act;
1306 struct itimerval itv;
1307 int err;
1309 /* timer signal */
1310 sigfillset(&act.sa_mask);
1311 act.sa_flags = 0;
1312 act.sa_handler = host_alarm_handler;
1314 sigaction(SIGALRM, &act, NULL);
1316 itv.it_interval.tv_sec = 0;
1317 /* for i386 kernel 2.6 to get 1 ms */
1318 itv.it_interval.tv_usec = 999;
1319 itv.it_value.tv_sec = 0;
1320 itv.it_value.tv_usec = 10 * 1000;
1322 err = setitimer(ITIMER_REAL, &itv, NULL);
1323 if (err)
1324 return -1;
1326 return 0;
1329 static void unix_stop_timer(struct qemu_alarm_timer *t)
1331 struct itimerval itv;
1333 memset(&itv, 0, sizeof(itv));
1334 setitimer(ITIMER_REAL, &itv, NULL);
1337 #endif /* !defined(_WIN32) */
1340 #ifdef _WIN32
1342 static int win32_start_timer(struct qemu_alarm_timer *t)
1344 TIMECAPS tc;
1345 struct qemu_alarm_win32 *data = t->priv;
1346 UINT flags;
1348 memset(&tc, 0, sizeof(tc));
1349 timeGetDevCaps(&tc, sizeof(tc));
1351 if (data->period < tc.wPeriodMin)
1352 data->period = tc.wPeriodMin;
1354 timeBeginPeriod(data->period);
1356 flags = TIME_CALLBACK_FUNCTION;
1357 if (alarm_has_dynticks(t))
1358 flags |= TIME_ONESHOT;
1359 else
1360 flags |= TIME_PERIODIC;
1362 data->timerId = timeSetEvent(1, // interval (ms)
1363 data->period, // resolution
1364 host_alarm_handler, // function
1365 (DWORD)t, // parameter
1366 flags);
1368 if (!data->timerId) {
1369 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1370 GetLastError());
1371 timeEndPeriod(data->period);
1372 return -1;
1375 return 0;
1378 static void win32_stop_timer(struct qemu_alarm_timer *t)
1380 struct qemu_alarm_win32 *data = t->priv;
1382 timeKillEvent(data->timerId);
1383 timeEndPeriod(data->period);
1386 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1388 struct qemu_alarm_win32 *data = t->priv;
1390 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1391 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1392 !active_timers[QEMU_CLOCK_HOST])
1393 return;
1395 timeKillEvent(data->timerId);
1397 data->timerId = timeSetEvent(1,
1398 data->period,
1399 host_alarm_handler,
1400 (DWORD)t,
1401 TIME_ONESHOT | TIME_PERIODIC);
1403 if (!data->timerId) {
1404 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1405 GetLastError());
1407 timeEndPeriod(data->period);
1408 exit(1);
1412 #endif /* _WIN32 */
1414 static int init_timer_alarm(void)
1416 struct qemu_alarm_timer *t = NULL;
1417 int i, err = -1;
1419 for (i = 0; alarm_timers[i].name; i++) {
1420 t = &alarm_timers[i];
1422 err = t->start(t);
1423 if (!err)
1424 break;
1427 if (err) {
1428 err = -ENOENT;
1429 goto fail;
1432 alarm_timer = t;
1434 return 0;
1436 fail:
1437 return err;
1440 static void quit_timers(void)
1442 alarm_timer->stop(alarm_timer);
1443 alarm_timer = NULL;
1446 /***********************************************************/
1447 /* host time/date access */
1448 void qemu_get_timedate(struct tm *tm, int offset)
1450 time_t ti;
1451 struct tm *ret;
1453 time(&ti);
1454 ti += offset;
1455 if (rtc_date_offset == -1) {
1456 if (rtc_utc)
1457 ret = gmtime(&ti);
1458 else
1459 ret = localtime(&ti);
1460 } else {
1461 ti -= rtc_date_offset;
1462 ret = gmtime(&ti);
1465 memcpy(tm, ret, sizeof(struct tm));
1468 int qemu_timedate_diff(struct tm *tm)
1470 time_t seconds;
1472 if (rtc_date_offset == -1)
1473 if (rtc_utc)
1474 seconds = mktimegm(tm);
1475 else
1476 seconds = mktime(tm);
1477 else
1478 seconds = mktimegm(tm) + rtc_date_offset;
1480 return seconds - time(NULL);
1483 static void configure_rtc_date_offset(const char *startdate, int legacy)
1485 time_t rtc_start_date;
1486 struct tm tm;
1488 if (!strcmp(startdate, "now") && legacy) {
1489 rtc_date_offset = -1;
1490 } else {
1491 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1492 &tm.tm_year,
1493 &tm.tm_mon,
1494 &tm.tm_mday,
1495 &tm.tm_hour,
1496 &tm.tm_min,
1497 &tm.tm_sec) == 6) {
1498 /* OK */
1499 } else if (sscanf(startdate, "%d-%d-%d",
1500 &tm.tm_year,
1501 &tm.tm_mon,
1502 &tm.tm_mday) == 3) {
1503 tm.tm_hour = 0;
1504 tm.tm_min = 0;
1505 tm.tm_sec = 0;
1506 } else {
1507 goto date_fail;
1509 tm.tm_year -= 1900;
1510 tm.tm_mon--;
1511 rtc_start_date = mktimegm(&tm);
1512 if (rtc_start_date == -1) {
1513 date_fail:
1514 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1515 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1516 exit(1);
1518 rtc_date_offset = time(NULL) - rtc_start_date;
1522 static void configure_rtc(QemuOpts *opts)
1524 const char *value;
1526 value = qemu_opt_get(opts, "base");
1527 if (value) {
1528 if (!strcmp(value, "utc")) {
1529 rtc_utc = 1;
1530 } else if (!strcmp(value, "localtime")) {
1531 rtc_utc = 0;
1532 } else {
1533 configure_rtc_date_offset(value, 0);
1536 value = qemu_opt_get(opts, "clock");
1537 if (value) {
1538 if (!strcmp(value, "host")) {
1539 rtc_clock = host_clock;
1540 } else if (!strcmp(value, "vm")) {
1541 rtc_clock = vm_clock;
1542 } else {
1543 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1544 exit(1);
1547 #ifdef CONFIG_TARGET_I386
1548 value = qemu_opt_get(opts, "driftfix");
1549 if (value) {
1550 if (!strcmp(buf, "slew")) {
1551 rtc_td_hack = 1;
1552 } else if (!strcmp(buf, "none")) {
1553 rtc_td_hack = 0;
1554 } else {
1555 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1556 exit(1);
1559 #endif
1562 #ifdef _WIN32
1563 static void socket_cleanup(void)
1565 WSACleanup();
1568 static int socket_init(void)
1570 WSADATA Data;
1571 int ret, err;
1573 ret = WSAStartup(MAKEWORD(2,2), &Data);
1574 if (ret != 0) {
1575 err = WSAGetLastError();
1576 fprintf(stderr, "WSAStartup: %d\n", err);
1577 return -1;
1579 atexit(socket_cleanup);
1580 return 0;
1582 #endif
1584 /***********************************************************/
1585 /* Bluetooth support */
1586 static int nb_hcis;
1587 static int cur_hci;
1588 static struct HCIInfo *hci_table[MAX_NICS];
1590 static struct bt_vlan_s {
1591 struct bt_scatternet_s net;
1592 int id;
1593 struct bt_vlan_s *next;
1594 } *first_bt_vlan;
1596 /* find or alloc a new bluetooth "VLAN" */
1597 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1599 struct bt_vlan_s **pvlan, *vlan;
1600 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1601 if (vlan->id == id)
1602 return &vlan->net;
1604 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1605 vlan->id = id;
1606 pvlan = &first_bt_vlan;
1607 while (*pvlan != NULL)
1608 pvlan = &(*pvlan)->next;
1609 *pvlan = vlan;
1610 return &vlan->net;
1613 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1617 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1619 return -ENOTSUP;
1622 static struct HCIInfo null_hci = {
1623 .cmd_send = null_hci_send,
1624 .sco_send = null_hci_send,
1625 .acl_send = null_hci_send,
1626 .bdaddr_set = null_hci_addr_set,
1629 struct HCIInfo *qemu_next_hci(void)
1631 if (cur_hci == nb_hcis)
1632 return &null_hci;
1634 return hci_table[cur_hci++];
1637 static struct HCIInfo *hci_init(const char *str)
1639 char *endp;
1640 struct bt_scatternet_s *vlan = 0;
1642 if (!strcmp(str, "null"))
1643 /* null */
1644 return &null_hci;
1645 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1646 /* host[:hciN] */
1647 return bt_host_hci(str[4] ? str + 5 : "hci0");
1648 else if (!strncmp(str, "hci", 3)) {
1649 /* hci[,vlan=n] */
1650 if (str[3]) {
1651 if (!strncmp(str + 3, ",vlan=", 6)) {
1652 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1653 if (*endp)
1654 vlan = 0;
1656 } else
1657 vlan = qemu_find_bt_vlan(0);
1658 if (vlan)
1659 return bt_new_hci(vlan);
1662 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1664 return 0;
1667 static int bt_hci_parse(const char *str)
1669 struct HCIInfo *hci;
1670 bdaddr_t bdaddr;
1672 if (nb_hcis >= MAX_NICS) {
1673 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1674 return -1;
1677 hci = hci_init(str);
1678 if (!hci)
1679 return -1;
1681 bdaddr.b[0] = 0x52;
1682 bdaddr.b[1] = 0x54;
1683 bdaddr.b[2] = 0x00;
1684 bdaddr.b[3] = 0x12;
1685 bdaddr.b[4] = 0x34;
1686 bdaddr.b[5] = 0x56 + nb_hcis;
1687 hci->bdaddr_set(hci, bdaddr.b);
1689 hci_table[nb_hcis++] = hci;
1691 return 0;
1694 static void bt_vhci_add(int vlan_id)
1696 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1698 if (!vlan->slave)
1699 fprintf(stderr, "qemu: warning: adding a VHCI to "
1700 "an empty scatternet %i\n", vlan_id);
1702 bt_vhci_init(bt_new_hci(vlan));
1705 static struct bt_device_s *bt_device_add(const char *opt)
1707 struct bt_scatternet_s *vlan;
1708 int vlan_id = 0;
1709 char *endp = strstr(opt, ",vlan=");
1710 int len = (endp ? endp - opt : strlen(opt)) + 1;
1711 char devname[10];
1713 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1715 if (endp) {
1716 vlan_id = strtol(endp + 6, &endp, 0);
1717 if (*endp) {
1718 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1719 return 0;
1723 vlan = qemu_find_bt_vlan(vlan_id);
1725 if (!vlan->slave)
1726 fprintf(stderr, "qemu: warning: adding a slave device to "
1727 "an empty scatternet %i\n", vlan_id);
1729 if (!strcmp(devname, "keyboard"))
1730 return bt_keyboard_init(vlan);
1732 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1733 return 0;
1736 static int bt_parse(const char *opt)
1738 const char *endp, *p;
1739 int vlan;
1741 if (strstart(opt, "hci", &endp)) {
1742 if (!*endp || *endp == ',') {
1743 if (*endp)
1744 if (!strstart(endp, ",vlan=", 0))
1745 opt = endp + 1;
1747 return bt_hci_parse(opt);
1749 } else if (strstart(opt, "vhci", &endp)) {
1750 if (!*endp || *endp == ',') {
1751 if (*endp) {
1752 if (strstart(endp, ",vlan=", &p)) {
1753 vlan = strtol(p, (char **) &endp, 0);
1754 if (*endp) {
1755 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1756 return 1;
1758 } else {
1759 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1760 return 1;
1762 } else
1763 vlan = 0;
1765 bt_vhci_add(vlan);
1766 return 0;
1768 } else if (strstart(opt, "device:", &endp))
1769 return !bt_device_add(endp);
1771 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1772 return 1;
1775 /***********************************************************/
1776 /* QEMU Block devices */
1778 #define HD_ALIAS "index=%d,media=disk"
1779 #define CDROM_ALIAS "index=2,media=cdrom"
1780 #define FD_ALIAS "index=%d,if=floppy"
1781 #define PFLASH_ALIAS "if=pflash"
1782 #define MTD_ALIAS "if=mtd"
1783 #define SD_ALIAS "index=0,if=sd"
1785 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1787 va_list ap;
1788 char optstr[1024];
1789 QemuOpts *opts;
1791 va_start(ap, fmt);
1792 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1793 va_end(ap);
1795 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1796 if (!opts) {
1797 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1798 __FUNCTION__, optstr);
1799 return NULL;
1801 if (file)
1802 qemu_opt_set(opts, "file", file);
1803 return opts;
1806 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1808 DriveInfo *dinfo;
1810 /* seek interface, bus and unit */
1812 QTAILQ_FOREACH(dinfo, &drives, next) {
1813 if (dinfo->type == type &&
1814 dinfo->bus == bus &&
1815 dinfo->unit == unit)
1816 return dinfo;
1819 return NULL;
1822 DriveInfo *drive_get_by_id(const char *id)
1824 DriveInfo *dinfo;
1826 QTAILQ_FOREACH(dinfo, &drives, next) {
1827 if (strcmp(id, dinfo->id))
1828 continue;
1829 return dinfo;
1831 return NULL;
1834 int drive_get_max_bus(BlockInterfaceType type)
1836 int max_bus;
1837 DriveInfo *dinfo;
1839 max_bus = -1;
1840 QTAILQ_FOREACH(dinfo, &drives, next) {
1841 if(dinfo->type == type &&
1842 dinfo->bus > max_bus)
1843 max_bus = dinfo->bus;
1845 return max_bus;
1848 const char *drive_get_serial(BlockDriverState *bdrv)
1850 DriveInfo *dinfo;
1852 QTAILQ_FOREACH(dinfo, &drives, next) {
1853 if (dinfo->bdrv == bdrv)
1854 return dinfo->serial;
1857 return "\0";
1860 BlockInterfaceErrorAction drive_get_on_error(
1861 BlockDriverState *bdrv, int is_read)
1863 DriveInfo *dinfo;
1865 QTAILQ_FOREACH(dinfo, &drives, next) {
1866 if (dinfo->bdrv == bdrv)
1867 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1870 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1873 static void bdrv_format_print(void *opaque, const char *name)
1875 fprintf(stderr, " %s", name);
1878 void drive_uninit(DriveInfo *dinfo)
1880 qemu_opts_del(dinfo->opts);
1881 bdrv_delete(dinfo->bdrv);
1882 QTAILQ_REMOVE(&drives, dinfo, next);
1883 qemu_free(dinfo);
1886 static int parse_block_error_action(const char *buf, int is_read)
1888 if (!strcmp(buf, "ignore")) {
1889 return BLOCK_ERR_IGNORE;
1890 } else if (!is_read && !strcmp(buf, "enospc")) {
1891 return BLOCK_ERR_STOP_ENOSPC;
1892 } else if (!strcmp(buf, "stop")) {
1893 return BLOCK_ERR_STOP_ANY;
1894 } else if (!strcmp(buf, "report")) {
1895 return BLOCK_ERR_REPORT;
1896 } else {
1897 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1898 buf, is_read ? "read" : "write");
1899 return -1;
1903 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1904 int *fatal_error)
1906 const char *buf;
1907 const char *file = NULL;
1908 char devname[128];
1909 const char *serial;
1910 const char *mediastr = "";
1911 BlockInterfaceType type;
1912 enum { MEDIA_DISK, MEDIA_CDROM } media;
1913 int bus_id, unit_id;
1914 int cyls, heads, secs, translation;
1915 BlockDriver *drv = NULL;
1916 QEMUMachine *machine = opaque;
1917 int max_devs;
1918 int index;
1919 int cache;
1920 int aio = 0;
1921 int ro = 0;
1922 int bdrv_flags;
1923 int on_read_error, on_write_error;
1924 const char *devaddr;
1925 DriveInfo *dinfo;
1926 int is_extboot = 0;
1927 int snapshot = 0;
1929 *fatal_error = 1;
1931 translation = BIOS_ATA_TRANSLATION_AUTO;
1932 cache = 1;
1934 if (machine && machine->use_scsi) {
1935 type = IF_SCSI;
1936 max_devs = MAX_SCSI_DEVS;
1937 pstrcpy(devname, sizeof(devname), "scsi");
1938 } else {
1939 type = IF_IDE;
1940 max_devs = MAX_IDE_DEVS;
1941 pstrcpy(devname, sizeof(devname), "ide");
1943 media = MEDIA_DISK;
1945 /* extract parameters */
1946 bus_id = qemu_opt_get_number(opts, "bus", 0);
1947 unit_id = qemu_opt_get_number(opts, "unit", -1);
1948 index = qemu_opt_get_number(opts, "index", -1);
1950 cyls = qemu_opt_get_number(opts, "cyls", 0);
1951 heads = qemu_opt_get_number(opts, "heads", 0);
1952 secs = qemu_opt_get_number(opts, "secs", 0);
1954 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1955 ro = qemu_opt_get_bool(opts, "readonly", 0);
1957 file = qemu_opt_get(opts, "file");
1958 serial = qemu_opt_get(opts, "serial");
1960 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1961 pstrcpy(devname, sizeof(devname), buf);
1962 if (!strcmp(buf, "ide")) {
1963 type = IF_IDE;
1964 max_devs = MAX_IDE_DEVS;
1965 } else if (!strcmp(buf, "scsi")) {
1966 type = IF_SCSI;
1967 max_devs = MAX_SCSI_DEVS;
1968 } else if (!strcmp(buf, "floppy")) {
1969 type = IF_FLOPPY;
1970 max_devs = 0;
1971 } else if (!strcmp(buf, "pflash")) {
1972 type = IF_PFLASH;
1973 max_devs = 0;
1974 } else if (!strcmp(buf, "mtd")) {
1975 type = IF_MTD;
1976 max_devs = 0;
1977 } else if (!strcmp(buf, "sd")) {
1978 type = IF_SD;
1979 max_devs = 0;
1980 } else if (!strcmp(buf, "virtio")) {
1981 type = IF_VIRTIO;
1982 max_devs = 0;
1983 } else if (!strcmp(buf, "xen")) {
1984 type = IF_XEN;
1985 max_devs = 0;
1986 } else if (!strcmp(buf, "none")) {
1987 type = IF_NONE;
1988 max_devs = 0;
1989 } else {
1990 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1991 return NULL;
1995 if (cyls || heads || secs) {
1996 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
1997 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1998 return NULL;
2000 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2001 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2002 return NULL;
2004 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2005 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2006 return NULL;
2010 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2011 if (!cyls) {
2012 fprintf(stderr,
2013 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2014 buf);
2015 return NULL;
2017 if (!strcmp(buf, "none"))
2018 translation = BIOS_ATA_TRANSLATION_NONE;
2019 else if (!strcmp(buf, "lba"))
2020 translation = BIOS_ATA_TRANSLATION_LBA;
2021 else if (!strcmp(buf, "auto"))
2022 translation = BIOS_ATA_TRANSLATION_AUTO;
2023 else {
2024 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2025 return NULL;
2029 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2030 if (!strcmp(buf, "disk")) {
2031 media = MEDIA_DISK;
2032 } else if (!strcmp(buf, "cdrom")) {
2033 if (cyls || secs || heads) {
2034 fprintf(stderr,
2035 "qemu: '%s' invalid physical CHS format\n", buf);
2036 return NULL;
2038 media = MEDIA_CDROM;
2039 } else {
2040 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2041 return NULL;
2045 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2046 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2047 cache = 0;
2048 else if (!strcmp(buf, "writethrough"))
2049 cache = 1;
2050 else if (!strcmp(buf, "writeback"))
2051 cache = 2;
2052 else {
2053 fprintf(stderr, "qemu: invalid cache option\n");
2054 return NULL;
2058 #ifdef CONFIG_LINUX_AIO
2059 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2060 if (!strcmp(buf, "threads"))
2061 aio = 0;
2062 else if (!strcmp(buf, "native"))
2063 aio = 1;
2064 else {
2065 fprintf(stderr, "qemu: invalid aio option\n");
2066 return NULL;
2069 #endif
2071 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2072 if (strcmp(buf, "?") == 0) {
2073 fprintf(stderr, "qemu: Supported formats:");
2074 bdrv_iterate_format(bdrv_format_print, NULL);
2075 fprintf(stderr, "\n");
2076 return NULL;
2078 drv = bdrv_find_whitelisted_format(buf);
2079 if (!drv) {
2080 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2081 return NULL;
2085 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
2086 if (is_extboot && extboot_drive) {
2087 fprintf(stderr, "qemu: two bootable drives specified\n");
2088 return NULL;
2091 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2092 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2093 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2094 fprintf(stderr, "werror is no supported by this format\n");
2095 return NULL;
2098 on_write_error = parse_block_error_action(buf, 0);
2099 if (on_write_error < 0) {
2100 return NULL;
2104 on_read_error = BLOCK_ERR_REPORT;
2105 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2106 if (type != IF_IDE && type != IF_VIRTIO) {
2107 fprintf(stderr, "rerror is no supported by this format\n");
2108 return NULL;
2111 on_read_error = parse_block_error_action(buf, 1);
2112 if (on_read_error < 0) {
2113 return NULL;
2117 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2118 if (type != IF_VIRTIO) {
2119 fprintf(stderr, "addr is not supported\n");
2120 return NULL;
2124 /* compute bus and unit according index */
2126 if (index != -1) {
2127 if (bus_id != 0 || unit_id != -1) {
2128 fprintf(stderr,
2129 "qemu: index cannot be used with bus and unit\n");
2130 return NULL;
2132 if (max_devs == 0)
2134 unit_id = index;
2135 bus_id = 0;
2136 } else {
2137 unit_id = index % max_devs;
2138 bus_id = index / max_devs;
2142 /* if user doesn't specify a unit_id,
2143 * try to find the first free
2146 if (unit_id == -1) {
2147 unit_id = 0;
2148 while (drive_get(type, bus_id, unit_id) != NULL) {
2149 unit_id++;
2150 if (max_devs && unit_id >= max_devs) {
2151 unit_id -= max_devs;
2152 bus_id++;
2157 /* check unit id */
2159 if (max_devs && unit_id >= max_devs) {
2160 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2161 unit_id, max_devs - 1);
2162 return NULL;
2166 * ignore multiple definitions
2169 if (drive_get(type, bus_id, unit_id) != NULL) {
2170 *fatal_error = 0;
2171 return NULL;
2174 /* init */
2176 dinfo = qemu_mallocz(sizeof(*dinfo));
2177 if ((buf = qemu_opts_id(opts)) != NULL) {
2178 dinfo->id = qemu_strdup(buf);
2179 } else {
2180 /* no id supplied -> create one */
2181 dinfo->id = qemu_mallocz(32);
2182 if (type == IF_IDE || type == IF_SCSI)
2183 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2184 if (max_devs)
2185 snprintf(dinfo->id, 32, "%s%i%s%i",
2186 devname, bus_id, mediastr, unit_id);
2187 else
2188 snprintf(dinfo->id, 32, "%s%s%i",
2189 devname, mediastr, unit_id);
2191 dinfo->bdrv = bdrv_new(dinfo->id);
2192 dinfo->devaddr = devaddr;
2193 dinfo->type = type;
2194 dinfo->bus = bus_id;
2195 dinfo->unit = unit_id;
2196 dinfo->on_read_error = on_read_error;
2197 dinfo->on_write_error = on_write_error;
2198 dinfo->opts = opts;
2199 if (serial)
2200 strncpy(dinfo->serial, serial, sizeof(serial));
2201 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2202 if (is_extboot) {
2203 extboot_drive = dinfo;
2206 switch(type) {
2207 case IF_IDE:
2208 case IF_SCSI:
2209 case IF_XEN:
2210 case IF_NONE:
2211 switch(media) {
2212 case MEDIA_DISK:
2213 if (cyls != 0) {
2214 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2215 bdrv_set_translation_hint(dinfo->bdrv, translation);
2217 break;
2218 case MEDIA_CDROM:
2219 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2220 break;
2222 break;
2223 case IF_SD:
2224 /* FIXME: This isn't really a floppy, but it's a reasonable
2225 approximation. */
2226 case IF_FLOPPY:
2227 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2228 break;
2229 case IF_PFLASH:
2230 case IF_MTD:
2231 break;
2232 case IF_VIRTIO:
2233 /* add virtio block device */
2234 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2235 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2236 qemu_opt_set(opts, "drive", dinfo->id);
2237 if (devaddr)
2238 qemu_opt_set(opts, "addr", devaddr);
2239 break;
2240 case IF_COUNT:
2241 abort();
2243 if (!file) {
2244 *fatal_error = 0;
2245 return NULL;
2247 bdrv_flags = 0;
2248 if (snapshot) {
2249 bdrv_flags |= BDRV_O_SNAPSHOT;
2250 cache = 2; /* always use write-back with snapshot */
2252 if (cache == 0) /* no caching */
2253 bdrv_flags |= BDRV_O_NOCACHE;
2254 else if (cache == 2) /* write-back */
2255 bdrv_flags |= BDRV_O_CACHE_WB;
2257 if (aio == 1) {
2258 bdrv_flags |= BDRV_O_NATIVE_AIO;
2259 } else {
2260 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2263 if (ro == 1) {
2264 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2265 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2266 return NULL;
2270 * cdrom is read-only. Set it now, after above interface checking
2271 * since readonly attribute not explicitly required, so no error.
2273 if (media == MEDIA_CDROM) {
2274 ro = 1;
2276 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2278 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2279 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2280 file, strerror(errno));
2281 return NULL;
2284 if (bdrv_key_required(dinfo->bdrv))
2285 autostart = 0;
2286 *fatal_error = 0;
2287 return dinfo;
2290 static int drive_init_func(QemuOpts *opts, void *opaque)
2292 QEMUMachine *machine = opaque;
2293 int fatal_error = 0;
2295 if (drive_init(opts, machine, &fatal_error) == NULL) {
2296 if (fatal_error)
2297 return 1;
2299 return 0;
2302 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2304 if (NULL == qemu_opt_get(opts, "snapshot")) {
2305 qemu_opt_set(opts, "snapshot", "on");
2307 return 0;
2310 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2312 boot_set_handler = func;
2313 boot_set_opaque = opaque;
2316 int qemu_boot_set(const char *boot_devices)
2318 if (!boot_set_handler) {
2319 return -EINVAL;
2321 return boot_set_handler(boot_set_opaque, boot_devices);
2324 static int parse_bootdevices(char *devices)
2326 /* We just do some generic consistency checks */
2327 const char *p;
2328 int bitmap = 0;
2330 for (p = devices; *p != '\0'; p++) {
2331 /* Allowed boot devices are:
2332 * a-b: floppy disk drives
2333 * c-f: IDE disk drives
2334 * g-m: machine implementation dependant drives
2335 * n-p: network devices
2336 * It's up to each machine implementation to check if the given boot
2337 * devices match the actual hardware implementation and firmware
2338 * features.
2340 if (*p < 'a' || *p > 'p') {
2341 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2342 exit(1);
2344 if (bitmap & (1 << (*p - 'a'))) {
2345 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2346 exit(1);
2348 bitmap |= 1 << (*p - 'a');
2350 return bitmap;
2353 static void restore_boot_devices(void *opaque)
2355 char *standard_boot_devices = opaque;
2357 qemu_boot_set(standard_boot_devices);
2359 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2360 qemu_free(standard_boot_devices);
2363 static void numa_add(const char *optarg)
2365 char option[128];
2366 char *endptr;
2367 unsigned long long value, endvalue;
2368 int nodenr;
2370 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2371 if (!strcmp(option, "node")) {
2372 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2373 nodenr = nb_numa_nodes;
2374 } else {
2375 nodenr = strtoull(option, NULL, 10);
2378 if (get_param_value(option, 128, "mem", optarg) == 0) {
2379 node_mem[nodenr] = 0;
2380 } else {
2381 value = strtoull(option, &endptr, 0);
2382 switch (*endptr) {
2383 case 0: case 'M': case 'm':
2384 value <<= 20;
2385 break;
2386 case 'G': case 'g':
2387 value <<= 30;
2388 break;
2390 node_mem[nodenr] = value;
2392 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2393 node_cpumask[nodenr] = 0;
2394 } else {
2395 value = strtoull(option, &endptr, 10);
2396 if (value >= 64) {
2397 value = 63;
2398 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2399 } else {
2400 if (*endptr == '-') {
2401 endvalue = strtoull(endptr+1, &endptr, 10);
2402 if (endvalue >= 63) {
2403 endvalue = 62;
2404 fprintf(stderr,
2405 "only 63 CPUs in NUMA mode supported.\n");
2407 value = (2ULL << endvalue) - (1ULL << value);
2408 } else {
2409 value = 1ULL << value;
2412 node_cpumask[nodenr] = value;
2414 nb_numa_nodes++;
2416 return;
2419 static void smp_parse(const char *optarg)
2421 int smp, sockets = 0, threads = 0, cores = 0;
2422 char *endptr;
2423 char option[128];
2425 smp = strtoul(optarg, &endptr, 10);
2426 if (endptr != optarg) {
2427 if (*endptr == ',') {
2428 endptr++;
2431 if (get_param_value(option, 128, "sockets", endptr) != 0)
2432 sockets = strtoull(option, NULL, 10);
2433 if (get_param_value(option, 128, "cores", endptr) != 0)
2434 cores = strtoull(option, NULL, 10);
2435 if (get_param_value(option, 128, "threads", endptr) != 0)
2436 threads = strtoull(option, NULL, 10);
2437 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2438 max_cpus = strtoull(option, NULL, 10);
2440 /* compute missing values, prefer sockets over cores over threads */
2441 if (smp == 0 || sockets == 0) {
2442 sockets = sockets > 0 ? sockets : 1;
2443 cores = cores > 0 ? cores : 1;
2444 threads = threads > 0 ? threads : 1;
2445 if (smp == 0) {
2446 smp = cores * threads * sockets;
2448 } else {
2449 if (cores == 0) {
2450 threads = threads > 0 ? threads : 1;
2451 cores = smp / (sockets * threads);
2452 } else {
2453 if (sockets) {
2454 threads = smp / (cores * sockets);
2458 smp_cpus = smp;
2459 smp_cores = cores > 0 ? cores : 1;
2460 smp_threads = threads > 0 ? threads : 1;
2461 if (max_cpus == 0)
2462 max_cpus = smp_cpus;
2465 /***********************************************************/
2466 /* USB devices */
2468 static int usb_device_add(const char *devname, int is_hotplug)
2470 const char *p;
2471 USBDevice *dev = NULL;
2473 if (!usb_enabled)
2474 return -1;
2476 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2477 dev = usbdevice_create(devname);
2478 if (dev)
2479 goto done;
2481 /* the other ones */
2482 if (strstart(devname, "host:", &p)) {
2483 dev = usb_host_device_open(p);
2484 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2485 dev = usb_bt_init(devname[2] ? hci_init(p) :
2486 bt_new_hci(qemu_find_bt_vlan(0)));
2487 } else {
2488 return -1;
2490 if (!dev)
2491 return -1;
2493 done:
2494 return 0;
2497 static int usb_device_del(const char *devname)
2499 int bus_num, addr;
2500 const char *p;
2502 if (strstart(devname, "host:", &p))
2503 return usb_host_device_close(p);
2505 if (!usb_enabled)
2506 return -1;
2508 p = strchr(devname, '.');
2509 if (!p)
2510 return -1;
2511 bus_num = strtoul(devname, NULL, 0);
2512 addr = strtoul(p + 1, NULL, 0);
2514 return usb_device_delete_addr(bus_num, addr);
2517 static int usb_parse(const char *cmdline)
2519 int r;
2520 r = usb_device_add(cmdline, 0);
2521 if (r < 0) {
2522 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2524 return r;
2527 void do_usb_add(Monitor *mon, const QDict *qdict)
2529 const char *devname = qdict_get_str(qdict, "devname");
2530 if (usb_device_add(devname, 1) < 0) {
2531 qemu_error("could not add USB device '%s'\n", devname);
2535 void do_usb_del(Monitor *mon, const QDict *qdict)
2537 const char *devname = qdict_get_str(qdict, "devname");
2538 if (usb_device_del(devname) < 0) {
2539 qemu_error("could not delete USB device '%s'\n", devname);
2543 /***********************************************************/
2544 /* PCMCIA/Cardbus */
2546 static struct pcmcia_socket_entry_s {
2547 PCMCIASocket *socket;
2548 struct pcmcia_socket_entry_s *next;
2549 } *pcmcia_sockets = 0;
2551 void pcmcia_socket_register(PCMCIASocket *socket)
2553 struct pcmcia_socket_entry_s *entry;
2555 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2556 entry->socket = socket;
2557 entry->next = pcmcia_sockets;
2558 pcmcia_sockets = entry;
2561 void pcmcia_socket_unregister(PCMCIASocket *socket)
2563 struct pcmcia_socket_entry_s *entry, **ptr;
2565 ptr = &pcmcia_sockets;
2566 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2567 if (entry->socket == socket) {
2568 *ptr = entry->next;
2569 qemu_free(entry);
2573 void pcmcia_info(Monitor *mon)
2575 struct pcmcia_socket_entry_s *iter;
2577 if (!pcmcia_sockets)
2578 monitor_printf(mon, "No PCMCIA sockets\n");
2580 for (iter = pcmcia_sockets; iter; iter = iter->next)
2581 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2582 iter->socket->attached ? iter->socket->card_string :
2583 "Empty");
2586 /***********************************************************/
2587 /* register display */
2589 struct DisplayAllocator default_allocator = {
2590 defaultallocator_create_displaysurface,
2591 defaultallocator_resize_displaysurface,
2592 defaultallocator_free_displaysurface
2595 void register_displaystate(DisplayState *ds)
2597 DisplayState **s;
2598 s = &display_state;
2599 while (*s != NULL)
2600 s = &(*s)->next;
2601 ds->next = NULL;
2602 *s = ds;
2605 DisplayState *get_displaystate(void)
2607 return display_state;
2610 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2612 if(ds->allocator == &default_allocator) ds->allocator = da;
2613 return ds->allocator;
2616 /* dumb display */
2618 static void dumb_display_init(void)
2620 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2621 ds->allocator = &default_allocator;
2622 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2623 register_displaystate(ds);
2626 /***********************************************************/
2627 /* I/O handling */
2629 typedef struct IOHandlerRecord {
2630 int fd;
2631 IOCanRWHandler *fd_read_poll;
2632 IOHandler *fd_read;
2633 IOHandler *fd_write;
2634 int deleted;
2635 void *opaque;
2636 /* temporary data */
2637 struct pollfd *ufd;
2638 struct IOHandlerRecord *next;
2639 } IOHandlerRecord;
2641 static IOHandlerRecord *first_io_handler;
2643 /* XXX: fd_read_poll should be suppressed, but an API change is
2644 necessary in the character devices to suppress fd_can_read(). */
2645 int qemu_set_fd_handler2(int fd,
2646 IOCanRWHandler *fd_read_poll,
2647 IOHandler *fd_read,
2648 IOHandler *fd_write,
2649 void *opaque)
2651 IOHandlerRecord **pioh, *ioh;
2653 if (!fd_read && !fd_write) {
2654 pioh = &first_io_handler;
2655 for(;;) {
2656 ioh = *pioh;
2657 if (ioh == NULL)
2658 break;
2659 if (ioh->fd == fd) {
2660 ioh->deleted = 1;
2661 break;
2663 pioh = &ioh->next;
2665 } else {
2666 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2667 if (ioh->fd == fd)
2668 goto found;
2670 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2671 ioh->next = first_io_handler;
2672 first_io_handler = ioh;
2673 found:
2674 ioh->fd = fd;
2675 ioh->fd_read_poll = fd_read_poll;
2676 ioh->fd_read = fd_read;
2677 ioh->fd_write = fd_write;
2678 ioh->opaque = opaque;
2679 ioh->deleted = 0;
2681 qemu_notify_event();
2682 return 0;
2685 int qemu_set_fd_handler(int fd,
2686 IOHandler *fd_read,
2687 IOHandler *fd_write,
2688 void *opaque)
2690 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2693 #ifdef _WIN32
2694 /***********************************************************/
2695 /* Polling handling */
2697 typedef struct PollingEntry {
2698 PollingFunc *func;
2699 void *opaque;
2700 struct PollingEntry *next;
2701 } PollingEntry;
2703 static PollingEntry *first_polling_entry;
2705 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2707 PollingEntry **ppe, *pe;
2708 pe = qemu_mallocz(sizeof(PollingEntry));
2709 pe->func = func;
2710 pe->opaque = opaque;
2711 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2712 *ppe = pe;
2713 return 0;
2716 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2718 PollingEntry **ppe, *pe;
2719 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2720 pe = *ppe;
2721 if (pe->func == func && pe->opaque == opaque) {
2722 *ppe = pe->next;
2723 qemu_free(pe);
2724 break;
2729 /***********************************************************/
2730 /* Wait objects support */
2731 typedef struct WaitObjects {
2732 int num;
2733 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2734 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2735 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2736 } WaitObjects;
2738 static WaitObjects wait_objects = {0};
2740 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2742 WaitObjects *w = &wait_objects;
2744 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2745 return -1;
2746 w->events[w->num] = handle;
2747 w->func[w->num] = func;
2748 w->opaque[w->num] = opaque;
2749 w->num++;
2750 return 0;
2753 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2755 int i, found;
2756 WaitObjects *w = &wait_objects;
2758 found = 0;
2759 for (i = 0; i < w->num; i++) {
2760 if (w->events[i] == handle)
2761 found = 1;
2762 if (found) {
2763 w->events[i] = w->events[i + 1];
2764 w->func[i] = w->func[i + 1];
2765 w->opaque[i] = w->opaque[i + 1];
2768 if (found)
2769 w->num--;
2771 #endif
2773 /***********************************************************/
2774 /* ram save/restore */
2776 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2777 #define RAM_SAVE_FLAG_COMPRESS 0x02
2778 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2779 #define RAM_SAVE_FLAG_PAGE 0x08
2780 #define RAM_SAVE_FLAG_EOS 0x10
2782 static int is_dup_page(uint8_t *page, uint8_t ch)
2784 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2785 uint32_t *array = (uint32_t *)page;
2786 int i;
2788 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2789 if (array[i] != val)
2790 return 0;
2793 return 1;
2796 static int ram_save_block(QEMUFile *f)
2798 static ram_addr_t current_addr = 0;
2799 ram_addr_t saved_addr = current_addr;
2800 ram_addr_t addr = 0;
2801 int found = 0;
2803 while (addr < last_ram_offset) {
2804 if (kvm_enabled() && current_addr == 0) {
2805 int r;
2806 r = kvm_update_dirty_pages_log();
2807 if (r) {
2808 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
2809 qemu_file_set_error(f);
2810 return 0;
2813 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2814 uint8_t *p;
2816 cpu_physical_memory_reset_dirty(current_addr,
2817 current_addr + TARGET_PAGE_SIZE,
2818 MIGRATION_DIRTY_FLAG);
2820 p = qemu_get_ram_ptr(current_addr);
2822 if (is_dup_page(p, *p)) {
2823 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2824 qemu_put_byte(f, *p);
2825 } else {
2826 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2827 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2830 found = 1;
2831 break;
2833 addr += TARGET_PAGE_SIZE;
2834 current_addr = (saved_addr + addr) % last_ram_offset;
2837 return found;
2840 static uint64_t bytes_transferred;
2842 static ram_addr_t ram_save_remaining(void)
2844 ram_addr_t addr;
2845 ram_addr_t count = 0;
2847 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2848 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2849 count++;
2852 return count;
2855 uint64_t ram_bytes_remaining(void)
2857 return ram_save_remaining() * TARGET_PAGE_SIZE;
2860 uint64_t ram_bytes_transferred(void)
2862 return bytes_transferred;
2865 uint64_t ram_bytes_total(void)
2867 return last_ram_offset;
2870 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2872 ram_addr_t addr;
2873 uint64_t bytes_transferred_last;
2874 double bwidth = 0;
2875 uint64_t expected_time = 0;
2877 if (stage < 0) {
2878 cpu_physical_memory_set_dirty_tracking(0);
2879 return 0;
2882 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2883 qemu_file_set_error(f);
2884 return 0;
2887 if (stage == 1) {
2888 bytes_transferred = 0;
2890 /* Make sure all dirty bits are set */
2891 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2892 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2893 cpu_physical_memory_set_dirty(addr);
2896 /* Enable dirty memory tracking */
2897 cpu_physical_memory_set_dirty_tracking(1);
2899 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2902 bytes_transferred_last = bytes_transferred;
2903 bwidth = get_clock();
2905 while (!qemu_file_rate_limit(f)) {
2906 int ret;
2908 ret = ram_save_block(f);
2909 bytes_transferred += ret * TARGET_PAGE_SIZE;
2910 if (ret == 0) /* no more blocks */
2911 break;
2914 bwidth = get_clock() - bwidth;
2915 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2917 /* if we haven't transferred anything this round, force expected_time to a
2918 * a very high value, but without crashing */
2919 if (bwidth == 0)
2920 bwidth = 0.000001;
2922 /* try transferring iterative blocks of memory */
2923 if (stage == 3) {
2924 /* flush all remaining blocks regardless of rate limiting */
2925 while (ram_save_block(f) != 0) {
2926 bytes_transferred += TARGET_PAGE_SIZE;
2928 cpu_physical_memory_set_dirty_tracking(0);
2931 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2933 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2935 return (stage == 2) && (expected_time <= migrate_max_downtime());
2938 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2940 ram_addr_t addr;
2941 int flags;
2943 if (version_id != 3)
2944 return -EINVAL;
2946 do {
2947 addr = qemu_get_be64(f);
2949 flags = addr & ~TARGET_PAGE_MASK;
2950 addr &= TARGET_PAGE_MASK;
2952 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2953 if (addr != last_ram_offset)
2954 return -EINVAL;
2957 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2958 uint8_t ch = qemu_get_byte(f);
2959 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2960 #ifndef _WIN32
2961 if (ch == 0 &&
2962 (!kvm_enabled() || kvm_has_sync_mmu())) {
2963 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2965 #endif
2966 } else if (flags & RAM_SAVE_FLAG_PAGE) {
2967 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2969 if (qemu_file_has_error(f)) {
2970 return -EIO;
2972 } while (!(flags & RAM_SAVE_FLAG_EOS));
2974 return 0;
2977 void qemu_service_io(void)
2979 qemu_notify_event();
2982 /***********************************************************/
2983 /* machine registration */
2985 static QEMUMachine *first_machine = NULL;
2986 QEMUMachine *current_machine = NULL;
2988 int qemu_register_machine(QEMUMachine *m)
2990 QEMUMachine **pm;
2991 pm = &first_machine;
2992 while (*pm != NULL)
2993 pm = &(*pm)->next;
2994 m->next = NULL;
2995 *pm = m;
2996 return 0;
2999 static QEMUMachine *find_machine(const char *name)
3001 QEMUMachine *m;
3003 for(m = first_machine; m != NULL; m = m->next) {
3004 if (!strcmp(m->name, name))
3005 return m;
3006 if (m->alias && !strcmp(m->alias, name))
3007 return m;
3009 return NULL;
3012 static QEMUMachine *find_default_machine(void)
3014 QEMUMachine *m;
3016 for(m = first_machine; m != NULL; m = m->next) {
3017 if (m->is_default) {
3018 return m;
3021 return NULL;
3024 /***********************************************************/
3025 /* main execution loop */
3027 static void gui_update(void *opaque)
3029 uint64_t interval = GUI_REFRESH_INTERVAL;
3030 DisplayState *ds = opaque;
3031 DisplayChangeListener *dcl = ds->listeners;
3033 qemu_flush_coalesced_mmio_buffer();
3034 dpy_refresh(ds);
3036 while (dcl != NULL) {
3037 if (dcl->gui_timer_interval &&
3038 dcl->gui_timer_interval < interval)
3039 interval = dcl->gui_timer_interval;
3040 dcl = dcl->next;
3042 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3045 static void nographic_update(void *opaque)
3047 uint64_t interval = GUI_REFRESH_INTERVAL;
3049 qemu_flush_coalesced_mmio_buffer();
3050 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3053 struct vm_change_state_entry {
3054 VMChangeStateHandler *cb;
3055 void *opaque;
3056 QLIST_ENTRY (vm_change_state_entry) entries;
3059 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3061 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3062 void *opaque)
3064 VMChangeStateEntry *e;
3066 e = qemu_mallocz(sizeof (*e));
3068 e->cb = cb;
3069 e->opaque = opaque;
3070 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3071 return e;
3074 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3076 QLIST_REMOVE (e, entries);
3077 qemu_free (e);
3080 static void vm_state_notify(int running, int reason)
3082 VMChangeStateEntry *e;
3084 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3085 e->cb(e->opaque, running, reason);
3089 static void resume_all_vcpus(void);
3090 static void pause_all_vcpus(void);
3092 void vm_start(void)
3094 if (!vm_running) {
3095 cpu_enable_ticks();
3096 vm_running = 1;
3097 vm_state_notify(1, 0);
3098 qemu_rearm_alarm_timer(alarm_timer);
3099 resume_all_vcpus();
3103 /* reset/shutdown handler */
3105 typedef struct QEMUResetEntry {
3106 QTAILQ_ENTRY(QEMUResetEntry) entry;
3107 QEMUResetHandler *func;
3108 void *opaque;
3109 } QEMUResetEntry;
3111 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3112 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3113 static int reset_requested;
3114 static int shutdown_requested;
3115 static int powerdown_requested;
3116 static int debug_requested;
3117 static int vmstop_requested;
3119 int qemu_no_shutdown(void)
3121 int r = no_shutdown;
3122 no_shutdown = 0;
3123 return r;
3126 int qemu_shutdown_requested(void)
3128 int r = shutdown_requested;
3129 shutdown_requested = 0;
3130 return r;
3133 int qemu_reset_requested(void)
3135 int r = reset_requested;
3136 reset_requested = 0;
3137 return r;
3140 int qemu_powerdown_requested(void)
3142 int r = powerdown_requested;
3143 powerdown_requested = 0;
3144 return r;
3147 static int qemu_debug_requested(void)
3149 int r = debug_requested;
3150 debug_requested = 0;
3151 return r;
3154 static int qemu_vmstop_requested(void)
3156 int r = vmstop_requested;
3157 vmstop_requested = 0;
3158 return r;
3161 static void do_vm_stop(int reason)
3163 if (vm_running) {
3164 cpu_disable_ticks();
3165 vm_running = 0;
3166 pause_all_vcpus();
3167 vm_state_notify(0, reason);
3171 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3173 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3175 re->func = func;
3176 re->opaque = opaque;
3177 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3180 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3182 QEMUResetEntry *re;
3184 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3185 if (re->func == func && re->opaque == opaque) {
3186 QTAILQ_REMOVE(&reset_handlers, re, entry);
3187 qemu_free(re);
3188 return;
3193 void qemu_system_reset(void)
3195 QEMUResetEntry *re, *nre;
3197 /* reset all devices */
3198 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3199 re->func(re->opaque);
3203 void qemu_system_reset_request(void)
3205 if (no_reboot) {
3206 shutdown_requested = 1;
3207 } else {
3208 reset_requested = 1;
3210 if (cpu_single_env) {
3211 cpu_single_env->stopped = 1;
3213 qemu_notify_event();
3216 void qemu_system_shutdown_request(void)
3218 shutdown_requested = 1;
3219 qemu_notify_event();
3222 void qemu_system_powerdown_request(void)
3224 powerdown_requested = 1;
3225 qemu_notify_event();
3228 #ifdef CONFIG_IOTHREAD
3229 static void qemu_system_vmstop_request(int reason)
3231 vmstop_requested = reason;
3232 qemu_notify_event();
3234 #endif
3236 #ifndef _WIN32
3237 static int io_thread_fd = -1;
3239 static void qemu_event_increment(void)
3241 static const char byte = 0;
3242 ssize_t ret;
3244 if (io_thread_fd == -1)
3245 return;
3247 ret = write(io_thread_fd, &byte, sizeof(byte));
3248 if (ret < 0 && (errno != EINTR && errno != EAGAIN)) {
3249 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3250 strerror(errno));
3251 exit (1);
3255 static void qemu_event_read(void *opaque)
3257 int fd = (unsigned long)opaque;
3258 ssize_t len;
3260 /* Drain the notify pipe */
3261 do {
3262 char buffer[512];
3263 len = read(fd, buffer, sizeof(buffer));
3264 } while ((len == -1 && errno == EINTR) || len > 0);
3267 static int qemu_event_init(void)
3269 int err;
3270 int fds[2];
3272 err = qemu_pipe(fds);
3273 if (err == -1)
3274 return -errno;
3276 err = fcntl_setfl(fds[0], O_NONBLOCK);
3277 if (err < 0)
3278 goto fail;
3280 err = fcntl_setfl(fds[1], O_NONBLOCK);
3281 if (err < 0)
3282 goto fail;
3284 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3285 (void *)(unsigned long)fds[0]);
3287 io_thread_fd = fds[1];
3288 return 0;
3290 fail:
3291 close(fds[0]);
3292 close(fds[1]);
3293 return err;
3295 #else
3296 HANDLE qemu_event_handle;
3298 static void dummy_event_handler(void *opaque)
3302 static int qemu_event_init(void)
3304 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3305 if (!qemu_event_handle) {
3306 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3307 return -1;
3309 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3310 return 0;
3313 static void qemu_event_increment(void)
3315 if (!SetEvent(qemu_event_handle)) {
3316 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3317 GetLastError());
3318 exit (1);
3321 #endif
3323 static int cpu_can_run(CPUState *env)
3325 if (env->stop)
3326 return 0;
3327 if (env->stopped)
3328 return 0;
3329 if (!vm_running)
3330 return 0;
3331 return 1;
3334 #ifndef CONFIG_IOTHREAD
3335 static int qemu_init_main_loop(void)
3337 return qemu_event_init();
3340 void qemu_init_vcpu(void *_env)
3342 CPUState *env = _env;
3344 env->nr_cores = smp_cores;
3345 env->nr_threads = smp_threads;
3346 if (kvm_enabled())
3347 kvm_init_vcpu(env);
3348 return;
3351 int qemu_cpu_self(void *env)
3353 return 1;
3356 static void resume_all_vcpus(void)
3360 static void pause_all_vcpus(void)
3364 void qemu_cpu_kick(void *env)
3366 return;
3369 void qemu_notify_event(void)
3371 CPUState *env = cpu_single_env;
3373 if (kvm_enabled()) {
3374 qemu_kvm_notify_work();
3375 return;
3377 if (env) {
3378 cpu_exit(env);
3382 #if defined(KVM_UPSTREAM) || !defined(CONFIG_KVM)
3383 void qemu_mutex_lock_iothread(void) {}
3384 void qemu_mutex_unlock_iothread(void) {}
3385 #endif
3387 void vm_stop(int reason)
3389 do_vm_stop(reason);
3392 #else /* CONFIG_IOTHREAD */
3394 #include "qemu-thread.h"
3396 QemuMutex qemu_global_mutex;
3397 static QemuMutex qemu_fair_mutex;
3399 static QemuThread io_thread;
3401 static QemuThread *tcg_cpu_thread;
3402 static QemuCond *tcg_halt_cond;
3404 static int qemu_system_ready;
3405 /* cpu creation */
3406 static QemuCond qemu_cpu_cond;
3407 /* system init */
3408 static QemuCond qemu_system_cond;
3409 static QemuCond qemu_pause_cond;
3411 static void block_io_signals(void);
3412 static void unblock_io_signals(void);
3413 static int tcg_has_work(void);
3415 static int qemu_init_main_loop(void)
3417 int ret;
3419 ret = qemu_event_init();
3420 if (ret)
3421 return ret;
3423 qemu_cond_init(&qemu_pause_cond);
3424 qemu_mutex_init(&qemu_fair_mutex);
3425 qemu_mutex_init(&qemu_global_mutex);
3426 qemu_mutex_lock(&qemu_global_mutex);
3428 unblock_io_signals();
3429 qemu_thread_self(&io_thread);
3431 return 0;
3434 static void qemu_wait_io_event(CPUState *env)
3436 while (!tcg_has_work())
3437 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3439 qemu_mutex_unlock(&qemu_global_mutex);
3442 * Users of qemu_global_mutex can be starved, having no chance
3443 * to acquire it since this path will get to it first.
3444 * So use another lock to provide fairness.
3446 qemu_mutex_lock(&qemu_fair_mutex);
3447 qemu_mutex_unlock(&qemu_fair_mutex);
3449 qemu_mutex_lock(&qemu_global_mutex);
3450 if (env->stop) {
3451 env->stop = 0;
3452 env->stopped = 1;
3453 qemu_cond_signal(&qemu_pause_cond);
3457 static int qemu_cpu_exec(CPUState *env);
3459 static void *kvm_cpu_thread_fn(void *arg)
3461 CPUState *env = arg;
3463 block_io_signals();
3464 qemu_thread_self(env->thread);
3465 if (kvm_enabled())
3466 kvm_init_vcpu(env);
3468 /* signal CPU creation */
3469 qemu_mutex_lock(&qemu_global_mutex);
3470 env->created = 1;
3471 qemu_cond_signal(&qemu_cpu_cond);
3473 /* and wait for machine initialization */
3474 while (!qemu_system_ready)
3475 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3477 while (1) {
3478 if (cpu_can_run(env))
3479 qemu_cpu_exec(env);
3480 qemu_wait_io_event(env);
3483 return NULL;
3486 static void tcg_cpu_exec(void);
3488 static void *tcg_cpu_thread_fn(void *arg)
3490 CPUState *env = arg;
3492 block_io_signals();
3493 qemu_thread_self(env->thread);
3495 /* signal CPU creation */
3496 qemu_mutex_lock(&qemu_global_mutex);
3497 for (env = first_cpu; env != NULL; env = env->next_cpu)
3498 env->created = 1;
3499 qemu_cond_signal(&qemu_cpu_cond);
3501 /* and wait for machine initialization */
3502 while (!qemu_system_ready)
3503 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3505 while (1) {
3506 tcg_cpu_exec();
3507 qemu_wait_io_event(cur_cpu);
3510 return NULL;
3513 void qemu_cpu_kick(void *_env)
3515 CPUState *env = _env;
3516 qemu_cond_broadcast(env->halt_cond);
3517 if (kvm_enabled())
3518 qemu_thread_signal(env->thread, SIGUSR1);
3521 int qemu_cpu_self(void *_env)
3523 CPUState *env = _env;
3524 QemuThread this;
3526 qemu_thread_self(&this);
3528 return qemu_thread_equal(&this, env->thread);
3531 static void cpu_signal(int sig)
3533 if (cpu_single_env)
3534 cpu_exit(cpu_single_env);
3537 static void block_io_signals(void)
3539 sigset_t set;
3540 struct sigaction sigact;
3542 sigemptyset(&set);
3543 sigaddset(&set, SIGUSR2);
3544 sigaddset(&set, SIGIO);
3545 sigaddset(&set, SIGALRM);
3546 pthread_sigmask(SIG_BLOCK, &set, NULL);
3548 sigemptyset(&set);
3549 sigaddset(&set, SIGUSR1);
3550 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3552 memset(&sigact, 0, sizeof(sigact));
3553 sigact.sa_handler = cpu_signal;
3554 sigaction(SIGUSR1, &sigact, NULL);
3557 static void unblock_io_signals(void)
3559 sigset_t set;
3561 sigemptyset(&set);
3562 sigaddset(&set, SIGUSR2);
3563 sigaddset(&set, SIGIO);
3564 sigaddset(&set, SIGALRM);
3565 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3567 sigemptyset(&set);
3568 sigaddset(&set, SIGUSR1);
3569 pthread_sigmask(SIG_BLOCK, &set, NULL);
3572 static void qemu_signal_lock(unsigned int msecs)
3574 qemu_mutex_lock(&qemu_fair_mutex);
3576 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3577 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3578 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3579 break;
3581 qemu_mutex_unlock(&qemu_fair_mutex);
3584 void qemu_mutex_lock_iothread(void)
3586 if (kvm_enabled()) {
3587 qemu_mutex_lock(&qemu_fair_mutex);
3588 qemu_mutex_lock(&qemu_global_mutex);
3589 qemu_mutex_unlock(&qemu_fair_mutex);
3590 } else
3591 qemu_signal_lock(100);
3594 void qemu_mutex_unlock_iothread(void)
3596 qemu_mutex_unlock(&qemu_global_mutex);
3599 static int all_vcpus_paused(void)
3601 CPUState *penv = first_cpu;
3603 while (penv) {
3604 if (!penv->stopped)
3605 return 0;
3606 penv = (CPUState *)penv->next_cpu;
3609 return 1;
3612 static void pause_all_vcpus(void)
3614 CPUState *penv = first_cpu;
3616 while (penv) {
3617 penv->stop = 1;
3618 qemu_thread_signal(penv->thread, SIGUSR1);
3619 qemu_cpu_kick(penv);
3620 penv = (CPUState *)penv->next_cpu;
3623 while (!all_vcpus_paused()) {
3624 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3625 penv = first_cpu;
3626 while (penv) {
3627 qemu_thread_signal(penv->thread, SIGUSR1);
3628 penv = (CPUState *)penv->next_cpu;
3633 static void resume_all_vcpus(void)
3635 CPUState *penv = first_cpu;
3637 while (penv) {
3638 penv->stop = 0;
3639 penv->stopped = 0;
3640 qemu_thread_signal(penv->thread, SIGUSR1);
3641 qemu_cpu_kick(penv);
3642 penv = (CPUState *)penv->next_cpu;
3646 static void tcg_init_vcpu(void *_env)
3648 CPUState *env = _env;
3649 /* share a single thread for all cpus with TCG */
3650 if (!tcg_cpu_thread) {
3651 env->thread = qemu_mallocz(sizeof(QemuThread));
3652 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3653 qemu_cond_init(env->halt_cond);
3654 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3655 while (env->created == 0)
3656 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3657 tcg_cpu_thread = env->thread;
3658 tcg_halt_cond = env->halt_cond;
3659 } else {
3660 env->thread = tcg_cpu_thread;
3661 env->halt_cond = tcg_halt_cond;
3665 static void kvm_start_vcpu(CPUState *env)
3667 env->thread = qemu_mallocz(sizeof(QemuThread));
3668 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3669 qemu_cond_init(env->halt_cond);
3670 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3671 while (env->created == 0)
3672 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3675 void qemu_init_vcpu(void *_env)
3677 CPUState *env = _env;
3679 env->nr_cores = smp_cores;
3680 env->nr_threads = smp_threads;
3681 if (kvm_enabled())
3682 kvm_start_vcpu(env);
3683 else
3684 tcg_init_vcpu(env);
3687 void qemu_notify_event(void)
3689 qemu_event_increment();
3692 void vm_stop(int reason)
3694 QemuThread me;
3695 qemu_thread_self(&me);
3697 if (!qemu_thread_equal(&me, &io_thread)) {
3698 qemu_system_vmstop_request(reason);
3700 * FIXME: should not return to device code in case
3701 * vm_stop() has been requested.
3703 if (cpu_single_env) {
3704 cpu_exit(cpu_single_env);
3705 cpu_single_env->stop = 1;
3707 return;
3709 do_vm_stop(reason);
3712 #endif
3715 #ifdef _WIN32
3716 static void host_main_loop_wait(int *timeout)
3718 int ret, ret2, i;
3719 PollingEntry *pe;
3722 /* XXX: need to suppress polling by better using win32 events */
3723 ret = 0;
3724 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3725 ret |= pe->func(pe->opaque);
3727 if (ret == 0) {
3728 int err;
3729 WaitObjects *w = &wait_objects;
3731 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3732 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3733 if (w->func[ret - WAIT_OBJECT_0])
3734 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3736 /* Check for additional signaled events */
3737 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3739 /* Check if event is signaled */
3740 ret2 = WaitForSingleObject(w->events[i], 0);
3741 if(ret2 == WAIT_OBJECT_0) {
3742 if (w->func[i])
3743 w->func[i](w->opaque[i]);
3744 } else if (ret2 == WAIT_TIMEOUT) {
3745 } else {
3746 err = GetLastError();
3747 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3750 } else if (ret == WAIT_TIMEOUT) {
3751 } else {
3752 err = GetLastError();
3753 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3757 *timeout = 0;
3759 #else
3760 static void host_main_loop_wait(int *timeout)
3763 #endif
3765 void main_loop_wait(int timeout)
3767 IOHandlerRecord *ioh;
3768 fd_set rfds, wfds, xfds;
3769 int ret, nfds;
3770 struct timeval tv;
3772 qemu_bh_update_timeout(&timeout);
3774 host_main_loop_wait(&timeout);
3776 /* poll any events */
3777 /* XXX: separate device handlers from system ones */
3778 nfds = -1;
3779 FD_ZERO(&rfds);
3780 FD_ZERO(&wfds);
3781 FD_ZERO(&xfds);
3782 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3783 if (ioh->deleted)
3784 continue;
3785 if (ioh->fd_read &&
3786 (!ioh->fd_read_poll ||
3787 ioh->fd_read_poll(ioh->opaque) != 0)) {
3788 FD_SET(ioh->fd, &rfds);
3789 if (ioh->fd > nfds)
3790 nfds = ioh->fd;
3792 if (ioh->fd_write) {
3793 FD_SET(ioh->fd, &wfds);
3794 if (ioh->fd > nfds)
3795 nfds = ioh->fd;
3799 tv.tv_sec = timeout / 1000;
3800 tv.tv_usec = (timeout % 1000) * 1000;
3802 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3804 qemu_mutex_unlock_iothread();
3805 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3806 qemu_mutex_lock_iothread();
3807 if (ret > 0) {
3808 IOHandlerRecord **pioh;
3810 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3811 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3812 ioh->fd_read(ioh->opaque);
3813 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3814 FD_CLR(ioh->fd, &rfds);
3816 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3817 ioh->fd_write(ioh->opaque);
3821 /* remove deleted IO handlers */
3822 pioh = &first_io_handler;
3823 while (*pioh) {
3824 ioh = *pioh;
3825 if (ioh->deleted) {
3826 *pioh = ioh->next;
3827 qemu_free(ioh);
3828 } else
3829 pioh = &ioh->next;
3833 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3835 /* rearm timer, if not periodic */
3836 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3837 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3838 qemu_rearm_alarm_timer(alarm_timer);
3841 /* vm time timers */
3842 if (vm_running) {
3843 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3844 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3845 qemu_get_clock(vm_clock));
3848 /* real time timers */
3849 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3850 qemu_get_clock(rt_clock));
3852 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3853 qemu_get_clock(host_clock));
3855 /* Check bottom-halves last in case any of the earlier events triggered
3856 them. */
3857 qemu_bh_poll();
3861 static int qemu_cpu_exec(CPUState *env)
3863 int ret;
3864 #ifdef CONFIG_PROFILER
3865 int64_t ti;
3866 #endif
3868 #ifdef CONFIG_PROFILER
3869 ti = profile_getclock();
3870 #endif
3871 if (use_icount) {
3872 int64_t count;
3873 int decr;
3874 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3875 env->icount_decr.u16.low = 0;
3876 env->icount_extra = 0;
3877 count = qemu_next_deadline();
3878 count = (count + (1 << icount_time_shift) - 1)
3879 >> icount_time_shift;
3880 qemu_icount += count;
3881 decr = (count > 0xffff) ? 0xffff : count;
3882 count -= decr;
3883 env->icount_decr.u16.low = decr;
3884 env->icount_extra = count;
3886 ret = cpu_exec(env);
3887 #ifdef CONFIG_PROFILER
3888 qemu_time += profile_getclock() - ti;
3889 #endif
3890 if (use_icount) {
3891 /* Fold pending instructions back into the
3892 instruction counter, and clear the interrupt flag. */
3893 qemu_icount -= (env->icount_decr.u16.low
3894 + env->icount_extra);
3895 env->icount_decr.u32 = 0;
3896 env->icount_extra = 0;
3898 return ret;
3901 static void tcg_cpu_exec(void)
3903 int ret = 0;
3905 if (next_cpu == NULL)
3906 next_cpu = first_cpu;
3907 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3908 CPUState *env = cur_cpu = next_cpu;
3910 if (!vm_running)
3911 break;
3912 if (timer_alarm_pending) {
3913 timer_alarm_pending = 0;
3914 break;
3916 if (cpu_can_run(env))
3917 ret = qemu_cpu_exec(env);
3918 if (ret == EXCP_DEBUG) {
3919 gdb_set_stop_cpu(env);
3920 debug_requested = 1;
3921 break;
3926 static int cpu_has_work(CPUState *env)
3928 if (env->stop)
3929 return 1;
3930 if (env->stopped)
3931 return 0;
3932 if (!env->halted)
3933 return 1;
3934 if (qemu_cpu_has_work(env))
3935 return 1;
3936 return 0;
3939 static int tcg_has_work(void)
3941 CPUState *env;
3943 for (env = first_cpu; env != NULL; env = env->next_cpu)
3944 if (cpu_has_work(env))
3945 return 1;
3946 return 0;
3949 static int qemu_calculate_timeout(void)
3951 #ifndef CONFIG_IOTHREAD
3952 int timeout;
3954 if (!vm_running)
3955 timeout = 5000;
3956 else if (tcg_has_work())
3957 timeout = 0;
3958 else if (!use_icount)
3959 timeout = 5000;
3960 else {
3961 /* XXX: use timeout computed from timers */
3962 int64_t add;
3963 int64_t delta;
3964 /* Advance virtual time to the next event. */
3965 if (use_icount == 1) {
3966 /* When not using an adaptive execution frequency
3967 we tend to get badly out of sync with real time,
3968 so just delay for a reasonable amount of time. */
3969 delta = 0;
3970 } else {
3971 delta = cpu_get_icount() - cpu_get_clock();
3973 if (delta > 0) {
3974 /* If virtual time is ahead of real time then just
3975 wait for IO. */
3976 timeout = (delta / 1000000) + 1;
3977 } else {
3978 /* Wait for either IO to occur or the next
3979 timer event. */
3980 add = qemu_next_deadline();
3981 /* We advance the timer before checking for IO.
3982 Limit the amount we advance so that early IO
3983 activity won't get the guest too far ahead. */
3984 if (add > 10000000)
3985 add = 10000000;
3986 delta += add;
3987 add = (add + (1 << icount_time_shift) - 1)
3988 >> icount_time_shift;
3989 qemu_icount += add;
3990 timeout = delta / 1000000;
3991 if (timeout < 0)
3992 timeout = 0;
3996 return timeout;
3997 #else /* CONFIG_IOTHREAD */
3998 return 1000;
3999 #endif
4002 static int vm_can_run(void)
4004 if (powerdown_requested)
4005 return 0;
4006 if (reset_requested)
4007 return 0;
4008 if (shutdown_requested)
4009 return 0;
4010 if (debug_requested)
4011 return 0;
4012 return 1;
4015 qemu_irq qemu_system_powerdown;
4017 static void main_loop(void)
4019 int r;
4021 if (kvm_enabled()) {
4022 kvm_main_loop();
4023 cpu_disable_ticks();
4024 return;
4027 #ifdef CONFIG_IOTHREAD
4028 qemu_system_ready = 1;
4029 qemu_cond_broadcast(&qemu_system_cond);
4030 #endif
4032 for (;;) {
4033 do {
4034 #ifdef CONFIG_PROFILER
4035 int64_t ti;
4036 #endif
4037 #ifndef CONFIG_IOTHREAD
4038 tcg_cpu_exec();
4039 #endif
4040 #ifdef CONFIG_PROFILER
4041 ti = profile_getclock();
4042 #endif
4043 main_loop_wait(qemu_calculate_timeout());
4044 #ifdef CONFIG_PROFILER
4045 dev_time += profile_getclock() - ti;
4046 #endif
4047 } while (vm_can_run());
4049 if (qemu_debug_requested()) {
4050 monitor_protocol_event(QEVENT_DEBUG, NULL);
4051 vm_stop(EXCP_DEBUG);
4053 if (qemu_shutdown_requested()) {
4054 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4055 if (no_shutdown) {
4056 vm_stop(0);
4057 no_shutdown = 0;
4058 } else
4059 break;
4061 if (qemu_reset_requested()) {
4062 monitor_protocol_event(QEVENT_RESET, NULL);
4063 pause_all_vcpus();
4064 qemu_system_reset();
4065 resume_all_vcpus();
4067 if (qemu_powerdown_requested()) {
4068 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4069 qemu_irq_raise(qemu_system_powerdown);
4071 if ((r = qemu_vmstop_requested())) {
4072 monitor_protocol_event(QEVENT_STOP, NULL);
4073 vm_stop(r);
4076 pause_all_vcpus();
4079 static void version(void)
4081 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4084 static void help(int exitcode)
4086 const char *options_help =
4087 #define DEF(option, opt_arg, opt_enum, opt_help) \
4088 opt_help
4089 #define DEFHEADING(text) stringify(text) "\n"
4090 #include "qemu-options.h"
4091 #undef DEF
4092 #undef DEFHEADING
4093 #undef GEN_DOCS
4095 version();
4096 printf("usage: %s [options] [disk_image]\n"
4097 "\n"
4098 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4099 "\n"
4100 "%s\n"
4101 "During emulation, the following keys are useful:\n"
4102 "ctrl-alt-f toggle full screen\n"
4103 "ctrl-alt-n switch to virtual console 'n'\n"
4104 "ctrl-alt toggle mouse and keyboard grab\n"
4105 "\n"
4106 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4107 "qemu",
4108 options_help);
4109 exit(exitcode);
4112 #define HAS_ARG 0x0001
4114 enum {
4115 #define DEF(option, opt_arg, opt_enum, opt_help) \
4116 opt_enum,
4117 #define DEFHEADING(text)
4118 #include "qemu-options.h"
4119 #undef DEF
4120 #undef DEFHEADING
4121 #undef GEN_DOCS
4124 typedef struct QEMUOption {
4125 const char *name;
4126 int flags;
4127 int index;
4128 } QEMUOption;
4130 static const QEMUOption qemu_options[] = {
4131 { "h", 0, QEMU_OPTION_h },
4132 #define DEF(option, opt_arg, opt_enum, opt_help) \
4133 { option, opt_arg, opt_enum },
4134 #define DEFHEADING(text)
4135 #include "qemu-options.h"
4136 #undef DEF
4137 #undef DEFHEADING
4138 #undef GEN_DOCS
4139 { NULL },
4142 #ifdef HAS_AUDIO
4143 struct soundhw soundhw[] = {
4144 #ifdef HAS_AUDIO_CHOICE
4145 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4147 "pcspk",
4148 "PC speaker",
4151 { .init_isa = pcspk_audio_init }
4153 #endif
4155 #ifdef CONFIG_SB16
4157 "sb16",
4158 "Creative Sound Blaster 16",
4161 { .init_isa = SB16_init }
4163 #endif
4165 #ifdef CONFIG_CS4231A
4167 "cs4231a",
4168 "CS4231A",
4171 { .init_isa = cs4231a_init }
4173 #endif
4175 #ifdef CONFIG_ADLIB
4177 "adlib",
4178 #ifdef HAS_YMF262
4179 "Yamaha YMF262 (OPL3)",
4180 #else
4181 "Yamaha YM3812 (OPL2)",
4182 #endif
4185 { .init_isa = Adlib_init }
4187 #endif
4189 #ifdef CONFIG_GUS
4191 "gus",
4192 "Gravis Ultrasound GF1",
4195 { .init_isa = GUS_init }
4197 #endif
4199 #ifdef CONFIG_AC97
4201 "ac97",
4202 "Intel 82801AA AC97 Audio",
4205 { .init_pci = ac97_init }
4207 #endif
4209 #ifdef CONFIG_ES1370
4211 "es1370",
4212 "ENSONIQ AudioPCI ES1370",
4215 { .init_pci = es1370_init }
4217 #endif
4219 #endif /* HAS_AUDIO_CHOICE */
4221 { NULL, NULL, 0, 0, { NULL } }
4224 static void select_soundhw (const char *optarg)
4226 struct soundhw *c;
4228 if (*optarg == '?') {
4229 show_valid_cards:
4231 printf ("Valid sound card names (comma separated):\n");
4232 for (c = soundhw; c->name; ++c) {
4233 printf ("%-11s %s\n", c->name, c->descr);
4235 printf ("\n-soundhw all will enable all of the above\n");
4236 exit (*optarg != '?');
4238 else {
4239 size_t l;
4240 const char *p;
4241 char *e;
4242 int bad_card = 0;
4244 if (!strcmp (optarg, "all")) {
4245 for (c = soundhw; c->name; ++c) {
4246 c->enabled = 1;
4248 return;
4251 p = optarg;
4252 while (*p) {
4253 e = strchr (p, ',');
4254 l = !e ? strlen (p) : (size_t) (e - p);
4256 for (c = soundhw; c->name; ++c) {
4257 if (!strncmp (c->name, p, l) && !c->name[l]) {
4258 c->enabled = 1;
4259 break;
4263 if (!c->name) {
4264 if (l > 80) {
4265 fprintf (stderr,
4266 "Unknown sound card name (too big to show)\n");
4268 else {
4269 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4270 (int) l, p);
4272 bad_card = 1;
4274 p += l + (e != NULL);
4277 if (bad_card)
4278 goto show_valid_cards;
4281 #endif
4283 static void select_vgahw (const char *p)
4285 const char *opts;
4287 default_vga = 0;
4288 vga_interface_type = VGA_NONE;
4289 if (strstart(p, "std", &opts)) {
4290 vga_interface_type = VGA_STD;
4291 } else if (strstart(p, "cirrus", &opts)) {
4292 vga_interface_type = VGA_CIRRUS;
4293 } else if (strstart(p, "vmware", &opts)) {
4294 vga_interface_type = VGA_VMWARE;
4295 } else if (strstart(p, "xenfb", &opts)) {
4296 vga_interface_type = VGA_XENFB;
4297 } else if (!strstart(p, "none", &opts)) {
4298 invalid_vga:
4299 fprintf(stderr, "Unknown vga type: %s\n", p);
4300 exit(1);
4302 while (*opts) {
4303 const char *nextopt;
4305 if (strstart(opts, ",retrace=", &nextopt)) {
4306 opts = nextopt;
4307 if (strstart(opts, "dumb", &nextopt))
4308 vga_retrace_method = VGA_RETRACE_DUMB;
4309 else if (strstart(opts, "precise", &nextopt))
4310 vga_retrace_method = VGA_RETRACE_PRECISE;
4311 else goto invalid_vga;
4312 } else goto invalid_vga;
4313 opts = nextopt;
4317 #ifdef TARGET_I386
4318 static int balloon_parse(const char *arg)
4320 QemuOpts *opts;
4322 if (strcmp(arg, "none") == 0) {
4323 return 0;
4326 if (!strncmp(arg, "virtio", 6)) {
4327 if (arg[6] == ',') {
4328 /* have params -> parse them */
4329 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4330 if (!opts)
4331 return -1;
4332 } else {
4333 /* create empty opts */
4334 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4336 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4337 return 0;
4340 return -1;
4342 #endif
4344 #ifdef _WIN32
4345 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4347 exit(STATUS_CONTROL_C_EXIT);
4348 return TRUE;
4350 #endif
4352 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4354 int ret;
4356 if(strlen(str) != 36)
4357 return -1;
4359 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4360 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4361 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4363 if(ret != 16)
4364 return -1;
4366 #ifdef TARGET_I386
4367 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4368 #endif
4370 return 0;
4373 #ifndef _WIN32
4375 static void termsig_handler(int signal)
4377 qemu_system_shutdown_request();
4380 static void sigchld_handler(int signal)
4382 waitpid(-1, NULL, WNOHANG);
4385 static void sighandler_setup(void)
4387 struct sigaction act;
4389 memset(&act, 0, sizeof(act));
4390 act.sa_handler = termsig_handler;
4391 sigaction(SIGINT, &act, NULL);
4392 sigaction(SIGHUP, &act, NULL);
4393 sigaction(SIGTERM, &act, NULL);
4395 act.sa_handler = sigchld_handler;
4396 act.sa_flags = SA_NOCLDSTOP;
4397 sigaction(SIGCHLD, &act, NULL);
4400 #endif
4402 #ifdef _WIN32
4403 /* Look for support files in the same directory as the executable. */
4404 static char *find_datadir(const char *argv0)
4406 char *p;
4407 char buf[MAX_PATH];
4408 DWORD len;
4410 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4411 if (len == 0) {
4412 return NULL;
4415 buf[len] = 0;
4416 p = buf + len - 1;
4417 while (p != buf && *p != '\\')
4418 p--;
4419 *p = 0;
4420 if (access(buf, R_OK) == 0) {
4421 return qemu_strdup(buf);
4423 return NULL;
4425 #else /* !_WIN32 */
4427 /* Find a likely location for support files using the location of the binary.
4428 For installed binaries this will be "$bindir/../share/qemu". When
4429 running from the build tree this will be "$bindir/../pc-bios". */
4430 #define SHARE_SUFFIX "/share/qemu"
4431 #define BUILD_SUFFIX "/pc-bios"
4432 static char *find_datadir(const char *argv0)
4434 char *dir;
4435 char *p = NULL;
4436 char *res;
4437 char buf[PATH_MAX];
4438 size_t max_len;
4440 #if defined(__linux__)
4442 int len;
4443 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4444 if (len > 0) {
4445 buf[len] = 0;
4446 p = buf;
4449 #elif defined(__FreeBSD__)
4451 int len;
4452 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4453 if (len > 0) {
4454 buf[len] = 0;
4455 p = buf;
4458 #endif
4459 /* If we don't have any way of figuring out the actual executable
4460 location then try argv[0]. */
4461 if (!p) {
4462 p = realpath(argv0, buf);
4463 if (!p) {
4464 return NULL;
4467 dir = dirname(p);
4468 dir = dirname(dir);
4470 max_len = strlen(dir) +
4471 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4472 res = qemu_mallocz(max_len);
4473 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4474 if (access(res, R_OK)) {
4475 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4476 if (access(res, R_OK)) {
4477 qemu_free(res);
4478 res = NULL;
4482 return res;
4484 #undef SHARE_SUFFIX
4485 #undef BUILD_SUFFIX
4486 #endif
4488 char *qemu_find_file(int type, const char *name)
4490 int len;
4491 const char *subdir;
4492 char *buf;
4494 /* If name contains path separators then try it as a straight path. */
4495 if ((strchr(name, '/') || strchr(name, '\\'))
4496 && access(name, R_OK) == 0) {
4497 return qemu_strdup(name);
4499 switch (type) {
4500 case QEMU_FILE_TYPE_BIOS:
4501 subdir = "";
4502 break;
4503 case QEMU_FILE_TYPE_KEYMAP:
4504 subdir = "keymaps/";
4505 break;
4506 default:
4507 abort();
4509 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4510 buf = qemu_mallocz(len);
4511 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4512 if (access(buf, R_OK)) {
4513 qemu_free(buf);
4514 return NULL;
4516 return buf;
4519 static int device_help_func(QemuOpts *opts, void *opaque)
4521 return qdev_device_help(opts);
4524 static int device_init_func(QemuOpts *opts, void *opaque)
4526 DeviceState *dev;
4528 dev = qdev_device_add(opts);
4529 if (!dev)
4530 return -1;
4531 return 0;
4534 static int chardev_init_func(QemuOpts *opts, void *opaque)
4536 CharDriverState *chr;
4538 chr = qemu_chr_open_opts(opts, NULL);
4539 if (!chr)
4540 return -1;
4541 return 0;
4544 static int mon_init_func(QemuOpts *opts, void *opaque)
4546 CharDriverState *chr;
4547 const char *chardev;
4548 const char *mode;
4549 int flags;
4551 mode = qemu_opt_get(opts, "mode");
4552 if (mode == NULL) {
4553 mode = "readline";
4555 if (strcmp(mode, "readline") == 0) {
4556 flags = MONITOR_USE_READLINE;
4557 } else if (strcmp(mode, "control") == 0) {
4558 flags = MONITOR_USE_CONTROL;
4559 } else {
4560 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4561 exit(1);
4564 if (qemu_opt_get_bool(opts, "default", 0))
4565 flags |= MONITOR_IS_DEFAULT;
4567 chardev = qemu_opt_get(opts, "chardev");
4568 chr = qemu_chr_find(chardev);
4569 if (chr == NULL) {
4570 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4571 exit(1);
4574 monitor_init(chr, flags);
4575 return 0;
4578 static void monitor_parse(const char *optarg, const char *mode)
4580 static int monitor_device_index = 0;
4581 QemuOpts *opts;
4582 const char *p;
4583 char label[32];
4584 int def = 0;
4586 if (strstart(optarg, "chardev:", &p)) {
4587 snprintf(label, sizeof(label), "%s", p);
4588 } else {
4589 if (monitor_device_index) {
4590 snprintf(label, sizeof(label), "monitor%d",
4591 monitor_device_index);
4592 } else {
4593 snprintf(label, sizeof(label), "monitor");
4594 def = 1;
4596 opts = qemu_chr_parse_compat(label, optarg);
4597 if (!opts) {
4598 fprintf(stderr, "parse error: %s\n", optarg);
4599 exit(1);
4603 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4604 if (!opts) {
4605 fprintf(stderr, "duplicate chardev: %s\n", label);
4606 exit(1);
4608 qemu_opt_set(opts, "mode", mode);
4609 qemu_opt_set(opts, "chardev", label);
4610 if (def)
4611 qemu_opt_set(opts, "default", "on");
4612 monitor_device_index++;
4615 struct device_config {
4616 enum {
4617 DEV_USB, /* -usbdevice */
4618 DEV_BT, /* -bt */
4619 DEV_SERIAL, /* -serial */
4620 DEV_PARALLEL, /* -parallel */
4621 DEV_VIRTCON, /* -virtioconsole */
4622 DEV_DEBUGCON, /* -debugcon */
4623 } type;
4624 const char *cmdline;
4625 QTAILQ_ENTRY(device_config) next;
4627 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4629 static void add_device_config(int type, const char *cmdline)
4631 struct device_config *conf;
4633 conf = qemu_mallocz(sizeof(*conf));
4634 conf->type = type;
4635 conf->cmdline = cmdline;
4636 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4639 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4641 struct device_config *conf;
4642 int rc;
4644 QTAILQ_FOREACH(conf, &device_configs, next) {
4645 if (conf->type != type)
4646 continue;
4647 rc = func(conf->cmdline);
4648 if (0 != rc)
4649 return rc;
4651 return 0;
4654 static int serial_parse(const char *devname)
4656 static int index = 0;
4657 char label[32];
4659 if (strcmp(devname, "none") == 0)
4660 return 0;
4661 if (index == MAX_SERIAL_PORTS) {
4662 fprintf(stderr, "qemu: too many serial ports\n");
4663 exit(1);
4665 snprintf(label, sizeof(label), "serial%d", index);
4666 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4667 if (!serial_hds[index]) {
4668 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4669 devname, strerror(errno));
4670 return -1;
4672 index++;
4673 return 0;
4676 static int parallel_parse(const char *devname)
4678 static int index = 0;
4679 char label[32];
4681 if (strcmp(devname, "none") == 0)
4682 return 0;
4683 if (index == MAX_PARALLEL_PORTS) {
4684 fprintf(stderr, "qemu: too many parallel ports\n");
4685 exit(1);
4687 snprintf(label, sizeof(label), "parallel%d", index);
4688 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4689 if (!parallel_hds[index]) {
4690 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4691 devname, strerror(errno));
4692 return -1;
4694 index++;
4695 return 0;
4698 static int virtcon_parse(const char *devname)
4700 static int index = 0;
4701 char label[32];
4702 QemuOpts *bus_opts, *dev_opts;
4704 if (strcmp(devname, "none") == 0)
4705 return 0;
4706 if (index == MAX_VIRTIO_CONSOLES) {
4707 fprintf(stderr, "qemu: too many virtio consoles\n");
4708 exit(1);
4711 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4712 qemu_opt_set(bus_opts, "driver", "virtio-serial");
4714 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4715 qemu_opt_set(dev_opts, "driver", "virtconsole");
4717 snprintf(label, sizeof(label), "virtcon%d", index);
4718 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4719 if (!virtcon_hds[index]) {
4720 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4721 devname, strerror(errno));
4722 return -1;
4724 qemu_opt_set(dev_opts, "chardev", label);
4726 index++;
4727 return 0;
4730 static int debugcon_parse(const char *devname)
4732 QemuOpts *opts;
4734 if (!qemu_chr_open("debugcon", devname, NULL)) {
4735 exit(1);
4737 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4738 if (!opts) {
4739 fprintf(stderr, "qemu: already have a debugcon device\n");
4740 exit(1);
4742 qemu_opt_set(opts, "driver", "isa-debugcon");
4743 qemu_opt_set(opts, "chardev", "debugcon");
4744 return 0;
4747 static const QEMUOption *lookup_opt(int argc, char **argv,
4748 const char **poptarg, int *poptind)
4750 const QEMUOption *popt;
4751 int optind = *poptind;
4752 char *r = argv[optind];
4753 const char *optarg;
4755 optind++;
4756 /* Treat --foo the same as -foo. */
4757 if (r[1] == '-')
4758 r++;
4759 popt = qemu_options;
4760 for(;;) {
4761 if (!popt->name) {
4762 fprintf(stderr, "%s: invalid option -- '%s'\n",
4763 argv[0], r);
4764 exit(1);
4766 if (!strcmp(popt->name, r + 1))
4767 break;
4768 popt++;
4770 if (popt->flags & HAS_ARG) {
4771 if (optind >= argc) {
4772 fprintf(stderr, "%s: option '%s' requires an argument\n",
4773 argv[0], r);
4774 exit(1);
4776 optarg = argv[optind++];
4777 } else {
4778 optarg = NULL;
4781 *poptarg = optarg;
4782 *poptind = optind;
4784 return popt;
4787 int main(int argc, char **argv, char **envp)
4789 const char *gdbstub_dev = NULL;
4790 uint32_t boot_devices_bitmap = 0;
4791 int i;
4792 int snapshot, linux_boot, net_boot;
4793 const char *initrd_filename;
4794 const char *kernel_filename, *kernel_cmdline;
4795 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4796 DisplayState *ds;
4797 DisplayChangeListener *dcl;
4798 int cyls, heads, secs, translation;
4799 QemuOpts *hda_opts = NULL, *opts;
4800 int optind;
4801 const char *optarg;
4802 const char *loadvm = NULL;
4803 QEMUMachine *machine;
4804 const char *cpu_model;
4805 #ifndef _WIN32
4806 int fds[2];
4807 #endif
4808 int tb_size;
4809 const char *pid_file = NULL;
4810 const char *incoming = NULL;
4811 #ifndef _WIN32
4812 int fd = 0;
4813 struct passwd *pwd = NULL;
4814 const char *chroot_dir = NULL;
4815 const char *run_as = NULL;
4816 #endif
4817 CPUState *env;
4818 int show_vnc_port = 0;
4819 int defconfig = 1;
4821 init_clocks();
4823 qemu_errors_to_file(stderr);
4824 qemu_cache_utils_init(envp);
4826 QLIST_INIT (&vm_change_state_head);
4827 #ifndef _WIN32
4829 struct sigaction act;
4830 sigfillset(&act.sa_mask);
4831 act.sa_flags = 0;
4832 act.sa_handler = SIG_IGN;
4833 sigaction(SIGPIPE, &act, NULL);
4835 #else
4836 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4837 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4838 QEMU to run on a single CPU */
4840 HANDLE h;
4841 DWORD mask, smask;
4842 int i;
4843 h = GetCurrentProcess();
4844 if (GetProcessAffinityMask(h, &mask, &smask)) {
4845 for(i = 0; i < 32; i++) {
4846 if (mask & (1 << i))
4847 break;
4849 if (i != 32) {
4850 mask = 1 << i;
4851 SetProcessAffinityMask(h, mask);
4855 #endif
4857 module_call_init(MODULE_INIT_MACHINE);
4858 machine = find_default_machine();
4859 cpu_model = NULL;
4860 initrd_filename = NULL;
4861 ram_size = 0;
4862 snapshot = 0;
4863 kernel_filename = NULL;
4864 kernel_cmdline = "";
4865 cyls = heads = secs = 0;
4866 translation = BIOS_ATA_TRANSLATION_AUTO;
4868 for (i = 0; i < MAX_NODES; i++) {
4869 node_mem[i] = 0;
4870 node_cpumask[i] = 0;
4873 assigned_devices_index = 0;
4875 nb_numa_nodes = 0;
4876 nb_nics = 0;
4878 tb_size = 0;
4879 autostart= 1;
4881 /* first pass of option parsing */
4882 optind = 1;
4883 while (optind < argc) {
4884 if (argv[optind][0] != '-') {
4885 /* disk image */
4886 optind++;
4887 continue;
4888 } else {
4889 const QEMUOption *popt;
4891 popt = lookup_opt(argc, argv, &optarg, &optind);
4892 switch (popt->index) {
4893 case QEMU_OPTION_nodefconfig:
4894 defconfig=0;
4895 break;
4900 if (defconfig) {
4901 FILE *fp;
4902 fp = fopen(CONFIG_QEMU_CONFDIR "/qemu.conf", "r");
4903 if (fp) {
4904 if (qemu_config_parse(fp) != 0) {
4905 exit(1);
4907 fclose(fp);
4910 fp = fopen(CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf", "r");
4911 if (fp) {
4912 if (qemu_config_parse(fp) != 0) {
4913 exit(1);
4915 fclose(fp);
4919 /* second pass of option parsing */
4920 optind = 1;
4921 for(;;) {
4922 if (optind >= argc)
4923 break;
4924 if (argv[optind][0] != '-') {
4925 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4926 } else {
4927 const QEMUOption *popt;
4929 popt = lookup_opt(argc, argv, &optarg, &optind);
4930 switch(popt->index) {
4931 case QEMU_OPTION_M:
4932 machine = find_machine(optarg);
4933 if (!machine) {
4934 QEMUMachine *m;
4935 printf("Supported machines are:\n");
4936 for(m = first_machine; m != NULL; m = m->next) {
4937 if (m->alias)
4938 printf("%-10s %s (alias of %s)\n",
4939 m->alias, m->desc, m->name);
4940 printf("%-10s %s%s\n",
4941 m->name, m->desc,
4942 m->is_default ? " (default)" : "");
4944 exit(*optarg != '?');
4946 break;
4947 case QEMU_OPTION_cpu:
4948 /* hw initialization will check this */
4949 if (*optarg == '?') {
4950 /* XXX: implement xxx_cpu_list for targets that still miss it */
4951 #if defined(cpu_list)
4952 cpu_list(stdout, &fprintf);
4953 #endif
4954 exit(0);
4955 } else {
4956 cpu_model = optarg;
4958 break;
4959 case QEMU_OPTION_initrd:
4960 initrd_filename = optarg;
4961 break;
4962 case QEMU_OPTION_hda:
4963 if (cyls == 0)
4964 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4965 else
4966 hda_opts = drive_add(optarg, HD_ALIAS
4967 ",cyls=%d,heads=%d,secs=%d%s",
4968 0, cyls, heads, secs,
4969 translation == BIOS_ATA_TRANSLATION_LBA ?
4970 ",trans=lba" :
4971 translation == BIOS_ATA_TRANSLATION_NONE ?
4972 ",trans=none" : "");
4973 break;
4974 case QEMU_OPTION_hdb:
4975 case QEMU_OPTION_hdc:
4976 case QEMU_OPTION_hdd:
4977 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4978 break;
4979 case QEMU_OPTION_drive:
4980 drive_add(NULL, "%s", optarg);
4981 break;
4982 case QEMU_OPTION_set:
4983 if (qemu_set_option(optarg) != 0)
4984 exit(1);
4985 break;
4986 case QEMU_OPTION_global:
4987 if (qemu_global_option(optarg) != 0)
4988 exit(1);
4989 break;
4990 case QEMU_OPTION_mtdblock:
4991 drive_add(optarg, MTD_ALIAS);
4992 break;
4993 case QEMU_OPTION_sd:
4994 drive_add(optarg, SD_ALIAS);
4995 break;
4996 case QEMU_OPTION_pflash:
4997 drive_add(optarg, PFLASH_ALIAS);
4998 break;
4999 case QEMU_OPTION_snapshot:
5000 snapshot = 1;
5001 break;
5002 case QEMU_OPTION_hdachs:
5004 const char *p;
5005 p = optarg;
5006 cyls = strtol(p, (char **)&p, 0);
5007 if (cyls < 1 || cyls > 16383)
5008 goto chs_fail;
5009 if (*p != ',')
5010 goto chs_fail;
5011 p++;
5012 heads = strtol(p, (char **)&p, 0);
5013 if (heads < 1 || heads > 16)
5014 goto chs_fail;
5015 if (*p != ',')
5016 goto chs_fail;
5017 p++;
5018 secs = strtol(p, (char **)&p, 0);
5019 if (secs < 1 || secs > 63)
5020 goto chs_fail;
5021 if (*p == ',') {
5022 p++;
5023 if (!strcmp(p, "none"))
5024 translation = BIOS_ATA_TRANSLATION_NONE;
5025 else if (!strcmp(p, "lba"))
5026 translation = BIOS_ATA_TRANSLATION_LBA;
5027 else if (!strcmp(p, "auto"))
5028 translation = BIOS_ATA_TRANSLATION_AUTO;
5029 else
5030 goto chs_fail;
5031 } else if (*p != '\0') {
5032 chs_fail:
5033 fprintf(stderr, "qemu: invalid physical CHS format\n");
5034 exit(1);
5036 if (hda_opts != NULL) {
5037 char num[16];
5038 snprintf(num, sizeof(num), "%d", cyls);
5039 qemu_opt_set(hda_opts, "cyls", num);
5040 snprintf(num, sizeof(num), "%d", heads);
5041 qemu_opt_set(hda_opts, "heads", num);
5042 snprintf(num, sizeof(num), "%d", secs);
5043 qemu_opt_set(hda_opts, "secs", num);
5044 if (translation == BIOS_ATA_TRANSLATION_LBA)
5045 qemu_opt_set(hda_opts, "trans", "lba");
5046 if (translation == BIOS_ATA_TRANSLATION_NONE)
5047 qemu_opt_set(hda_opts, "trans", "none");
5050 break;
5051 case QEMU_OPTION_numa:
5052 if (nb_numa_nodes >= MAX_NODES) {
5053 fprintf(stderr, "qemu: too many NUMA nodes\n");
5054 exit(1);
5056 numa_add(optarg);
5057 break;
5058 case QEMU_OPTION_nographic:
5059 display_type = DT_NOGRAPHIC;
5060 break;
5061 #ifdef CONFIG_CURSES
5062 case QEMU_OPTION_curses:
5063 display_type = DT_CURSES;
5064 break;
5065 #endif
5066 case QEMU_OPTION_portrait:
5067 graphic_rotate = 1;
5068 break;
5069 case QEMU_OPTION_kernel:
5070 kernel_filename = optarg;
5071 break;
5072 case QEMU_OPTION_append:
5073 kernel_cmdline = optarg;
5074 break;
5075 case QEMU_OPTION_cdrom:
5076 drive_add(optarg, CDROM_ALIAS);
5077 break;
5078 case QEMU_OPTION_boot:
5080 static const char * const params[] = {
5081 "order", "once", "menu", NULL
5083 char buf[sizeof(boot_devices)];
5084 char *standard_boot_devices;
5085 int legacy = 0;
5087 if (!strchr(optarg, '=')) {
5088 legacy = 1;
5089 pstrcpy(buf, sizeof(buf), optarg);
5090 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5091 fprintf(stderr,
5092 "qemu: unknown boot parameter '%s' in '%s'\n",
5093 buf, optarg);
5094 exit(1);
5097 if (legacy ||
5098 get_param_value(buf, sizeof(buf), "order", optarg)) {
5099 boot_devices_bitmap = parse_bootdevices(buf);
5100 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5102 if (!legacy) {
5103 if (get_param_value(buf, sizeof(buf),
5104 "once", optarg)) {
5105 boot_devices_bitmap |= parse_bootdevices(buf);
5106 standard_boot_devices = qemu_strdup(boot_devices);
5107 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5108 qemu_register_reset(restore_boot_devices,
5109 standard_boot_devices);
5111 if (get_param_value(buf, sizeof(buf),
5112 "menu", optarg)) {
5113 if (!strcmp(buf, "on")) {
5114 boot_menu = 1;
5115 } else if (!strcmp(buf, "off")) {
5116 boot_menu = 0;
5117 } else {
5118 fprintf(stderr,
5119 "qemu: invalid option value '%s'\n",
5120 buf);
5121 exit(1);
5126 break;
5127 case QEMU_OPTION_fda:
5128 case QEMU_OPTION_fdb:
5129 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5130 break;
5131 #ifdef TARGET_I386
5132 case QEMU_OPTION_no_fd_bootchk:
5133 fd_bootchk = 0;
5134 break;
5135 #endif
5136 case QEMU_OPTION_netdev:
5137 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5138 exit(1);
5140 break;
5141 case QEMU_OPTION_net:
5142 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5143 exit(1);
5145 break;
5146 #ifdef CONFIG_SLIRP
5147 case QEMU_OPTION_tftp:
5148 legacy_tftp_prefix = optarg;
5149 break;
5150 case QEMU_OPTION_bootp:
5151 legacy_bootp_filename = optarg;
5152 break;
5153 #ifndef _WIN32
5154 case QEMU_OPTION_smb:
5155 if (net_slirp_smb(optarg) < 0)
5156 exit(1);
5157 break;
5158 #endif
5159 case QEMU_OPTION_redir:
5160 if (net_slirp_redir(optarg) < 0)
5161 exit(1);
5162 break;
5163 #endif
5164 case QEMU_OPTION_bt:
5165 add_device_config(DEV_BT, optarg);
5166 break;
5167 #ifdef HAS_AUDIO
5168 case QEMU_OPTION_audio_help:
5169 AUD_help ();
5170 exit (0);
5171 break;
5172 case QEMU_OPTION_soundhw:
5173 select_soundhw (optarg);
5174 break;
5175 #endif
5176 case QEMU_OPTION_h:
5177 help(0);
5178 break;
5179 case QEMU_OPTION_version:
5180 version();
5181 exit(0);
5182 break;
5183 case QEMU_OPTION_m: {
5184 uint64_t value;
5185 char *ptr;
5187 value = strtoul(optarg, &ptr, 10);
5188 switch (*ptr) {
5189 case 0: case 'M': case 'm':
5190 value <<= 20;
5191 break;
5192 case 'G': case 'g':
5193 value <<= 30;
5194 break;
5195 default:
5196 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5197 exit(1);
5200 /* On 32-bit hosts, QEMU is limited by virtual address space */
5201 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5202 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5203 exit(1);
5205 if (value != (uint64_t)(ram_addr_t)value) {
5206 fprintf(stderr, "qemu: ram size too large\n");
5207 exit(1);
5209 ram_size = value;
5210 break;
5212 case QEMU_OPTION_d:
5214 int mask;
5215 const CPULogItem *item;
5217 mask = cpu_str_to_log_mask(optarg);
5218 if (!mask) {
5219 printf("Log items (comma separated):\n");
5220 for(item = cpu_log_items; item->mask != 0; item++) {
5221 printf("%-10s %s\n", item->name, item->help);
5223 exit(1);
5225 cpu_set_log(mask);
5227 break;
5228 case QEMU_OPTION_s:
5229 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5230 break;
5231 case QEMU_OPTION_gdb:
5232 gdbstub_dev = optarg;
5233 break;
5234 case QEMU_OPTION_L:
5235 data_dir = optarg;
5236 break;
5237 case QEMU_OPTION_bios:
5238 bios_name = optarg;
5239 break;
5240 case QEMU_OPTION_singlestep:
5241 singlestep = 1;
5242 break;
5243 case QEMU_OPTION_S:
5244 autostart = 0;
5245 break;
5246 case QEMU_OPTION_k:
5247 keyboard_layout = optarg;
5248 break;
5249 case QEMU_OPTION_localtime:
5250 rtc_utc = 0;
5251 break;
5252 case QEMU_OPTION_vga:
5253 select_vgahw (optarg);
5254 break;
5255 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5256 case QEMU_OPTION_g:
5258 const char *p;
5259 int w, h, depth;
5260 p = optarg;
5261 w = strtol(p, (char **)&p, 10);
5262 if (w <= 0) {
5263 graphic_error:
5264 fprintf(stderr, "qemu: invalid resolution or depth\n");
5265 exit(1);
5267 if (*p != 'x')
5268 goto graphic_error;
5269 p++;
5270 h = strtol(p, (char **)&p, 10);
5271 if (h <= 0)
5272 goto graphic_error;
5273 if (*p == 'x') {
5274 p++;
5275 depth = strtol(p, (char **)&p, 10);
5276 if (depth != 8 && depth != 15 && depth != 16 &&
5277 depth != 24 && depth != 32)
5278 goto graphic_error;
5279 } else if (*p == '\0') {
5280 depth = graphic_depth;
5281 } else {
5282 goto graphic_error;
5285 graphic_width = w;
5286 graphic_height = h;
5287 graphic_depth = depth;
5289 break;
5290 #endif
5291 case QEMU_OPTION_echr:
5293 char *r;
5294 term_escape_char = strtol(optarg, &r, 0);
5295 if (r == optarg)
5296 printf("Bad argument to echr\n");
5297 break;
5299 case QEMU_OPTION_monitor:
5300 monitor_parse(optarg, "readline");
5301 default_monitor = 0;
5302 break;
5303 case QEMU_OPTION_qmp:
5304 monitor_parse(optarg, "control");
5305 default_monitor = 0;
5306 break;
5307 case QEMU_OPTION_mon:
5308 opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5309 if (!opts) {
5310 fprintf(stderr, "parse error: %s\n", optarg);
5311 exit(1);
5313 default_monitor = 0;
5314 break;
5315 case QEMU_OPTION_chardev:
5316 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5317 if (!opts) {
5318 fprintf(stderr, "parse error: %s\n", optarg);
5319 exit(1);
5321 break;
5322 case QEMU_OPTION_serial:
5323 add_device_config(DEV_SERIAL, optarg);
5324 default_serial = 0;
5325 break;
5326 case QEMU_OPTION_watchdog:
5327 if (watchdog) {
5328 fprintf(stderr,
5329 "qemu: only one watchdog option may be given\n");
5330 return 1;
5332 watchdog = optarg;
5333 break;
5334 case QEMU_OPTION_watchdog_action:
5335 if (select_watchdog_action(optarg) == -1) {
5336 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5337 exit(1);
5339 break;
5340 case QEMU_OPTION_virtiocon:
5341 add_device_config(DEV_VIRTCON, optarg);
5342 default_virtcon = 0;
5343 break;
5344 case QEMU_OPTION_parallel:
5345 add_device_config(DEV_PARALLEL, optarg);
5346 default_parallel = 0;
5347 break;
5348 case QEMU_OPTION_debugcon:
5349 add_device_config(DEV_DEBUGCON, optarg);
5350 break;
5351 case QEMU_OPTION_loadvm:
5352 loadvm = optarg;
5353 break;
5354 case QEMU_OPTION_full_screen:
5355 full_screen = 1;
5356 break;
5357 #ifdef CONFIG_SDL
5358 case QEMU_OPTION_no_frame:
5359 no_frame = 1;
5360 break;
5361 case QEMU_OPTION_alt_grab:
5362 alt_grab = 1;
5363 break;
5364 case QEMU_OPTION_ctrl_grab:
5365 ctrl_grab = 1;
5366 break;
5367 case QEMU_OPTION_no_quit:
5368 no_quit = 1;
5369 break;
5370 case QEMU_OPTION_sdl:
5371 display_type = DT_SDL;
5372 break;
5373 #endif
5374 case QEMU_OPTION_pidfile:
5375 pid_file = optarg;
5376 break;
5377 #ifdef TARGET_I386
5378 case QEMU_OPTION_win2k_hack:
5379 win2k_install_hack = 1;
5380 break;
5381 case QEMU_OPTION_rtc_td_hack:
5382 rtc_td_hack = 1;
5383 break;
5384 case QEMU_OPTION_acpitable:
5385 if(acpi_table_add(optarg) < 0) {
5386 fprintf(stderr, "Wrong acpi table provided\n");
5387 exit(1);
5389 break;
5390 case QEMU_OPTION_smbios:
5391 if(smbios_entry_add(optarg) < 0) {
5392 fprintf(stderr, "Wrong smbios provided\n");
5393 exit(1);
5395 break;
5396 #endif
5397 #ifdef CONFIG_KVM
5398 #ifdef KVM_UPSTREAM
5399 case QEMU_OPTION_enable_kvm:
5400 kvm_allowed = 1;
5401 #endif
5402 break;
5403 case QEMU_OPTION_no_kvm:
5404 kvm_allowed = 0;
5405 break;
5406 case QEMU_OPTION_no_kvm_irqchip: {
5407 kvm_irqchip = 0;
5408 kvm_pit = 0;
5409 break;
5411 case QEMU_OPTION_no_kvm_pit: {
5412 kvm_pit = 0;
5413 break;
5415 case QEMU_OPTION_no_kvm_pit_reinjection: {
5416 kvm_pit_reinject = 0;
5417 break;
5419 case QEMU_OPTION_enable_nesting: {
5420 kvm_nested = 1;
5421 break;
5423 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5424 case QEMU_OPTION_pcidevice:
5425 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5426 fprintf(stderr, "Too many assigned devices\n");
5427 exit(1);
5429 assigned_devices[assigned_devices_index] = optarg;
5430 assigned_devices_index++;
5431 break;
5432 #endif
5433 #endif
5434 case QEMU_OPTION_usb:
5435 usb_enabled = 1;
5436 break;
5437 case QEMU_OPTION_usbdevice:
5438 usb_enabled = 1;
5439 add_device_config(DEV_USB, optarg);
5440 break;
5441 case QEMU_OPTION_device:
5442 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5443 exit(1);
5445 break;
5446 case QEMU_OPTION_smp:
5447 smp_parse(optarg);
5448 if (smp_cpus < 1) {
5449 fprintf(stderr, "Invalid number of CPUs\n");
5450 exit(1);
5452 if (max_cpus < smp_cpus) {
5453 fprintf(stderr, "maxcpus must be equal to or greater than "
5454 "smp\n");
5455 exit(1);
5457 if (max_cpus > 255) {
5458 fprintf(stderr, "Unsupported number of maxcpus\n");
5459 exit(1);
5461 break;
5462 case QEMU_OPTION_vnc:
5463 display_type = DT_VNC;
5464 vnc_display = optarg;
5465 break;
5466 #ifdef TARGET_I386
5467 case QEMU_OPTION_no_acpi:
5468 acpi_enabled = 0;
5469 break;
5470 case QEMU_OPTION_no_hpet:
5471 no_hpet = 1;
5472 break;
5473 case QEMU_OPTION_balloon:
5474 if (balloon_parse(optarg) < 0) {
5475 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5476 exit(1);
5478 break;
5479 #endif
5480 case QEMU_OPTION_no_reboot:
5481 no_reboot = 1;
5482 break;
5483 case QEMU_OPTION_no_shutdown:
5484 no_shutdown = 1;
5485 break;
5486 case QEMU_OPTION_show_cursor:
5487 cursor_hide = 0;
5488 break;
5489 case QEMU_OPTION_uuid:
5490 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5491 fprintf(stderr, "Fail to parse UUID string."
5492 " Wrong format.\n");
5493 exit(1);
5495 break;
5496 #ifndef _WIN32
5497 case QEMU_OPTION_daemonize:
5498 daemonize = 1;
5499 break;
5500 #endif
5501 case QEMU_OPTION_option_rom:
5502 if (nb_option_roms >= MAX_OPTION_ROMS) {
5503 fprintf(stderr, "Too many option ROMs\n");
5504 exit(1);
5506 option_rom[nb_option_roms] = optarg;
5507 nb_option_roms++;
5508 break;
5509 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5510 case QEMU_OPTION_semihosting:
5511 semihosting_enabled = 1;
5512 break;
5513 #endif
5514 case QEMU_OPTION_tdf:
5515 time_drift_fix = 1;
5516 break;
5517 case QEMU_OPTION_kvm_shadow_memory:
5518 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5519 break;
5520 case QEMU_OPTION_mempath:
5521 mem_path = optarg;
5522 break;
5523 #ifdef MAP_POPULATE
5524 case QEMU_OPTION_mem_prealloc:
5525 mem_prealloc = !mem_prealloc;
5526 break;
5527 #endif
5528 case QEMU_OPTION_name:
5529 qemu_name = qemu_strdup(optarg);
5531 char *p = strchr(qemu_name, ',');
5532 if (p != NULL) {
5533 *p++ = 0;
5534 if (strncmp(p, "process=", 8)) {
5535 fprintf(stderr, "Unknown subargument %s to -name", p);
5536 exit(1);
5538 p += 8;
5539 set_proc_name(p);
5542 break;
5543 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5544 case QEMU_OPTION_prom_env:
5545 if (nb_prom_envs >= MAX_PROM_ENVS) {
5546 fprintf(stderr, "Too many prom variables\n");
5547 exit(1);
5549 prom_envs[nb_prom_envs] = optarg;
5550 nb_prom_envs++;
5551 break;
5552 #endif
5553 #ifdef TARGET_ARM
5554 case QEMU_OPTION_old_param:
5555 old_param = 1;
5556 break;
5557 #endif
5558 case QEMU_OPTION_clock:
5559 configure_alarms(optarg);
5560 break;
5561 case QEMU_OPTION_startdate:
5562 configure_rtc_date_offset(optarg, 1);
5563 break;
5564 case QEMU_OPTION_rtc:
5565 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5566 if (!opts) {
5567 fprintf(stderr, "parse error: %s\n", optarg);
5568 exit(1);
5570 configure_rtc(opts);
5571 break;
5572 case QEMU_OPTION_tb_size:
5573 tb_size = strtol(optarg, NULL, 0);
5574 if (tb_size < 0)
5575 tb_size = 0;
5576 break;
5577 case QEMU_OPTION_icount:
5578 use_icount = 1;
5579 if (strcmp(optarg, "auto") == 0) {
5580 icount_time_shift = -1;
5581 } else {
5582 icount_time_shift = strtol(optarg, NULL, 0);
5584 break;
5585 case QEMU_OPTION_incoming:
5586 incoming = optarg;
5587 break;
5588 case QEMU_OPTION_nodefaults:
5589 default_serial = 0;
5590 default_parallel = 0;
5591 default_virtcon = 0;
5592 default_monitor = 0;
5593 default_vga = 0;
5594 default_net = 0;
5595 default_floppy = 0;
5596 default_cdrom = 0;
5597 default_sdcard = 0;
5598 break;
5599 #ifndef _WIN32
5600 case QEMU_OPTION_chroot:
5601 chroot_dir = optarg;
5602 break;
5603 case QEMU_OPTION_runas:
5604 run_as = optarg;
5605 break;
5606 case QEMU_OPTION_nvram:
5607 nvram = optarg;
5608 break;
5609 #endif
5610 #ifdef CONFIG_XEN
5611 case QEMU_OPTION_xen_domid:
5612 xen_domid = atoi(optarg);
5613 break;
5614 case QEMU_OPTION_xen_create:
5615 xen_mode = XEN_CREATE;
5616 break;
5617 case QEMU_OPTION_xen_attach:
5618 xen_mode = XEN_ATTACH;
5619 break;
5620 #endif
5621 case QEMU_OPTION_readconfig:
5623 FILE *fp;
5624 fp = fopen(optarg, "r");
5625 if (fp == NULL) {
5626 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5627 exit(1);
5629 if (qemu_config_parse(fp) != 0) {
5630 exit(1);
5632 fclose(fp);
5633 break;
5635 case QEMU_OPTION_writeconfig:
5637 FILE *fp;
5638 if (strcmp(optarg, "-") == 0) {
5639 fp = stdout;
5640 } else {
5641 fp = fopen(optarg, "w");
5642 if (fp == NULL) {
5643 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5644 exit(1);
5647 qemu_config_write(fp);
5648 fclose(fp);
5649 break;
5655 /* If no data_dir is specified then try to find it relative to the
5656 executable path. */
5657 if (!data_dir) {
5658 data_dir = find_datadir(argv[0]);
5660 /* If all else fails use the install patch specified when building. */
5661 if (!data_dir) {
5662 data_dir = CONFIG_QEMU_SHAREDIR;
5666 * Default to max_cpus = smp_cpus, in case the user doesn't
5667 * specify a max_cpus value.
5669 if (!max_cpus)
5670 max_cpus = smp_cpus;
5672 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5673 if (smp_cpus > machine->max_cpus) {
5674 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5675 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5676 machine->max_cpus);
5677 exit(1);
5680 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5681 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5683 if (machine->no_serial) {
5684 default_serial = 0;
5686 if (machine->no_parallel) {
5687 default_parallel = 0;
5689 if (!machine->use_virtcon) {
5690 default_virtcon = 0;
5692 if (machine->no_vga) {
5693 default_vga = 0;
5695 if (machine->no_floppy) {
5696 default_floppy = 0;
5698 if (machine->no_cdrom) {
5699 default_cdrom = 0;
5701 if (machine->no_sdcard) {
5702 default_sdcard = 0;
5705 if (display_type == DT_NOGRAPHIC) {
5706 if (default_parallel)
5707 add_device_config(DEV_PARALLEL, "null");
5708 if (default_serial && default_monitor) {
5709 add_device_config(DEV_SERIAL, "mon:stdio");
5710 } else if (default_virtcon && default_monitor) {
5711 add_device_config(DEV_VIRTCON, "mon:stdio");
5712 } else {
5713 if (default_serial)
5714 add_device_config(DEV_SERIAL, "stdio");
5715 if (default_virtcon)
5716 add_device_config(DEV_VIRTCON, "stdio");
5717 if (default_monitor)
5718 monitor_parse("stdio", "readline");
5720 } else {
5721 if (default_serial)
5722 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5723 if (default_parallel)
5724 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5725 if (default_monitor)
5726 monitor_parse("vc:80Cx24C", "readline");
5727 if (default_virtcon)
5728 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5730 if (default_vga)
5731 vga_interface_type = VGA_CIRRUS;
5733 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5734 exit(1);
5736 #ifndef _WIN32
5737 if (daemonize) {
5738 pid_t pid;
5740 if (pipe(fds) == -1)
5741 exit(1);
5743 pid = fork();
5744 if (pid > 0) {
5745 uint8_t status;
5746 ssize_t len;
5748 close(fds[1]);
5750 again:
5751 len = read(fds[0], &status, 1);
5752 if (len == -1 && (errno == EINTR))
5753 goto again;
5755 if (len != 1)
5756 exit(1);
5757 else if (status == 1) {
5758 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5759 exit(1);
5760 } else
5761 exit(0);
5762 } else if (pid < 0)
5763 exit(1);
5765 close(fds[0]);
5766 qemu_set_cloexec(fds[1]);
5768 setsid();
5770 pid = fork();
5771 if (pid > 0)
5772 exit(0);
5773 else if (pid < 0)
5774 exit(1);
5776 umask(027);
5778 signal(SIGTSTP, SIG_IGN);
5779 signal(SIGTTOU, SIG_IGN);
5780 signal(SIGTTIN, SIG_IGN);
5782 #endif
5784 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5785 #ifndef _WIN32
5786 if (daemonize) {
5787 uint8_t status = 1;
5788 if (write(fds[1], &status, 1) != 1) {
5789 perror("daemonize. Writing to pipe\n");
5791 } else
5792 #endif
5793 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5794 exit(1);
5797 if (kvm_enabled()) {
5798 int ret;
5800 ret = kvm_init(smp_cpus);
5801 if (ret < 0) {
5802 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5803 fprintf(stderr, "failed to initialize KVM\n");
5804 exit(1);
5805 #endif
5806 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5807 kvm_allowed = 0;
5811 if (qemu_init_main_loop()) {
5812 fprintf(stderr, "qemu_init_main_loop failed\n");
5813 exit(1);
5815 linux_boot = (kernel_filename != NULL);
5817 if (!linux_boot && *kernel_cmdline != '\0') {
5818 fprintf(stderr, "-append only allowed with -kernel option\n");
5819 exit(1);
5822 if (!linux_boot && initrd_filename != NULL) {
5823 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5824 exit(1);
5827 #ifndef _WIN32
5828 /* Win32 doesn't support line-buffering and requires size >= 2 */
5829 setvbuf(stdout, NULL, _IOLBF, 0);
5830 #endif
5832 if (init_timer_alarm() < 0) {
5833 fprintf(stderr, "could not initialize alarm timer\n");
5834 exit(1);
5836 if (use_icount && icount_time_shift < 0) {
5837 use_icount = 2;
5838 /* 125MIPS seems a reasonable initial guess at the guest speed.
5839 It will be corrected fairly quickly anyway. */
5840 icount_time_shift = 3;
5841 init_icount_adjust();
5844 #ifdef _WIN32
5845 socket_init();
5846 #endif
5848 if (net_init_clients() < 0) {
5849 exit(1);
5852 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5853 net_set_boot_mask(net_boot);
5855 /* init the bluetooth world */
5856 if (foreach_device_config(DEV_BT, bt_parse))
5857 exit(1);
5859 /* init the memory */
5860 if (ram_size == 0)
5861 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5863 /* init the dynamic translator */
5864 cpu_exec_init_all(tb_size * 1024 * 1024);
5866 bdrv_init_with_whitelist();
5868 blk_mig_init();
5870 if (default_cdrom) {
5871 /* we always create the cdrom drive, even if no disk is there */
5872 drive_add(NULL, CDROM_ALIAS);
5875 if (default_floppy) {
5876 /* we always create at least one floppy */
5877 drive_add(NULL, FD_ALIAS, 0);
5880 if (default_sdcard) {
5881 /* we always create one sd slot, even if no card is in it */
5882 drive_add(NULL, SD_ALIAS);
5885 /* open the virtual block devices */
5886 if (snapshot)
5887 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5888 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5889 exit(1);
5891 vmstate_register(0, &vmstate_timers ,&timers_state);
5892 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5893 ram_load, NULL);
5895 if (nb_numa_nodes > 0) {
5896 int i;
5898 if (nb_numa_nodes > smp_cpus) {
5899 nb_numa_nodes = smp_cpus;
5902 /* If no memory size if given for any node, assume the default case
5903 * and distribute the available memory equally across all nodes
5905 for (i = 0; i < nb_numa_nodes; i++) {
5906 if (node_mem[i] != 0)
5907 break;
5909 if (i == nb_numa_nodes) {
5910 uint64_t usedmem = 0;
5912 /* On Linux, the each node's border has to be 8MB aligned,
5913 * the final node gets the rest.
5915 for (i = 0; i < nb_numa_nodes - 1; i++) {
5916 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5917 usedmem += node_mem[i];
5919 node_mem[i] = ram_size - usedmem;
5922 for (i = 0; i < nb_numa_nodes; i++) {
5923 if (node_cpumask[i] != 0)
5924 break;
5926 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5927 * must cope with this anyway, because there are BIOSes out there in
5928 * real machines which also use this scheme.
5930 if (i == nb_numa_nodes) {
5931 for (i = 0; i < smp_cpus; i++) {
5932 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5937 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5938 exit(1);
5939 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5940 exit(1);
5941 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5942 exit(1);
5943 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5944 exit(1);
5946 module_call_init(MODULE_INIT_DEVICE);
5948 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
5949 exit(0);
5951 if (watchdog) {
5952 i = select_watchdog(watchdog);
5953 if (i > 0)
5954 exit (i == 1 ? 1 : 0);
5957 if (machine->compat_props) {
5958 qdev_prop_register_global_list(machine->compat_props);
5960 qemu_add_globals();
5962 machine->init(ram_size, boot_devices,
5963 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5966 #ifndef _WIN32
5967 /* must be after terminal init, SDL library changes signal handlers */
5968 sighandler_setup();
5969 #endif
5971 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5972 for (i = 0; i < nb_numa_nodes; i++) {
5973 if (node_cpumask[i] & (1 << env->cpu_index)) {
5974 env->numa_node = i;
5979 current_machine = machine;
5981 /* init USB devices */
5982 if (usb_enabled) {
5983 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5984 exit(1);
5987 /* init generic devices */
5988 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5989 exit(1);
5991 if (!display_state)
5992 dumb_display_init();
5993 /* just use the first displaystate for the moment */
5994 ds = display_state;
5996 if (display_type == DT_DEFAULT) {
5997 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5998 display_type = DT_SDL;
5999 #else
6000 display_type = DT_VNC;
6001 vnc_display = "localhost:0,to=99";
6002 show_vnc_port = 1;
6003 #endif
6007 switch (display_type) {
6008 case DT_NOGRAPHIC:
6009 break;
6010 #if defined(CONFIG_CURSES)
6011 case DT_CURSES:
6012 curses_display_init(ds, full_screen);
6013 break;
6014 #endif
6015 #if defined(CONFIG_SDL)
6016 case DT_SDL:
6017 sdl_display_init(ds, full_screen, no_frame);
6018 break;
6019 #elif defined(CONFIG_COCOA)
6020 case DT_SDL:
6021 cocoa_display_init(ds, full_screen);
6022 break;
6023 #endif
6024 case DT_VNC:
6025 vnc_display_init(ds);
6026 if (vnc_display_open(ds, vnc_display) < 0)
6027 exit(1);
6029 if (show_vnc_port) {
6030 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6032 break;
6033 default:
6034 break;
6036 dpy_resize(ds);
6038 dcl = ds->listeners;
6039 while (dcl != NULL) {
6040 if (dcl->dpy_refresh != NULL) {
6041 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6042 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6044 dcl = dcl->next;
6047 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6048 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6049 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6052 text_consoles_set_display(display_state);
6054 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6055 exit(1);
6057 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6058 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6059 gdbstub_dev);
6060 exit(1);
6063 qdev_machine_creation_done();
6065 if (rom_load_all() != 0) {
6066 fprintf(stderr, "rom loading failed\n");
6067 exit(1);
6070 qemu_system_reset();
6071 if (loadvm) {
6072 if (load_vmstate(cur_mon, loadvm) < 0) {
6073 autostart = 0;
6077 if (incoming) {
6078 qemu_start_incoming_migration(incoming);
6079 } else if (autostart) {
6080 vm_start();
6083 #ifndef _WIN32
6084 if (daemonize) {
6085 uint8_t status = 0;
6086 ssize_t len;
6088 again1:
6089 len = write(fds[1], &status, 1);
6090 if (len == -1 && (errno == EINTR))
6091 goto again1;
6093 if (len != 1)
6094 exit(1);
6096 if (chdir("/")) {
6097 perror("not able to chdir to /");
6098 exit(1);
6100 TFR(fd = qemu_open("/dev/null", O_RDWR));
6101 if (fd == -1)
6102 exit(1);
6105 if (run_as) {
6106 pwd = getpwnam(run_as);
6107 if (!pwd) {
6108 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6109 exit(1);
6113 if (chroot_dir) {
6114 if (chroot(chroot_dir) < 0) {
6115 fprintf(stderr, "chroot failed\n");
6116 exit(1);
6118 if (chdir("/")) {
6119 perror("not able to chdir to /");
6120 exit(1);
6124 if (run_as) {
6125 if (setgid(pwd->pw_gid) < 0) {
6126 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6127 exit(1);
6129 if (setuid(pwd->pw_uid) < 0) {
6130 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6131 exit(1);
6133 if (setuid(0) != -1) {
6134 fprintf(stderr, "Dropping privileges failed\n");
6135 exit(1);
6139 if (daemonize) {
6140 dup2(fd, 0);
6141 dup2(fd, 1);
6142 dup2(fd, 2);
6144 close(fd);
6146 #endif
6148 main_loop();
6149 quit_timers();
6150 net_cleanup();
6152 return 0;