Try not to exceed max downtime on stage3
[qemu/ar7.git] / vl.c
blobb87044c53c11eb6dc797ea4e87c6765f9487aa71
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"
161 #include "disas.h"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #include "slirp/libslirp.h"
169 #include "qemu-queue.h"
171 //#define DEBUG_NET
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 #define MAX_VIRTIO_CONSOLES 1
178 static const char *data_dir;
179 const char *bios_name = NULL;
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
183 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
184 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
185 static DisplayState *display_state;
186 DisplayType display_type = DT_DEFAULT;
187 const char* keyboard_layout = NULL;
188 ram_addr_t ram_size;
189 int nb_nics;
190 NICInfo nd_table[MAX_NICS];
191 int vm_running;
192 int autostart;
193 static int rtc_utc = 1;
194 static int rtc_date_offset = -1; /* -1 means no change */
195 QEMUClock *rtc_clock;
196 int vga_interface_type = VGA_NONE;
197 #ifdef TARGET_SPARC
198 int graphic_width = 1024;
199 int graphic_height = 768;
200 int graphic_depth = 8;
201 #else
202 int graphic_width = 800;
203 int graphic_height = 600;
204 int graphic_depth = 15;
205 #endif
206 static int full_screen = 0;
207 #ifdef CONFIG_SDL
208 static int no_frame = 0;
209 #endif
210 int no_quit = 0;
211 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
212 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
213 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
214 #ifdef TARGET_I386
215 int win2k_install_hack = 0;
216 int rtc_td_hack = 0;
217 #endif
218 int usb_enabled = 0;
219 int singlestep = 0;
220 int smp_cpus = 1;
221 int max_cpus = 0;
222 int smp_cores = 1;
223 int smp_threads = 1;
224 const char *vnc_display;
225 int acpi_enabled = 1;
226 int no_hpet = 0;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int no_shutdown = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 uint8_t irq0override = 1;
233 #ifndef _WIN32
234 int daemonize = 0;
235 #endif
236 const char *watchdog;
237 const char *option_rom[MAX_OPTION_ROMS];
238 int nb_option_roms;
239 int semihosting_enabled = 0;
240 #ifdef TARGET_ARM
241 int old_param = 0;
242 #endif
243 const char *qemu_name;
244 int alt_grab = 0;
245 int ctrl_grab = 0;
246 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
247 unsigned int nb_prom_envs = 0;
248 const char *prom_envs[MAX_PROM_ENVS];
249 #endif
250 int boot_menu;
252 int nb_numa_nodes;
253 uint64_t node_mem[MAX_NODES];
254 uint64_t node_cpumask[MAX_NODES];
256 static CPUState *cur_cpu;
257 static CPUState *next_cpu;
258 static int timer_alarm_pending = 1;
259 /* Conversion factor from emulated instructions to virtual clock ticks. */
260 static int icount_time_shift;
261 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
262 #define MAX_ICOUNT_SHIFT 10
263 /* Compensate for varying guest execution speed. */
264 static int64_t qemu_icount_bias;
265 static QEMUTimer *icount_rt_timer;
266 static QEMUTimer *icount_vm_timer;
267 static QEMUTimer *nographic_timer;
269 uint8_t qemu_uuid[16];
271 static QEMUBootSetHandler *boot_set_handler;
272 static void *boot_set_opaque;
274 static int default_serial = 1;
275 static int default_parallel = 1;
276 static int default_virtcon = 1;
277 static int default_monitor = 1;
278 static int default_vga = 1;
279 static int default_floppy = 1;
280 static int default_cdrom = 1;
281 static int default_sdcard = 1;
283 static struct {
284 const char *driver;
285 int *flag;
286 } default_list[] = {
287 { .driver = "isa-serial", .flag = &default_serial },
288 { .driver = "isa-parallel", .flag = &default_parallel },
289 { .driver = "isa-fdc", .flag = &default_floppy },
290 { .driver = "ide-drive", .flag = &default_cdrom },
291 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
292 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
293 { .driver = "virtio-serial", .flag = &default_virtcon },
294 { .driver = "VGA", .flag = &default_vga },
295 { .driver = "cirrus-vga", .flag = &default_vga },
296 { .driver = "vmware-svga", .flag = &default_vga },
299 static int default_driver_check(QemuOpts *opts, void *opaque)
301 const char *driver = qemu_opt_get(opts, "driver");
302 int i;
304 if (!driver)
305 return 0;
306 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
307 if (strcmp(default_list[i].driver, driver) != 0)
308 continue;
309 *(default_list[i].flag) = 0;
311 return 0;
314 /***********************************************************/
315 /* x86 ISA bus support */
317 target_phys_addr_t isa_mem_base = 0;
318 PicState2 *isa_pic;
320 /***********************************************************/
321 void hw_error(const char *fmt, ...)
323 va_list ap;
324 CPUState *env;
326 va_start(ap, fmt);
327 fprintf(stderr, "qemu: hardware error: ");
328 vfprintf(stderr, fmt, ap);
329 fprintf(stderr, "\n");
330 for(env = first_cpu; env != NULL; env = env->next_cpu) {
331 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
332 #ifdef TARGET_I386
333 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
334 #else
335 cpu_dump_state(env, stderr, fprintf, 0);
336 #endif
338 va_end(ap);
339 abort();
342 static void set_proc_name(const char *s)
344 #if defined(__linux__) && defined(PR_SET_NAME)
345 char name[16];
346 if (!s)
347 return;
348 name[sizeof(name) - 1] = 0;
349 strncpy(name, s, sizeof(name));
350 /* Could rewrite argv[0] too, but that's a bit more complicated.
351 This simple way is enough for `top'. */
352 prctl(PR_SET_NAME, name);
353 #endif
356 /***************/
357 /* ballooning */
359 static QEMUBalloonEvent *qemu_balloon_event;
360 void *qemu_balloon_event_opaque;
362 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
364 qemu_balloon_event = func;
365 qemu_balloon_event_opaque = opaque;
368 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
370 if (qemu_balloon_event) {
371 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
372 return 1;
373 } else {
374 return 0;
378 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
380 if (qemu_balloon_event) {
381 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
382 return 1;
383 } else {
384 return 0;
389 /***********************************************************/
390 /* real time host monotonic timer */
392 /* compute with 96 bit intermediate result: (a*b)/c */
393 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
395 union {
396 uint64_t ll;
397 struct {
398 #ifdef HOST_WORDS_BIGENDIAN
399 uint32_t high, low;
400 #else
401 uint32_t low, high;
402 #endif
403 } l;
404 } u, res;
405 uint64_t rl, rh;
407 u.ll = a;
408 rl = (uint64_t)u.l.low * (uint64_t)b;
409 rh = (uint64_t)u.l.high * (uint64_t)b;
410 rh += (rl >> 32);
411 res.l.high = rh / c;
412 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
413 return res.ll;
416 static int64_t get_clock_realtime(void)
418 struct timeval tv;
420 gettimeofday(&tv, NULL);
421 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
424 #ifdef WIN32
426 static int64_t clock_freq;
428 static void init_get_clock(void)
430 LARGE_INTEGER freq;
431 int ret;
432 ret = QueryPerformanceFrequency(&freq);
433 if (ret == 0) {
434 fprintf(stderr, "Could not calibrate ticks\n");
435 exit(1);
437 clock_freq = freq.QuadPart;
440 static int64_t get_clock(void)
442 LARGE_INTEGER ti;
443 QueryPerformanceCounter(&ti);
444 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
447 #else
449 static int use_rt_clock;
451 static void init_get_clock(void)
453 use_rt_clock = 0;
454 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
455 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
457 struct timespec ts;
458 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
459 use_rt_clock = 1;
462 #endif
465 static int64_t get_clock(void)
467 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
468 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
469 if (use_rt_clock) {
470 struct timespec ts;
471 clock_gettime(CLOCK_MONOTONIC, &ts);
472 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
473 } else
474 #endif
476 /* XXX: using gettimeofday leads to problems if the date
477 changes, so it should be avoided. */
478 return get_clock_realtime();
481 #endif
483 /* Return the virtual CPU time, based on the instruction counter. */
484 static int64_t cpu_get_icount(void)
486 int64_t icount;
487 CPUState *env = cpu_single_env;;
488 icount = qemu_icount;
489 if (env) {
490 if (!can_do_io(env))
491 fprintf(stderr, "Bad clock read\n");
492 icount -= (env->icount_decr.u16.low + env->icount_extra);
494 return qemu_icount_bias + (icount << icount_time_shift);
497 /***********************************************************/
498 /* guest cycle counter */
500 typedef struct TimersState {
501 int64_t cpu_ticks_prev;
502 int64_t cpu_ticks_offset;
503 int64_t cpu_clock_offset;
504 int32_t cpu_ticks_enabled;
505 int64_t dummy;
506 } TimersState;
508 TimersState timers_state;
510 /* return the host CPU cycle counter and handle stop/restart */
511 int64_t cpu_get_ticks(void)
513 if (use_icount) {
514 return cpu_get_icount();
516 if (!timers_state.cpu_ticks_enabled) {
517 return timers_state.cpu_ticks_offset;
518 } else {
519 int64_t ticks;
520 ticks = cpu_get_real_ticks();
521 if (timers_state.cpu_ticks_prev > ticks) {
522 /* Note: non increasing ticks may happen if the host uses
523 software suspend */
524 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
526 timers_state.cpu_ticks_prev = ticks;
527 return ticks + timers_state.cpu_ticks_offset;
531 /* return the host CPU monotonic timer and handle stop/restart */
532 static int64_t cpu_get_clock(void)
534 int64_t ti;
535 if (!timers_state.cpu_ticks_enabled) {
536 return timers_state.cpu_clock_offset;
537 } else {
538 ti = get_clock();
539 return ti + timers_state.cpu_clock_offset;
543 /* enable cpu_get_ticks() */
544 void cpu_enable_ticks(void)
546 if (!timers_state.cpu_ticks_enabled) {
547 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
548 timers_state.cpu_clock_offset -= get_clock();
549 timers_state.cpu_ticks_enabled = 1;
553 /* disable cpu_get_ticks() : the clock is stopped. You must not call
554 cpu_get_ticks() after that. */
555 void cpu_disable_ticks(void)
557 if (timers_state.cpu_ticks_enabled) {
558 timers_state.cpu_ticks_offset = cpu_get_ticks();
559 timers_state.cpu_clock_offset = cpu_get_clock();
560 timers_state.cpu_ticks_enabled = 0;
564 /***********************************************************/
565 /* timers */
567 #define QEMU_CLOCK_REALTIME 0
568 #define QEMU_CLOCK_VIRTUAL 1
569 #define QEMU_CLOCK_HOST 2
571 struct QEMUClock {
572 int type;
573 /* XXX: add frequency */
576 struct QEMUTimer {
577 QEMUClock *clock;
578 int64_t expire_time;
579 QEMUTimerCB *cb;
580 void *opaque;
581 struct QEMUTimer *next;
584 struct qemu_alarm_timer {
585 char const *name;
586 unsigned int flags;
588 int (*start)(struct qemu_alarm_timer *t);
589 void (*stop)(struct qemu_alarm_timer *t);
590 void (*rearm)(struct qemu_alarm_timer *t);
591 void *priv;
594 #define ALARM_FLAG_DYNTICKS 0x1
595 #define ALARM_FLAG_EXPIRED 0x2
597 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
599 return t && (t->flags & ALARM_FLAG_DYNTICKS);
602 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
604 if (!alarm_has_dynticks(t))
605 return;
607 t->rearm(t);
610 /* TODO: MIN_TIMER_REARM_US should be optimized */
611 #define MIN_TIMER_REARM_US 250
613 static struct qemu_alarm_timer *alarm_timer;
615 #ifdef _WIN32
617 struct qemu_alarm_win32 {
618 MMRESULT timerId;
619 unsigned int period;
620 } alarm_win32_data = {0, -1};
622 static int win32_start_timer(struct qemu_alarm_timer *t);
623 static void win32_stop_timer(struct qemu_alarm_timer *t);
624 static void win32_rearm_timer(struct qemu_alarm_timer *t);
626 #else
628 static int unix_start_timer(struct qemu_alarm_timer *t);
629 static void unix_stop_timer(struct qemu_alarm_timer *t);
631 #ifdef __linux__
633 static int dynticks_start_timer(struct qemu_alarm_timer *t);
634 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
635 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
637 static int hpet_start_timer(struct qemu_alarm_timer *t);
638 static void hpet_stop_timer(struct qemu_alarm_timer *t);
640 static int rtc_start_timer(struct qemu_alarm_timer *t);
641 static void rtc_stop_timer(struct qemu_alarm_timer *t);
643 #endif /* __linux__ */
645 #endif /* _WIN32 */
647 /* Correlation between real and virtual time is always going to be
648 fairly approximate, so ignore small variation.
649 When the guest is idle real and virtual time will be aligned in
650 the IO wait loop. */
651 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
653 static void icount_adjust(void)
655 int64_t cur_time;
656 int64_t cur_icount;
657 int64_t delta;
658 static int64_t last_delta;
659 /* If the VM is not running, then do nothing. */
660 if (!vm_running)
661 return;
663 cur_time = cpu_get_clock();
664 cur_icount = qemu_get_clock(vm_clock);
665 delta = cur_icount - cur_time;
666 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
667 if (delta > 0
668 && last_delta + ICOUNT_WOBBLE < delta * 2
669 && icount_time_shift > 0) {
670 /* The guest is getting too far ahead. Slow time down. */
671 icount_time_shift--;
673 if (delta < 0
674 && last_delta - ICOUNT_WOBBLE > delta * 2
675 && icount_time_shift < MAX_ICOUNT_SHIFT) {
676 /* The guest is getting too far behind. Speed time up. */
677 icount_time_shift++;
679 last_delta = delta;
680 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
683 static void icount_adjust_rt(void * opaque)
685 qemu_mod_timer(icount_rt_timer,
686 qemu_get_clock(rt_clock) + 1000);
687 icount_adjust();
690 static void icount_adjust_vm(void * opaque)
692 qemu_mod_timer(icount_vm_timer,
693 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
694 icount_adjust();
697 static void init_icount_adjust(void)
699 /* Have both realtime and virtual time triggers for speed adjustment.
700 The realtime trigger catches emulated time passing too slowly,
701 the virtual time trigger catches emulated time passing too fast.
702 Realtime triggers occur even when idle, so use them less frequently
703 than VM triggers. */
704 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
705 qemu_mod_timer(icount_rt_timer,
706 qemu_get_clock(rt_clock) + 1000);
707 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
708 qemu_mod_timer(icount_vm_timer,
709 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
712 static struct qemu_alarm_timer alarm_timers[] = {
713 #ifndef _WIN32
714 #ifdef __linux__
715 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
716 dynticks_stop_timer, dynticks_rearm_timer, NULL},
717 /* HPET - if available - is preferred */
718 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
719 /* ...otherwise try RTC */
720 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
721 #endif
722 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
723 #else
724 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
725 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
726 {"win32", 0, win32_start_timer,
727 win32_stop_timer, NULL, &alarm_win32_data},
728 #endif
729 {NULL, }
732 static void show_available_alarms(void)
734 int i;
736 printf("Available alarm timers, in order of precedence:\n");
737 for (i = 0; alarm_timers[i].name; i++)
738 printf("%s\n", alarm_timers[i].name);
741 static void configure_alarms(char const *opt)
743 int i;
744 int cur = 0;
745 int count = ARRAY_SIZE(alarm_timers) - 1;
746 char *arg;
747 char *name;
748 struct qemu_alarm_timer tmp;
750 if (!strcmp(opt, "?")) {
751 show_available_alarms();
752 exit(0);
755 arg = qemu_strdup(opt);
757 /* Reorder the array */
758 name = strtok(arg, ",");
759 while (name) {
760 for (i = 0; i < count && alarm_timers[i].name; i++) {
761 if (!strcmp(alarm_timers[i].name, name))
762 break;
765 if (i == count) {
766 fprintf(stderr, "Unknown clock %s\n", name);
767 goto next;
770 if (i < cur)
771 /* Ignore */
772 goto next;
774 /* Swap */
775 tmp = alarm_timers[i];
776 alarm_timers[i] = alarm_timers[cur];
777 alarm_timers[cur] = tmp;
779 cur++;
780 next:
781 name = strtok(NULL, ",");
784 qemu_free(arg);
786 if (cur) {
787 /* Disable remaining timers */
788 for (i = cur; i < count; i++)
789 alarm_timers[i].name = NULL;
790 } else {
791 show_available_alarms();
792 exit(1);
796 #define QEMU_NUM_CLOCKS 3
798 QEMUClock *rt_clock;
799 QEMUClock *vm_clock;
800 QEMUClock *host_clock;
802 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
804 static QEMUClock *qemu_new_clock(int type)
806 QEMUClock *clock;
807 clock = qemu_mallocz(sizeof(QEMUClock));
808 clock->type = type;
809 return clock;
812 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
814 QEMUTimer *ts;
816 ts = qemu_mallocz(sizeof(QEMUTimer));
817 ts->clock = clock;
818 ts->cb = cb;
819 ts->opaque = opaque;
820 return ts;
823 void qemu_free_timer(QEMUTimer *ts)
825 qemu_free(ts);
828 /* stop a timer, but do not dealloc it */
829 void qemu_del_timer(QEMUTimer *ts)
831 QEMUTimer **pt, *t;
833 /* NOTE: this code must be signal safe because
834 qemu_timer_expired() can be called from a signal. */
835 pt = &active_timers[ts->clock->type];
836 for(;;) {
837 t = *pt;
838 if (!t)
839 break;
840 if (t == ts) {
841 *pt = t->next;
842 break;
844 pt = &t->next;
848 /* modify the current timer so that it will be fired when current_time
849 >= expire_time. The corresponding callback will be called. */
850 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
852 QEMUTimer **pt, *t;
854 qemu_del_timer(ts);
856 /* add the timer in the sorted list */
857 /* NOTE: this code must be signal safe because
858 qemu_timer_expired() can be called from a signal. */
859 pt = &active_timers[ts->clock->type];
860 for(;;) {
861 t = *pt;
862 if (!t)
863 break;
864 if (t->expire_time > expire_time)
865 break;
866 pt = &t->next;
868 ts->expire_time = expire_time;
869 ts->next = *pt;
870 *pt = ts;
872 /* Rearm if necessary */
873 if (pt == &active_timers[ts->clock->type]) {
874 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
875 qemu_rearm_alarm_timer(alarm_timer);
877 /* Interrupt execution to force deadline recalculation. */
878 if (use_icount)
879 qemu_notify_event();
883 int qemu_timer_pending(QEMUTimer *ts)
885 QEMUTimer *t;
886 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
887 if (t == ts)
888 return 1;
890 return 0;
893 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
895 if (!timer_head)
896 return 0;
897 return (timer_head->expire_time <= current_time);
900 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
902 QEMUTimer *ts;
904 for(;;) {
905 ts = *ptimer_head;
906 if (!ts || ts->expire_time > current_time)
907 break;
908 /* remove timer from the list before calling the callback */
909 *ptimer_head = ts->next;
910 ts->next = NULL;
912 /* run the callback (the timer list can be modified) */
913 ts->cb(ts->opaque);
917 int64_t qemu_get_clock(QEMUClock *clock)
919 switch(clock->type) {
920 case QEMU_CLOCK_REALTIME:
921 return get_clock() / 1000000;
922 default:
923 case QEMU_CLOCK_VIRTUAL:
924 if (use_icount) {
925 return cpu_get_icount();
926 } else {
927 return cpu_get_clock();
929 case QEMU_CLOCK_HOST:
930 return get_clock_realtime();
934 int64_t qemu_get_clock_ns(QEMUClock *clock)
936 switch(clock->type) {
937 case QEMU_CLOCK_REALTIME:
938 return get_clock();
939 default:
940 case QEMU_CLOCK_VIRTUAL:
941 if (use_icount) {
942 return cpu_get_icount();
943 } else {
944 return cpu_get_clock();
946 case QEMU_CLOCK_HOST:
947 return get_clock_realtime();
951 static void init_clocks(void)
953 init_get_clock();
954 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
955 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
956 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
958 rtc_clock = host_clock;
961 /* save a timer */
962 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
964 uint64_t expire_time;
966 if (qemu_timer_pending(ts)) {
967 expire_time = ts->expire_time;
968 } else {
969 expire_time = -1;
971 qemu_put_be64(f, expire_time);
974 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
976 uint64_t expire_time;
978 expire_time = qemu_get_be64(f);
979 if (expire_time != -1) {
980 qemu_mod_timer(ts, expire_time);
981 } else {
982 qemu_del_timer(ts);
986 static const VMStateDescription vmstate_timers = {
987 .name = "timer",
988 .version_id = 2,
989 .minimum_version_id = 1,
990 .minimum_version_id_old = 1,
991 .fields = (VMStateField []) {
992 VMSTATE_INT64(cpu_ticks_offset, TimersState),
993 VMSTATE_INT64(dummy, TimersState),
994 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
995 VMSTATE_END_OF_LIST()
999 static void qemu_event_increment(void);
1001 #ifdef _WIN32
1002 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1003 DWORD_PTR dwUser, DWORD_PTR dw1,
1004 DWORD_PTR dw2)
1005 #else
1006 static void host_alarm_handler(int host_signum)
1007 #endif
1009 #if 0
1010 #define DISP_FREQ 1000
1012 static int64_t delta_min = INT64_MAX;
1013 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1014 static int count;
1015 ti = qemu_get_clock(vm_clock);
1016 if (last_clock != 0) {
1017 delta = ti - last_clock;
1018 if (delta < delta_min)
1019 delta_min = delta;
1020 if (delta > delta_max)
1021 delta_max = delta;
1022 delta_cum += delta;
1023 if (++count == DISP_FREQ) {
1024 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1025 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1026 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1027 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1028 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1029 count = 0;
1030 delta_min = INT64_MAX;
1031 delta_max = 0;
1032 delta_cum = 0;
1035 last_clock = ti;
1037 #endif
1038 if (alarm_has_dynticks(alarm_timer) ||
1039 (!use_icount &&
1040 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1041 qemu_get_clock(vm_clock))) ||
1042 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1043 qemu_get_clock(rt_clock)) ||
1044 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1045 qemu_get_clock(host_clock))) {
1046 qemu_event_increment();
1047 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1049 #ifndef CONFIG_IOTHREAD
1050 if (next_cpu) {
1051 /* stop the currently executing cpu because a timer occured */
1052 cpu_exit(next_cpu);
1054 #endif
1055 timer_alarm_pending = 1;
1056 qemu_notify_event();
1060 static int64_t qemu_next_deadline(void)
1062 /* To avoid problems with overflow limit this to 2^32. */
1063 int64_t delta = INT32_MAX;
1065 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1066 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1067 qemu_get_clock(vm_clock);
1069 if (active_timers[QEMU_CLOCK_HOST]) {
1070 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1071 qemu_get_clock(host_clock);
1072 if (hdelta < delta)
1073 delta = hdelta;
1076 if (delta < 0)
1077 delta = 0;
1079 return delta;
1082 #if defined(__linux__)
1083 static uint64_t qemu_next_deadline_dyntick(void)
1085 int64_t delta;
1086 int64_t rtdelta;
1088 if (use_icount)
1089 delta = INT32_MAX;
1090 else
1091 delta = (qemu_next_deadline() + 999) / 1000;
1093 if (active_timers[QEMU_CLOCK_REALTIME]) {
1094 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1095 qemu_get_clock(rt_clock))*1000;
1096 if (rtdelta < delta)
1097 delta = rtdelta;
1100 if (delta < MIN_TIMER_REARM_US)
1101 delta = MIN_TIMER_REARM_US;
1103 return delta;
1105 #endif
1107 #ifndef _WIN32
1109 /* Sets a specific flag */
1110 static int fcntl_setfl(int fd, int flag)
1112 int flags;
1114 flags = fcntl(fd, F_GETFL);
1115 if (flags == -1)
1116 return -errno;
1118 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1119 return -errno;
1121 return 0;
1124 #if defined(__linux__)
1126 #define RTC_FREQ 1024
1128 static void enable_sigio_timer(int fd)
1130 struct sigaction act;
1132 /* timer signal */
1133 sigfillset(&act.sa_mask);
1134 act.sa_flags = 0;
1135 act.sa_handler = host_alarm_handler;
1137 sigaction(SIGIO, &act, NULL);
1138 fcntl_setfl(fd, O_ASYNC);
1139 fcntl(fd, F_SETOWN, getpid());
1142 static int hpet_start_timer(struct qemu_alarm_timer *t)
1144 struct hpet_info info;
1145 int r, fd;
1147 fd = qemu_open("/dev/hpet", O_RDONLY);
1148 if (fd < 0)
1149 return -1;
1151 /* Set frequency */
1152 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1153 if (r < 0) {
1154 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1155 "error, but for better emulation accuracy type:\n"
1156 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1157 goto fail;
1160 /* Check capabilities */
1161 r = ioctl(fd, HPET_INFO, &info);
1162 if (r < 0)
1163 goto fail;
1165 /* Enable periodic mode */
1166 r = ioctl(fd, HPET_EPI, 0);
1167 if (info.hi_flags && (r < 0))
1168 goto fail;
1170 /* Enable interrupt */
1171 r = ioctl(fd, HPET_IE_ON, 0);
1172 if (r < 0)
1173 goto fail;
1175 enable_sigio_timer(fd);
1176 t->priv = (void *)(long)fd;
1178 return 0;
1179 fail:
1180 close(fd);
1181 return -1;
1184 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1186 int fd = (long)t->priv;
1188 close(fd);
1191 static int rtc_start_timer(struct qemu_alarm_timer *t)
1193 int rtc_fd;
1194 unsigned long current_rtc_freq = 0;
1196 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1197 if (rtc_fd < 0)
1198 return -1;
1199 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1200 if (current_rtc_freq != RTC_FREQ &&
1201 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1202 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1203 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1204 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1205 goto fail;
1207 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1208 fail:
1209 close(rtc_fd);
1210 return -1;
1213 enable_sigio_timer(rtc_fd);
1215 t->priv = (void *)(long)rtc_fd;
1217 return 0;
1220 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1222 int rtc_fd = (long)t->priv;
1224 close(rtc_fd);
1227 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1229 struct sigevent ev;
1230 timer_t host_timer;
1231 struct sigaction act;
1233 sigfillset(&act.sa_mask);
1234 act.sa_flags = 0;
1235 act.sa_handler = host_alarm_handler;
1237 sigaction(SIGALRM, &act, NULL);
1240 * Initialize ev struct to 0 to avoid valgrind complaining
1241 * about uninitialized data in timer_create call
1243 memset(&ev, 0, sizeof(ev));
1244 ev.sigev_value.sival_int = 0;
1245 ev.sigev_notify = SIGEV_SIGNAL;
1246 ev.sigev_signo = SIGALRM;
1248 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1249 perror("timer_create");
1251 /* disable dynticks */
1252 fprintf(stderr, "Dynamic Ticks disabled\n");
1254 return -1;
1257 t->priv = (void *)(long)host_timer;
1259 return 0;
1262 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1264 timer_t host_timer = (timer_t)(long)t->priv;
1266 timer_delete(host_timer);
1269 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1271 timer_t host_timer = (timer_t)(long)t->priv;
1272 struct itimerspec timeout;
1273 int64_t nearest_delta_us = INT64_MAX;
1274 int64_t current_us;
1276 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1277 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1278 !active_timers[QEMU_CLOCK_HOST])
1279 return;
1281 nearest_delta_us = qemu_next_deadline_dyntick();
1283 /* check whether a timer is already running */
1284 if (timer_gettime(host_timer, &timeout)) {
1285 perror("gettime");
1286 fprintf(stderr, "Internal timer error: aborting\n");
1287 exit(1);
1289 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1290 if (current_us && current_us <= nearest_delta_us)
1291 return;
1293 timeout.it_interval.tv_sec = 0;
1294 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1295 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1296 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1297 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1298 perror("settime");
1299 fprintf(stderr, "Internal timer error: aborting\n");
1300 exit(1);
1304 #endif /* defined(__linux__) */
1306 static int unix_start_timer(struct qemu_alarm_timer *t)
1308 struct sigaction act;
1309 struct itimerval itv;
1310 int err;
1312 /* timer signal */
1313 sigfillset(&act.sa_mask);
1314 act.sa_flags = 0;
1315 act.sa_handler = host_alarm_handler;
1317 sigaction(SIGALRM, &act, NULL);
1319 itv.it_interval.tv_sec = 0;
1320 /* for i386 kernel 2.6 to get 1 ms */
1321 itv.it_interval.tv_usec = 999;
1322 itv.it_value.tv_sec = 0;
1323 itv.it_value.tv_usec = 10 * 1000;
1325 err = setitimer(ITIMER_REAL, &itv, NULL);
1326 if (err)
1327 return -1;
1329 return 0;
1332 static void unix_stop_timer(struct qemu_alarm_timer *t)
1334 struct itimerval itv;
1336 memset(&itv, 0, sizeof(itv));
1337 setitimer(ITIMER_REAL, &itv, NULL);
1340 #endif /* !defined(_WIN32) */
1343 #ifdef _WIN32
1345 static int win32_start_timer(struct qemu_alarm_timer *t)
1347 TIMECAPS tc;
1348 struct qemu_alarm_win32 *data = t->priv;
1349 UINT flags;
1351 memset(&tc, 0, sizeof(tc));
1352 timeGetDevCaps(&tc, sizeof(tc));
1354 if (data->period < tc.wPeriodMin)
1355 data->period = tc.wPeriodMin;
1357 timeBeginPeriod(data->period);
1359 flags = TIME_CALLBACK_FUNCTION;
1360 if (alarm_has_dynticks(t))
1361 flags |= TIME_ONESHOT;
1362 else
1363 flags |= TIME_PERIODIC;
1365 data->timerId = timeSetEvent(1, // interval (ms)
1366 data->period, // resolution
1367 host_alarm_handler, // function
1368 (DWORD)t, // parameter
1369 flags);
1371 if (!data->timerId) {
1372 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1373 GetLastError());
1374 timeEndPeriod(data->period);
1375 return -1;
1378 return 0;
1381 static void win32_stop_timer(struct qemu_alarm_timer *t)
1383 struct qemu_alarm_win32 *data = t->priv;
1385 timeKillEvent(data->timerId);
1386 timeEndPeriod(data->period);
1389 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1391 struct qemu_alarm_win32 *data = t->priv;
1393 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1394 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1395 !active_timers[QEMU_CLOCK_HOST])
1396 return;
1398 timeKillEvent(data->timerId);
1400 data->timerId = timeSetEvent(1,
1401 data->period,
1402 host_alarm_handler,
1403 (DWORD)t,
1404 TIME_ONESHOT | TIME_PERIODIC);
1406 if (!data->timerId) {
1407 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1408 GetLastError());
1410 timeEndPeriod(data->period);
1411 exit(1);
1415 #endif /* _WIN32 */
1417 static int init_timer_alarm(void)
1419 struct qemu_alarm_timer *t = NULL;
1420 int i, err = -1;
1422 for (i = 0; alarm_timers[i].name; i++) {
1423 t = &alarm_timers[i];
1425 err = t->start(t);
1426 if (!err)
1427 break;
1430 if (err) {
1431 err = -ENOENT;
1432 goto fail;
1435 alarm_timer = t;
1437 return 0;
1439 fail:
1440 return err;
1443 static void quit_timers(void)
1445 alarm_timer->stop(alarm_timer);
1446 alarm_timer = NULL;
1449 /***********************************************************/
1450 /* host time/date access */
1451 void qemu_get_timedate(struct tm *tm, int offset)
1453 time_t ti;
1454 struct tm *ret;
1456 time(&ti);
1457 ti += offset;
1458 if (rtc_date_offset == -1) {
1459 if (rtc_utc)
1460 ret = gmtime(&ti);
1461 else
1462 ret = localtime(&ti);
1463 } else {
1464 ti -= rtc_date_offset;
1465 ret = gmtime(&ti);
1468 memcpy(tm, ret, sizeof(struct tm));
1471 int qemu_timedate_diff(struct tm *tm)
1473 time_t seconds;
1475 if (rtc_date_offset == -1)
1476 if (rtc_utc)
1477 seconds = mktimegm(tm);
1478 else
1479 seconds = mktime(tm);
1480 else
1481 seconds = mktimegm(tm) + rtc_date_offset;
1483 return seconds - time(NULL);
1486 static void configure_rtc_date_offset(const char *startdate, int legacy)
1488 time_t rtc_start_date;
1489 struct tm tm;
1491 if (!strcmp(startdate, "now") && legacy) {
1492 rtc_date_offset = -1;
1493 } else {
1494 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1495 &tm.tm_year,
1496 &tm.tm_mon,
1497 &tm.tm_mday,
1498 &tm.tm_hour,
1499 &tm.tm_min,
1500 &tm.tm_sec) == 6) {
1501 /* OK */
1502 } else if (sscanf(startdate, "%d-%d-%d",
1503 &tm.tm_year,
1504 &tm.tm_mon,
1505 &tm.tm_mday) == 3) {
1506 tm.tm_hour = 0;
1507 tm.tm_min = 0;
1508 tm.tm_sec = 0;
1509 } else {
1510 goto date_fail;
1512 tm.tm_year -= 1900;
1513 tm.tm_mon--;
1514 rtc_start_date = mktimegm(&tm);
1515 if (rtc_start_date == -1) {
1516 date_fail:
1517 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1518 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1519 exit(1);
1521 rtc_date_offset = time(NULL) - rtc_start_date;
1525 static void configure_rtc(QemuOpts *opts)
1527 const char *value;
1529 value = qemu_opt_get(opts, "base");
1530 if (value) {
1531 if (!strcmp(value, "utc")) {
1532 rtc_utc = 1;
1533 } else if (!strcmp(value, "localtime")) {
1534 rtc_utc = 0;
1535 } else {
1536 configure_rtc_date_offset(value, 0);
1539 value = qemu_opt_get(opts, "clock");
1540 if (value) {
1541 if (!strcmp(value, "host")) {
1542 rtc_clock = host_clock;
1543 } else if (!strcmp(value, "vm")) {
1544 rtc_clock = vm_clock;
1545 } else {
1546 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1547 exit(1);
1550 #ifdef CONFIG_TARGET_I386
1551 value = qemu_opt_get(opts, "driftfix");
1552 if (value) {
1553 if (!strcmp(buf, "slew")) {
1554 rtc_td_hack = 1;
1555 } else if (!strcmp(buf, "none")) {
1556 rtc_td_hack = 0;
1557 } else {
1558 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1559 exit(1);
1562 #endif
1565 #ifdef _WIN32
1566 static void socket_cleanup(void)
1568 WSACleanup();
1571 static int socket_init(void)
1573 WSADATA Data;
1574 int ret, err;
1576 ret = WSAStartup(MAKEWORD(2,2), &Data);
1577 if (ret != 0) {
1578 err = WSAGetLastError();
1579 fprintf(stderr, "WSAStartup: %d\n", err);
1580 return -1;
1582 atexit(socket_cleanup);
1583 return 0;
1585 #endif
1587 /***********************************************************/
1588 /* Bluetooth support */
1589 static int nb_hcis;
1590 static int cur_hci;
1591 static struct HCIInfo *hci_table[MAX_NICS];
1593 static struct bt_vlan_s {
1594 struct bt_scatternet_s net;
1595 int id;
1596 struct bt_vlan_s *next;
1597 } *first_bt_vlan;
1599 /* find or alloc a new bluetooth "VLAN" */
1600 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1602 struct bt_vlan_s **pvlan, *vlan;
1603 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1604 if (vlan->id == id)
1605 return &vlan->net;
1607 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1608 vlan->id = id;
1609 pvlan = &first_bt_vlan;
1610 while (*pvlan != NULL)
1611 pvlan = &(*pvlan)->next;
1612 *pvlan = vlan;
1613 return &vlan->net;
1616 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1620 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1622 return -ENOTSUP;
1625 static struct HCIInfo null_hci = {
1626 .cmd_send = null_hci_send,
1627 .sco_send = null_hci_send,
1628 .acl_send = null_hci_send,
1629 .bdaddr_set = null_hci_addr_set,
1632 struct HCIInfo *qemu_next_hci(void)
1634 if (cur_hci == nb_hcis)
1635 return &null_hci;
1637 return hci_table[cur_hci++];
1640 static struct HCIInfo *hci_init(const char *str)
1642 char *endp;
1643 struct bt_scatternet_s *vlan = 0;
1645 if (!strcmp(str, "null"))
1646 /* null */
1647 return &null_hci;
1648 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1649 /* host[:hciN] */
1650 return bt_host_hci(str[4] ? str + 5 : "hci0");
1651 else if (!strncmp(str, "hci", 3)) {
1652 /* hci[,vlan=n] */
1653 if (str[3]) {
1654 if (!strncmp(str + 3, ",vlan=", 6)) {
1655 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1656 if (*endp)
1657 vlan = 0;
1659 } else
1660 vlan = qemu_find_bt_vlan(0);
1661 if (vlan)
1662 return bt_new_hci(vlan);
1665 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1667 return 0;
1670 static int bt_hci_parse(const char *str)
1672 struct HCIInfo *hci;
1673 bdaddr_t bdaddr;
1675 if (nb_hcis >= MAX_NICS) {
1676 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1677 return -1;
1680 hci = hci_init(str);
1681 if (!hci)
1682 return -1;
1684 bdaddr.b[0] = 0x52;
1685 bdaddr.b[1] = 0x54;
1686 bdaddr.b[2] = 0x00;
1687 bdaddr.b[3] = 0x12;
1688 bdaddr.b[4] = 0x34;
1689 bdaddr.b[5] = 0x56 + nb_hcis;
1690 hci->bdaddr_set(hci, bdaddr.b);
1692 hci_table[nb_hcis++] = hci;
1694 return 0;
1697 static void bt_vhci_add(int vlan_id)
1699 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1701 if (!vlan->slave)
1702 fprintf(stderr, "qemu: warning: adding a VHCI to "
1703 "an empty scatternet %i\n", vlan_id);
1705 bt_vhci_init(bt_new_hci(vlan));
1708 static struct bt_device_s *bt_device_add(const char *opt)
1710 struct bt_scatternet_s *vlan;
1711 int vlan_id = 0;
1712 char *endp = strstr(opt, ",vlan=");
1713 int len = (endp ? endp - opt : strlen(opt)) + 1;
1714 char devname[10];
1716 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1718 if (endp) {
1719 vlan_id = strtol(endp + 6, &endp, 0);
1720 if (*endp) {
1721 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1722 return 0;
1726 vlan = qemu_find_bt_vlan(vlan_id);
1728 if (!vlan->slave)
1729 fprintf(stderr, "qemu: warning: adding a slave device to "
1730 "an empty scatternet %i\n", vlan_id);
1732 if (!strcmp(devname, "keyboard"))
1733 return bt_keyboard_init(vlan);
1735 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1736 return 0;
1739 static int bt_parse(const char *opt)
1741 const char *endp, *p;
1742 int vlan;
1744 if (strstart(opt, "hci", &endp)) {
1745 if (!*endp || *endp == ',') {
1746 if (*endp)
1747 if (!strstart(endp, ",vlan=", 0))
1748 opt = endp + 1;
1750 return bt_hci_parse(opt);
1752 } else if (strstart(opt, "vhci", &endp)) {
1753 if (!*endp || *endp == ',') {
1754 if (*endp) {
1755 if (strstart(endp, ",vlan=", &p)) {
1756 vlan = strtol(p, (char **) &endp, 0);
1757 if (*endp) {
1758 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1759 return 1;
1761 } else {
1762 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1763 return 1;
1765 } else
1766 vlan = 0;
1768 bt_vhci_add(vlan);
1769 return 0;
1771 } else if (strstart(opt, "device:", &endp))
1772 return !bt_device_add(endp);
1774 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1775 return 1;
1778 /***********************************************************/
1779 /* QEMU Block devices */
1781 #define HD_ALIAS "index=%d,media=disk"
1782 #define CDROM_ALIAS "index=2,media=cdrom"
1783 #define FD_ALIAS "index=%d,if=floppy"
1784 #define PFLASH_ALIAS "if=pflash"
1785 #define MTD_ALIAS "if=mtd"
1786 #define SD_ALIAS "index=0,if=sd"
1788 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1790 va_list ap;
1791 char optstr[1024];
1792 QemuOpts *opts;
1794 va_start(ap, fmt);
1795 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1796 va_end(ap);
1798 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1799 if (!opts) {
1800 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1801 __FUNCTION__, optstr);
1802 return NULL;
1804 if (file)
1805 qemu_opt_set(opts, "file", file);
1806 return opts;
1809 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1811 DriveInfo *dinfo;
1813 /* seek interface, bus and unit */
1815 QTAILQ_FOREACH(dinfo, &drives, next) {
1816 if (dinfo->type == type &&
1817 dinfo->bus == bus &&
1818 dinfo->unit == unit)
1819 return dinfo;
1822 return NULL;
1825 DriveInfo *drive_get_by_id(const char *id)
1827 DriveInfo *dinfo;
1829 QTAILQ_FOREACH(dinfo, &drives, next) {
1830 if (strcmp(id, dinfo->id))
1831 continue;
1832 return dinfo;
1834 return NULL;
1837 int drive_get_max_bus(BlockInterfaceType type)
1839 int max_bus;
1840 DriveInfo *dinfo;
1842 max_bus = -1;
1843 QTAILQ_FOREACH(dinfo, &drives, next) {
1844 if(dinfo->type == type &&
1845 dinfo->bus > max_bus)
1846 max_bus = dinfo->bus;
1848 return max_bus;
1851 const char *drive_get_serial(BlockDriverState *bdrv)
1853 DriveInfo *dinfo;
1855 QTAILQ_FOREACH(dinfo, &drives, next) {
1856 if (dinfo->bdrv == bdrv)
1857 return dinfo->serial;
1860 return "\0";
1863 BlockInterfaceErrorAction drive_get_on_error(
1864 BlockDriverState *bdrv, int is_read)
1866 DriveInfo *dinfo;
1868 QTAILQ_FOREACH(dinfo, &drives, next) {
1869 if (dinfo->bdrv == bdrv)
1870 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1873 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1876 static void bdrv_format_print(void *opaque, const char *name)
1878 fprintf(stderr, " %s", name);
1881 void drive_uninit(DriveInfo *dinfo)
1883 qemu_opts_del(dinfo->opts);
1884 bdrv_delete(dinfo->bdrv);
1885 QTAILQ_REMOVE(&drives, dinfo, next);
1886 qemu_free(dinfo);
1889 static int parse_block_error_action(const char *buf, int is_read)
1891 if (!strcmp(buf, "ignore")) {
1892 return BLOCK_ERR_IGNORE;
1893 } else if (!is_read && !strcmp(buf, "enospc")) {
1894 return BLOCK_ERR_STOP_ENOSPC;
1895 } else if (!strcmp(buf, "stop")) {
1896 return BLOCK_ERR_STOP_ANY;
1897 } else if (!strcmp(buf, "report")) {
1898 return BLOCK_ERR_REPORT;
1899 } else {
1900 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1901 buf, is_read ? "read" : "write");
1902 return -1;
1906 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1907 int *fatal_error)
1909 const char *buf;
1910 const char *file = NULL;
1911 char devname[128];
1912 const char *serial;
1913 const char *mediastr = "";
1914 BlockInterfaceType type;
1915 enum { MEDIA_DISK, MEDIA_CDROM } media;
1916 int bus_id, unit_id;
1917 int cyls, heads, secs, translation;
1918 BlockDriver *drv = NULL;
1919 QEMUMachine *machine = opaque;
1920 int max_devs;
1921 int index;
1922 int cache;
1923 int aio = 0;
1924 int ro = 0;
1925 int bdrv_flags;
1926 int on_read_error, on_write_error;
1927 const char *devaddr;
1928 DriveInfo *dinfo;
1929 int snapshot = 0;
1931 *fatal_error = 1;
1933 translation = BIOS_ATA_TRANSLATION_AUTO;
1934 cache = 1;
1936 if (machine && machine->use_scsi) {
1937 type = IF_SCSI;
1938 max_devs = MAX_SCSI_DEVS;
1939 pstrcpy(devname, sizeof(devname), "scsi");
1940 } else {
1941 type = IF_IDE;
1942 max_devs = MAX_IDE_DEVS;
1943 pstrcpy(devname, sizeof(devname), "ide");
1945 media = MEDIA_DISK;
1947 /* extract parameters */
1948 bus_id = qemu_opt_get_number(opts, "bus", 0);
1949 unit_id = qemu_opt_get_number(opts, "unit", -1);
1950 index = qemu_opt_get_number(opts, "index", -1);
1952 cyls = qemu_opt_get_number(opts, "cyls", 0);
1953 heads = qemu_opt_get_number(opts, "heads", 0);
1954 secs = qemu_opt_get_number(opts, "secs", 0);
1956 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1957 ro = qemu_opt_get_bool(opts, "readonly", 0);
1959 file = qemu_opt_get(opts, "file");
1960 serial = qemu_opt_get(opts, "serial");
1962 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1963 pstrcpy(devname, sizeof(devname), buf);
1964 if (!strcmp(buf, "ide")) {
1965 type = IF_IDE;
1966 max_devs = MAX_IDE_DEVS;
1967 } else if (!strcmp(buf, "scsi")) {
1968 type = IF_SCSI;
1969 max_devs = MAX_SCSI_DEVS;
1970 } else if (!strcmp(buf, "floppy")) {
1971 type = IF_FLOPPY;
1972 max_devs = 0;
1973 } else if (!strcmp(buf, "pflash")) {
1974 type = IF_PFLASH;
1975 max_devs = 0;
1976 } else if (!strcmp(buf, "mtd")) {
1977 type = IF_MTD;
1978 max_devs = 0;
1979 } else if (!strcmp(buf, "sd")) {
1980 type = IF_SD;
1981 max_devs = 0;
1982 } else if (!strcmp(buf, "virtio")) {
1983 type = IF_VIRTIO;
1984 max_devs = 0;
1985 } else if (!strcmp(buf, "xen")) {
1986 type = IF_XEN;
1987 max_devs = 0;
1988 } else if (!strcmp(buf, "none")) {
1989 type = IF_NONE;
1990 max_devs = 0;
1991 } else {
1992 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1993 return NULL;
1997 if (cyls || heads || secs) {
1998 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
1999 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2000 return NULL;
2002 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2003 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2004 return NULL;
2006 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2007 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2008 return NULL;
2012 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2013 if (!cyls) {
2014 fprintf(stderr,
2015 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2016 buf);
2017 return NULL;
2019 if (!strcmp(buf, "none"))
2020 translation = BIOS_ATA_TRANSLATION_NONE;
2021 else if (!strcmp(buf, "lba"))
2022 translation = BIOS_ATA_TRANSLATION_LBA;
2023 else if (!strcmp(buf, "auto"))
2024 translation = BIOS_ATA_TRANSLATION_AUTO;
2025 else {
2026 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2027 return NULL;
2031 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2032 if (!strcmp(buf, "disk")) {
2033 media = MEDIA_DISK;
2034 } else if (!strcmp(buf, "cdrom")) {
2035 if (cyls || secs || heads) {
2036 fprintf(stderr,
2037 "qemu: '%s' invalid physical CHS format\n", buf);
2038 return NULL;
2040 media = MEDIA_CDROM;
2041 } else {
2042 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2043 return NULL;
2047 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2048 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2049 cache = 0;
2050 else if (!strcmp(buf, "writethrough"))
2051 cache = 1;
2052 else if (!strcmp(buf, "writeback"))
2053 cache = 2;
2054 else {
2055 fprintf(stderr, "qemu: invalid cache option\n");
2056 return NULL;
2060 #ifdef CONFIG_LINUX_AIO
2061 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2062 if (!strcmp(buf, "threads"))
2063 aio = 0;
2064 else if (!strcmp(buf, "native"))
2065 aio = 1;
2066 else {
2067 fprintf(stderr, "qemu: invalid aio option\n");
2068 return NULL;
2071 #endif
2073 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2074 if (strcmp(buf, "?") == 0) {
2075 fprintf(stderr, "qemu: Supported formats:");
2076 bdrv_iterate_format(bdrv_format_print, NULL);
2077 fprintf(stderr, "\n");
2078 return NULL;
2080 drv = bdrv_find_whitelisted_format(buf);
2081 if (!drv) {
2082 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2083 return NULL;
2087 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2088 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2089 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2090 fprintf(stderr, "werror is no supported by this format\n");
2091 return NULL;
2094 on_write_error = parse_block_error_action(buf, 0);
2095 if (on_write_error < 0) {
2096 return NULL;
2100 on_read_error = BLOCK_ERR_REPORT;
2101 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2102 if (type != IF_IDE && type != IF_VIRTIO) {
2103 fprintf(stderr, "rerror is no supported by this format\n");
2104 return NULL;
2107 on_read_error = parse_block_error_action(buf, 1);
2108 if (on_read_error < 0) {
2109 return NULL;
2113 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2114 if (type != IF_VIRTIO) {
2115 fprintf(stderr, "addr is not supported\n");
2116 return NULL;
2120 /* compute bus and unit according index */
2122 if (index != -1) {
2123 if (bus_id != 0 || unit_id != -1) {
2124 fprintf(stderr,
2125 "qemu: index cannot be used with bus and unit\n");
2126 return NULL;
2128 if (max_devs == 0)
2130 unit_id = index;
2131 bus_id = 0;
2132 } else {
2133 unit_id = index % max_devs;
2134 bus_id = index / max_devs;
2138 /* if user doesn't specify a unit_id,
2139 * try to find the first free
2142 if (unit_id == -1) {
2143 unit_id = 0;
2144 while (drive_get(type, bus_id, unit_id) != NULL) {
2145 unit_id++;
2146 if (max_devs && unit_id >= max_devs) {
2147 unit_id -= max_devs;
2148 bus_id++;
2153 /* check unit id */
2155 if (max_devs && unit_id >= max_devs) {
2156 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2157 unit_id, max_devs - 1);
2158 return NULL;
2162 * ignore multiple definitions
2165 if (drive_get(type, bus_id, unit_id) != NULL) {
2166 *fatal_error = 0;
2167 return NULL;
2170 /* init */
2172 dinfo = qemu_mallocz(sizeof(*dinfo));
2173 if ((buf = qemu_opts_id(opts)) != NULL) {
2174 dinfo->id = qemu_strdup(buf);
2175 } else {
2176 /* no id supplied -> create one */
2177 dinfo->id = qemu_mallocz(32);
2178 if (type == IF_IDE || type == IF_SCSI)
2179 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2180 if (max_devs)
2181 snprintf(dinfo->id, 32, "%s%i%s%i",
2182 devname, bus_id, mediastr, unit_id);
2183 else
2184 snprintf(dinfo->id, 32, "%s%s%i",
2185 devname, mediastr, unit_id);
2187 dinfo->bdrv = bdrv_new(dinfo->id);
2188 dinfo->devaddr = devaddr;
2189 dinfo->type = type;
2190 dinfo->bus = bus_id;
2191 dinfo->unit = unit_id;
2192 dinfo->on_read_error = on_read_error;
2193 dinfo->on_write_error = on_write_error;
2194 dinfo->opts = opts;
2195 if (serial)
2196 strncpy(dinfo->serial, serial, sizeof(serial));
2197 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2199 switch(type) {
2200 case IF_IDE:
2201 case IF_SCSI:
2202 case IF_XEN:
2203 case IF_NONE:
2204 switch(media) {
2205 case MEDIA_DISK:
2206 if (cyls != 0) {
2207 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2208 bdrv_set_translation_hint(dinfo->bdrv, translation);
2210 break;
2211 case MEDIA_CDROM:
2212 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2213 break;
2215 break;
2216 case IF_SD:
2217 /* FIXME: This isn't really a floppy, but it's a reasonable
2218 approximation. */
2219 case IF_FLOPPY:
2220 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2221 break;
2222 case IF_PFLASH:
2223 case IF_MTD:
2224 break;
2225 case IF_VIRTIO:
2226 /* add virtio block device */
2227 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2228 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2229 qemu_opt_set(opts, "drive", dinfo->id);
2230 if (devaddr)
2231 qemu_opt_set(opts, "addr", devaddr);
2232 break;
2233 case IF_COUNT:
2234 abort();
2236 if (!file) {
2237 *fatal_error = 0;
2238 return NULL;
2240 bdrv_flags = 0;
2241 if (snapshot) {
2242 bdrv_flags |= BDRV_O_SNAPSHOT;
2243 cache = 2; /* always use write-back with snapshot */
2245 if (cache == 0) /* no caching */
2246 bdrv_flags |= BDRV_O_NOCACHE;
2247 else if (cache == 2) /* write-back */
2248 bdrv_flags |= BDRV_O_CACHE_WB;
2250 if (aio == 1) {
2251 bdrv_flags |= BDRV_O_NATIVE_AIO;
2252 } else {
2253 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2256 if (ro == 1) {
2257 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2258 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2259 return NULL;
2263 * cdrom is read-only. Set it now, after above interface checking
2264 * since readonly attribute not explicitly required, so no error.
2266 if (media == MEDIA_CDROM) {
2267 ro = 1;
2269 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2271 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2272 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2273 file, strerror(errno));
2274 return NULL;
2277 if (bdrv_key_required(dinfo->bdrv))
2278 autostart = 0;
2279 *fatal_error = 0;
2280 return dinfo;
2283 static int drive_init_func(QemuOpts *opts, void *opaque)
2285 QEMUMachine *machine = opaque;
2286 int fatal_error = 0;
2288 if (drive_init(opts, machine, &fatal_error) == NULL) {
2289 if (fatal_error)
2290 return 1;
2292 return 0;
2295 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2297 if (NULL == qemu_opt_get(opts, "snapshot")) {
2298 qemu_opt_set(opts, "snapshot", "on");
2300 return 0;
2303 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2305 boot_set_handler = func;
2306 boot_set_opaque = opaque;
2309 int qemu_boot_set(const char *boot_devices)
2311 if (!boot_set_handler) {
2312 return -EINVAL;
2314 return boot_set_handler(boot_set_opaque, boot_devices);
2317 static int parse_bootdevices(char *devices)
2319 /* We just do some generic consistency checks */
2320 const char *p;
2321 int bitmap = 0;
2323 for (p = devices; *p != '\0'; p++) {
2324 /* Allowed boot devices are:
2325 * a-b: floppy disk drives
2326 * c-f: IDE disk drives
2327 * g-m: machine implementation dependant drives
2328 * n-p: network devices
2329 * It's up to each machine implementation to check if the given boot
2330 * devices match the actual hardware implementation and firmware
2331 * features.
2333 if (*p < 'a' || *p > 'p') {
2334 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2335 exit(1);
2337 if (bitmap & (1 << (*p - 'a'))) {
2338 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2339 exit(1);
2341 bitmap |= 1 << (*p - 'a');
2343 return bitmap;
2346 static void restore_boot_devices(void *opaque)
2348 char *standard_boot_devices = opaque;
2350 qemu_boot_set(standard_boot_devices);
2352 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2353 qemu_free(standard_boot_devices);
2356 static void numa_add(const char *optarg)
2358 char option[128];
2359 char *endptr;
2360 unsigned long long value, endvalue;
2361 int nodenr;
2363 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2364 if (!strcmp(option, "node")) {
2365 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2366 nodenr = nb_numa_nodes;
2367 } else {
2368 nodenr = strtoull(option, NULL, 10);
2371 if (get_param_value(option, 128, "mem", optarg) == 0) {
2372 node_mem[nodenr] = 0;
2373 } else {
2374 value = strtoull(option, &endptr, 0);
2375 switch (*endptr) {
2376 case 0: case 'M': case 'm':
2377 value <<= 20;
2378 break;
2379 case 'G': case 'g':
2380 value <<= 30;
2381 break;
2383 node_mem[nodenr] = value;
2385 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2386 node_cpumask[nodenr] = 0;
2387 } else {
2388 value = strtoull(option, &endptr, 10);
2389 if (value >= 64) {
2390 value = 63;
2391 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2392 } else {
2393 if (*endptr == '-') {
2394 endvalue = strtoull(endptr+1, &endptr, 10);
2395 if (endvalue >= 63) {
2396 endvalue = 62;
2397 fprintf(stderr,
2398 "only 63 CPUs in NUMA mode supported.\n");
2400 value = (2ULL << endvalue) - (1ULL << value);
2401 } else {
2402 value = 1ULL << value;
2405 node_cpumask[nodenr] = value;
2407 nb_numa_nodes++;
2409 return;
2412 static void smp_parse(const char *optarg)
2414 int smp, sockets = 0, threads = 0, cores = 0;
2415 char *endptr;
2416 char option[128];
2418 smp = strtoul(optarg, &endptr, 10);
2419 if (endptr != optarg) {
2420 if (*endptr == ',') {
2421 endptr++;
2424 if (get_param_value(option, 128, "sockets", endptr) != 0)
2425 sockets = strtoull(option, NULL, 10);
2426 if (get_param_value(option, 128, "cores", endptr) != 0)
2427 cores = strtoull(option, NULL, 10);
2428 if (get_param_value(option, 128, "threads", endptr) != 0)
2429 threads = strtoull(option, NULL, 10);
2430 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2431 max_cpus = strtoull(option, NULL, 10);
2433 /* compute missing values, prefer sockets over cores over threads */
2434 if (smp == 0 || sockets == 0) {
2435 sockets = sockets > 0 ? sockets : 1;
2436 cores = cores > 0 ? cores : 1;
2437 threads = threads > 0 ? threads : 1;
2438 if (smp == 0) {
2439 smp = cores * threads * sockets;
2441 } else {
2442 if (cores == 0) {
2443 threads = threads > 0 ? threads : 1;
2444 cores = smp / (sockets * threads);
2445 } else {
2446 if (sockets) {
2447 threads = smp / (cores * sockets);
2451 smp_cpus = smp;
2452 smp_cores = cores > 0 ? cores : 1;
2453 smp_threads = threads > 0 ? threads : 1;
2454 if (max_cpus == 0)
2455 max_cpus = smp_cpus;
2458 /***********************************************************/
2459 /* USB devices */
2461 static int usb_device_add(const char *devname, int is_hotplug)
2463 const char *p;
2464 USBDevice *dev = NULL;
2466 if (!usb_enabled)
2467 return -1;
2469 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2470 dev = usbdevice_create(devname);
2471 if (dev)
2472 goto done;
2474 /* the other ones */
2475 if (strstart(devname, "host:", &p)) {
2476 dev = usb_host_device_open(p);
2477 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2478 dev = usb_bt_init(devname[2] ? hci_init(p) :
2479 bt_new_hci(qemu_find_bt_vlan(0)));
2480 } else {
2481 return -1;
2483 if (!dev)
2484 return -1;
2486 done:
2487 return 0;
2490 static int usb_device_del(const char *devname)
2492 int bus_num, addr;
2493 const char *p;
2495 if (strstart(devname, "host:", &p))
2496 return usb_host_device_close(p);
2498 if (!usb_enabled)
2499 return -1;
2501 p = strchr(devname, '.');
2502 if (!p)
2503 return -1;
2504 bus_num = strtoul(devname, NULL, 0);
2505 addr = strtoul(p + 1, NULL, 0);
2507 return usb_device_delete_addr(bus_num, addr);
2510 static int usb_parse(const char *cmdline)
2512 int r;
2513 r = usb_device_add(cmdline, 0);
2514 if (r < 0) {
2515 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2517 return r;
2520 void do_usb_add(Monitor *mon, const QDict *qdict)
2522 const char *devname = qdict_get_str(qdict, "devname");
2523 if (usb_device_add(devname, 1) < 0) {
2524 qemu_error("could not add USB device '%s'\n", devname);
2528 void do_usb_del(Monitor *mon, const QDict *qdict)
2530 const char *devname = qdict_get_str(qdict, "devname");
2531 if (usb_device_del(devname) < 0) {
2532 qemu_error("could not delete USB device '%s'\n", devname);
2536 /***********************************************************/
2537 /* PCMCIA/Cardbus */
2539 static struct pcmcia_socket_entry_s {
2540 PCMCIASocket *socket;
2541 struct pcmcia_socket_entry_s *next;
2542 } *pcmcia_sockets = 0;
2544 void pcmcia_socket_register(PCMCIASocket *socket)
2546 struct pcmcia_socket_entry_s *entry;
2548 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2549 entry->socket = socket;
2550 entry->next = pcmcia_sockets;
2551 pcmcia_sockets = entry;
2554 void pcmcia_socket_unregister(PCMCIASocket *socket)
2556 struct pcmcia_socket_entry_s *entry, **ptr;
2558 ptr = &pcmcia_sockets;
2559 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2560 if (entry->socket == socket) {
2561 *ptr = entry->next;
2562 qemu_free(entry);
2566 void pcmcia_info(Monitor *mon)
2568 struct pcmcia_socket_entry_s *iter;
2570 if (!pcmcia_sockets)
2571 monitor_printf(mon, "No PCMCIA sockets\n");
2573 for (iter = pcmcia_sockets; iter; iter = iter->next)
2574 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2575 iter->socket->attached ? iter->socket->card_string :
2576 "Empty");
2579 /***********************************************************/
2580 /* register display */
2582 struct DisplayAllocator default_allocator = {
2583 defaultallocator_create_displaysurface,
2584 defaultallocator_resize_displaysurface,
2585 defaultallocator_free_displaysurface
2588 void register_displaystate(DisplayState *ds)
2590 DisplayState **s;
2591 s = &display_state;
2592 while (*s != NULL)
2593 s = &(*s)->next;
2594 ds->next = NULL;
2595 *s = ds;
2598 DisplayState *get_displaystate(void)
2600 return display_state;
2603 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2605 if(ds->allocator == &default_allocator) ds->allocator = da;
2606 return ds->allocator;
2609 /* dumb display */
2611 static void dumb_display_init(void)
2613 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2614 ds->allocator = &default_allocator;
2615 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2616 register_displaystate(ds);
2619 /***********************************************************/
2620 /* I/O handling */
2622 typedef struct IOHandlerRecord {
2623 int fd;
2624 IOCanRWHandler *fd_read_poll;
2625 IOHandler *fd_read;
2626 IOHandler *fd_write;
2627 int deleted;
2628 void *opaque;
2629 /* temporary data */
2630 struct pollfd *ufd;
2631 struct IOHandlerRecord *next;
2632 } IOHandlerRecord;
2634 static IOHandlerRecord *first_io_handler;
2636 /* XXX: fd_read_poll should be suppressed, but an API change is
2637 necessary in the character devices to suppress fd_can_read(). */
2638 int qemu_set_fd_handler2(int fd,
2639 IOCanRWHandler *fd_read_poll,
2640 IOHandler *fd_read,
2641 IOHandler *fd_write,
2642 void *opaque)
2644 IOHandlerRecord **pioh, *ioh;
2646 if (!fd_read && !fd_write) {
2647 pioh = &first_io_handler;
2648 for(;;) {
2649 ioh = *pioh;
2650 if (ioh == NULL)
2651 break;
2652 if (ioh->fd == fd) {
2653 ioh->deleted = 1;
2654 break;
2656 pioh = &ioh->next;
2658 } else {
2659 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2660 if (ioh->fd == fd)
2661 goto found;
2663 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2664 ioh->next = first_io_handler;
2665 first_io_handler = ioh;
2666 found:
2667 ioh->fd = fd;
2668 ioh->fd_read_poll = fd_read_poll;
2669 ioh->fd_read = fd_read;
2670 ioh->fd_write = fd_write;
2671 ioh->opaque = opaque;
2672 ioh->deleted = 0;
2674 return 0;
2677 int qemu_set_fd_handler(int fd,
2678 IOHandler *fd_read,
2679 IOHandler *fd_write,
2680 void *opaque)
2682 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2685 #ifdef _WIN32
2686 /***********************************************************/
2687 /* Polling handling */
2689 typedef struct PollingEntry {
2690 PollingFunc *func;
2691 void *opaque;
2692 struct PollingEntry *next;
2693 } PollingEntry;
2695 static PollingEntry *first_polling_entry;
2697 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2699 PollingEntry **ppe, *pe;
2700 pe = qemu_mallocz(sizeof(PollingEntry));
2701 pe->func = func;
2702 pe->opaque = opaque;
2703 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2704 *ppe = pe;
2705 return 0;
2708 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2710 PollingEntry **ppe, *pe;
2711 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2712 pe = *ppe;
2713 if (pe->func == func && pe->opaque == opaque) {
2714 *ppe = pe->next;
2715 qemu_free(pe);
2716 break;
2721 /***********************************************************/
2722 /* Wait objects support */
2723 typedef struct WaitObjects {
2724 int num;
2725 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2726 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2727 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2728 } WaitObjects;
2730 static WaitObjects wait_objects = {0};
2732 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2734 WaitObjects *w = &wait_objects;
2736 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2737 return -1;
2738 w->events[w->num] = handle;
2739 w->func[w->num] = func;
2740 w->opaque[w->num] = opaque;
2741 w->num++;
2742 return 0;
2745 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2747 int i, found;
2748 WaitObjects *w = &wait_objects;
2750 found = 0;
2751 for (i = 0; i < w->num; i++) {
2752 if (w->events[i] == handle)
2753 found = 1;
2754 if (found) {
2755 w->events[i] = w->events[i + 1];
2756 w->func[i] = w->func[i + 1];
2757 w->opaque[i] = w->opaque[i + 1];
2760 if (found)
2761 w->num--;
2763 #endif
2765 /***********************************************************/
2766 /* ram save/restore */
2768 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2769 #define RAM_SAVE_FLAG_COMPRESS 0x02
2770 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2771 #define RAM_SAVE_FLAG_PAGE 0x08
2772 #define RAM_SAVE_FLAG_EOS 0x10
2774 static int is_dup_page(uint8_t *page, uint8_t ch)
2776 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2777 uint32_t *array = (uint32_t *)page;
2778 int i;
2780 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2781 if (array[i] != val)
2782 return 0;
2785 return 1;
2788 static int ram_save_block(QEMUFile *f)
2790 static ram_addr_t current_addr = 0;
2791 ram_addr_t saved_addr = current_addr;
2792 ram_addr_t addr = 0;
2793 int found = 0;
2795 while (addr < last_ram_offset) {
2796 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2797 uint8_t *p;
2799 cpu_physical_memory_reset_dirty(current_addr,
2800 current_addr + TARGET_PAGE_SIZE,
2801 MIGRATION_DIRTY_FLAG);
2803 p = qemu_get_ram_ptr(current_addr);
2805 if (is_dup_page(p, *p)) {
2806 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2807 qemu_put_byte(f, *p);
2808 } else {
2809 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2810 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2813 found = 1;
2814 break;
2816 addr += TARGET_PAGE_SIZE;
2817 current_addr = (saved_addr + addr) % last_ram_offset;
2820 return found;
2823 static uint64_t bytes_transferred;
2825 static ram_addr_t ram_save_remaining(void)
2827 ram_addr_t addr;
2828 ram_addr_t count = 0;
2830 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2831 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2832 count++;
2835 return count;
2838 uint64_t ram_bytes_remaining(void)
2840 return ram_save_remaining() * TARGET_PAGE_SIZE;
2843 uint64_t ram_bytes_transferred(void)
2845 return bytes_transferred;
2848 uint64_t ram_bytes_total(void)
2850 return last_ram_offset;
2853 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2855 ram_addr_t addr;
2856 uint64_t bytes_transferred_last;
2857 double bwidth = 0;
2858 uint64_t expected_time = 0;
2860 if (stage < 0) {
2861 cpu_physical_memory_set_dirty_tracking(0);
2862 return 0;
2865 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2866 qemu_file_set_error(f);
2867 return 0;
2870 if (stage == 1) {
2871 bytes_transferred = 0;
2873 /* Make sure all dirty bits are set */
2874 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2875 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2876 cpu_physical_memory_set_dirty(addr);
2879 /* Enable dirty memory tracking */
2880 cpu_physical_memory_set_dirty_tracking(1);
2882 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2885 bytes_transferred_last = bytes_transferred;
2886 bwidth = qemu_get_clock_ns(rt_clock);
2888 while (!qemu_file_rate_limit(f)) {
2889 int ret;
2891 ret = ram_save_block(f);
2892 bytes_transferred += ret * TARGET_PAGE_SIZE;
2893 if (ret == 0) /* no more blocks */
2894 break;
2897 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
2898 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2900 /* if we haven't transferred anything this round, force expected_time to a
2901 * a very high value, but without crashing */
2902 if (bwidth == 0)
2903 bwidth = 0.000001;
2905 /* try transferring iterative blocks of memory */
2906 if (stage == 3) {
2907 /* flush all remaining blocks regardless of rate limiting */
2908 while (ram_save_block(f) != 0) {
2909 bytes_transferred += TARGET_PAGE_SIZE;
2911 cpu_physical_memory_set_dirty_tracking(0);
2914 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2916 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2918 return (stage == 2) && (expected_time <= migrate_max_downtime());
2921 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2923 ram_addr_t addr;
2924 int flags;
2926 if (version_id != 3)
2927 return -EINVAL;
2929 do {
2930 addr = qemu_get_be64(f);
2932 flags = addr & ~TARGET_PAGE_MASK;
2933 addr &= TARGET_PAGE_MASK;
2935 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2936 if (addr != last_ram_offset)
2937 return -EINVAL;
2940 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2941 uint8_t ch = qemu_get_byte(f);
2942 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2943 #ifndef _WIN32
2944 if (ch == 0 &&
2945 (!kvm_enabled() || kvm_has_sync_mmu())) {
2946 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2948 #endif
2949 } else if (flags & RAM_SAVE_FLAG_PAGE) {
2950 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2952 if (qemu_file_has_error(f)) {
2953 return -EIO;
2955 } while (!(flags & RAM_SAVE_FLAG_EOS));
2957 return 0;
2960 void qemu_service_io(void)
2962 qemu_notify_event();
2965 /***********************************************************/
2966 /* machine registration */
2968 static QEMUMachine *first_machine = NULL;
2969 QEMUMachine *current_machine = NULL;
2971 int qemu_register_machine(QEMUMachine *m)
2973 QEMUMachine **pm;
2974 pm = &first_machine;
2975 while (*pm != NULL)
2976 pm = &(*pm)->next;
2977 m->next = NULL;
2978 *pm = m;
2979 return 0;
2982 static QEMUMachine *find_machine(const char *name)
2984 QEMUMachine *m;
2986 for(m = first_machine; m != NULL; m = m->next) {
2987 if (!strcmp(m->name, name))
2988 return m;
2989 if (m->alias && !strcmp(m->alias, name))
2990 return m;
2992 return NULL;
2995 static QEMUMachine *find_default_machine(void)
2997 QEMUMachine *m;
2999 for(m = first_machine; m != NULL; m = m->next) {
3000 if (m->is_default) {
3001 return m;
3004 return NULL;
3007 /***********************************************************/
3008 /* main execution loop */
3010 static void gui_update(void *opaque)
3012 uint64_t interval = GUI_REFRESH_INTERVAL;
3013 DisplayState *ds = opaque;
3014 DisplayChangeListener *dcl = ds->listeners;
3016 qemu_flush_coalesced_mmio_buffer();
3017 dpy_refresh(ds);
3019 while (dcl != NULL) {
3020 if (dcl->gui_timer_interval &&
3021 dcl->gui_timer_interval < interval)
3022 interval = dcl->gui_timer_interval;
3023 dcl = dcl->next;
3025 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3028 static void nographic_update(void *opaque)
3030 uint64_t interval = GUI_REFRESH_INTERVAL;
3032 qemu_flush_coalesced_mmio_buffer();
3033 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3036 struct vm_change_state_entry {
3037 VMChangeStateHandler *cb;
3038 void *opaque;
3039 QLIST_ENTRY (vm_change_state_entry) entries;
3042 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3044 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3045 void *opaque)
3047 VMChangeStateEntry *e;
3049 e = qemu_mallocz(sizeof (*e));
3051 e->cb = cb;
3052 e->opaque = opaque;
3053 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3054 return e;
3057 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3059 QLIST_REMOVE (e, entries);
3060 qemu_free (e);
3063 static void vm_state_notify(int running, int reason)
3065 VMChangeStateEntry *e;
3067 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3068 e->cb(e->opaque, running, reason);
3072 static void resume_all_vcpus(void);
3073 static void pause_all_vcpus(void);
3075 void vm_start(void)
3077 if (!vm_running) {
3078 cpu_enable_ticks();
3079 vm_running = 1;
3080 vm_state_notify(1, 0);
3081 qemu_rearm_alarm_timer(alarm_timer);
3082 resume_all_vcpus();
3086 /* reset/shutdown handler */
3088 typedef struct QEMUResetEntry {
3089 QTAILQ_ENTRY(QEMUResetEntry) entry;
3090 QEMUResetHandler *func;
3091 void *opaque;
3092 } QEMUResetEntry;
3094 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3095 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3096 static int reset_requested;
3097 static int shutdown_requested;
3098 static int powerdown_requested;
3099 static int debug_requested;
3100 static int vmstop_requested;
3102 int qemu_shutdown_requested(void)
3104 int r = shutdown_requested;
3105 shutdown_requested = 0;
3106 return r;
3109 int qemu_reset_requested(void)
3111 int r = reset_requested;
3112 reset_requested = 0;
3113 return r;
3116 int qemu_powerdown_requested(void)
3118 int r = powerdown_requested;
3119 powerdown_requested = 0;
3120 return r;
3123 static int qemu_debug_requested(void)
3125 int r = debug_requested;
3126 debug_requested = 0;
3127 return r;
3130 static int qemu_vmstop_requested(void)
3132 int r = vmstop_requested;
3133 vmstop_requested = 0;
3134 return r;
3137 static void do_vm_stop(int reason)
3139 if (vm_running) {
3140 cpu_disable_ticks();
3141 vm_running = 0;
3142 pause_all_vcpus();
3143 vm_state_notify(0, reason);
3147 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3149 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3151 re->func = func;
3152 re->opaque = opaque;
3153 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3156 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3158 QEMUResetEntry *re;
3160 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3161 if (re->func == func && re->opaque == opaque) {
3162 QTAILQ_REMOVE(&reset_handlers, re, entry);
3163 qemu_free(re);
3164 return;
3169 void qemu_system_reset(void)
3171 QEMUResetEntry *re, *nre;
3173 /* reset all devices */
3174 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3175 re->func(re->opaque);
3179 void qemu_system_reset_request(void)
3181 if (no_reboot) {
3182 shutdown_requested = 1;
3183 } else {
3184 reset_requested = 1;
3186 qemu_notify_event();
3189 void qemu_system_shutdown_request(void)
3191 shutdown_requested = 1;
3192 qemu_notify_event();
3195 void qemu_system_powerdown_request(void)
3197 powerdown_requested = 1;
3198 qemu_notify_event();
3201 #ifdef CONFIG_IOTHREAD
3202 static void qemu_system_vmstop_request(int reason)
3204 vmstop_requested = reason;
3205 qemu_notify_event();
3207 #endif
3209 #ifndef _WIN32
3210 static int io_thread_fd = -1;
3212 static void qemu_event_increment(void)
3214 static const char byte = 0;
3215 ssize_t ret;
3217 if (io_thread_fd == -1)
3218 return;
3220 ret = write(io_thread_fd, &byte, sizeof(byte));
3221 if (ret < 0 && (errno != EINTR && errno != EAGAIN)) {
3222 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3223 strerror(errno));
3224 exit (1);
3228 static void qemu_event_read(void *opaque)
3230 int fd = (unsigned long)opaque;
3231 ssize_t len;
3233 /* Drain the notify pipe */
3234 do {
3235 char buffer[512];
3236 len = read(fd, buffer, sizeof(buffer));
3237 } while ((len == -1 && errno == EINTR) || len > 0);
3240 static int qemu_event_init(void)
3242 int err;
3243 int fds[2];
3245 err = qemu_pipe(fds);
3246 if (err == -1)
3247 return -errno;
3249 err = fcntl_setfl(fds[0], O_NONBLOCK);
3250 if (err < 0)
3251 goto fail;
3253 err = fcntl_setfl(fds[1], O_NONBLOCK);
3254 if (err < 0)
3255 goto fail;
3257 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3258 (void *)(unsigned long)fds[0]);
3260 io_thread_fd = fds[1];
3261 return 0;
3263 fail:
3264 close(fds[0]);
3265 close(fds[1]);
3266 return err;
3268 #else
3269 HANDLE qemu_event_handle;
3271 static void dummy_event_handler(void *opaque)
3275 static int qemu_event_init(void)
3277 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3278 if (!qemu_event_handle) {
3279 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3280 return -1;
3282 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3283 return 0;
3286 static void qemu_event_increment(void)
3288 if (!SetEvent(qemu_event_handle)) {
3289 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3290 GetLastError());
3291 exit (1);
3294 #endif
3296 static int cpu_can_run(CPUState *env)
3298 if (env->stop)
3299 return 0;
3300 if (env->stopped)
3301 return 0;
3302 if (!vm_running)
3303 return 0;
3304 return 1;
3307 #ifndef CONFIG_IOTHREAD
3308 static int qemu_init_main_loop(void)
3310 return qemu_event_init();
3313 void qemu_init_vcpu(void *_env)
3315 CPUState *env = _env;
3317 env->nr_cores = smp_cores;
3318 env->nr_threads = smp_threads;
3319 if (kvm_enabled())
3320 kvm_init_vcpu(env);
3321 return;
3324 int qemu_cpu_self(void *env)
3326 return 1;
3329 static void resume_all_vcpus(void)
3333 static void pause_all_vcpus(void)
3337 void qemu_cpu_kick(void *env)
3339 return;
3342 void qemu_notify_event(void)
3344 CPUState *env = cpu_single_env;
3346 if (env) {
3347 cpu_exit(env);
3351 void qemu_mutex_lock_iothread(void) {}
3352 void qemu_mutex_unlock_iothread(void) {}
3354 void vm_stop(int reason)
3356 do_vm_stop(reason);
3359 #else /* CONFIG_IOTHREAD */
3361 #include "qemu-thread.h"
3363 QemuMutex qemu_global_mutex;
3364 static QemuMutex qemu_fair_mutex;
3366 static QemuThread io_thread;
3368 static QemuThread *tcg_cpu_thread;
3369 static QemuCond *tcg_halt_cond;
3371 static int qemu_system_ready;
3372 /* cpu creation */
3373 static QemuCond qemu_cpu_cond;
3374 /* system init */
3375 static QemuCond qemu_system_cond;
3376 static QemuCond qemu_pause_cond;
3378 static void block_io_signals(void);
3379 static void unblock_io_signals(void);
3380 static int tcg_has_work(void);
3382 static int qemu_init_main_loop(void)
3384 int ret;
3386 ret = qemu_event_init();
3387 if (ret)
3388 return ret;
3390 qemu_cond_init(&qemu_pause_cond);
3391 qemu_mutex_init(&qemu_fair_mutex);
3392 qemu_mutex_init(&qemu_global_mutex);
3393 qemu_mutex_lock(&qemu_global_mutex);
3395 unblock_io_signals();
3396 qemu_thread_self(&io_thread);
3398 return 0;
3401 static void qemu_wait_io_event(CPUState *env)
3403 while (!tcg_has_work())
3404 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3406 qemu_mutex_unlock(&qemu_global_mutex);
3409 * Users of qemu_global_mutex can be starved, having no chance
3410 * to acquire it since this path will get to it first.
3411 * So use another lock to provide fairness.
3413 qemu_mutex_lock(&qemu_fair_mutex);
3414 qemu_mutex_unlock(&qemu_fair_mutex);
3416 qemu_mutex_lock(&qemu_global_mutex);
3417 if (env->stop) {
3418 env->stop = 0;
3419 env->stopped = 1;
3420 qemu_cond_signal(&qemu_pause_cond);
3424 static int qemu_cpu_exec(CPUState *env);
3426 static void *kvm_cpu_thread_fn(void *arg)
3428 CPUState *env = arg;
3430 block_io_signals();
3431 qemu_thread_self(env->thread);
3432 if (kvm_enabled())
3433 kvm_init_vcpu(env);
3435 /* signal CPU creation */
3436 qemu_mutex_lock(&qemu_global_mutex);
3437 env->created = 1;
3438 qemu_cond_signal(&qemu_cpu_cond);
3440 /* and wait for machine initialization */
3441 while (!qemu_system_ready)
3442 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3444 while (1) {
3445 if (cpu_can_run(env))
3446 qemu_cpu_exec(env);
3447 qemu_wait_io_event(env);
3450 return NULL;
3453 static void tcg_cpu_exec(void);
3455 static void *tcg_cpu_thread_fn(void *arg)
3457 CPUState *env = arg;
3459 block_io_signals();
3460 qemu_thread_self(env->thread);
3462 /* signal CPU creation */
3463 qemu_mutex_lock(&qemu_global_mutex);
3464 for (env = first_cpu; env != NULL; env = env->next_cpu)
3465 env->created = 1;
3466 qemu_cond_signal(&qemu_cpu_cond);
3468 /* and wait for machine initialization */
3469 while (!qemu_system_ready)
3470 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3472 while (1) {
3473 tcg_cpu_exec();
3474 qemu_wait_io_event(cur_cpu);
3477 return NULL;
3480 void qemu_cpu_kick(void *_env)
3482 CPUState *env = _env;
3483 qemu_cond_broadcast(env->halt_cond);
3484 if (kvm_enabled())
3485 qemu_thread_signal(env->thread, SIGUSR1);
3488 int qemu_cpu_self(void *_env)
3490 CPUState *env = _env;
3491 QemuThread this;
3493 qemu_thread_self(&this);
3495 return qemu_thread_equal(&this, env->thread);
3498 static void cpu_signal(int sig)
3500 if (cpu_single_env)
3501 cpu_exit(cpu_single_env);
3504 static void block_io_signals(void)
3506 sigset_t set;
3507 struct sigaction sigact;
3509 sigemptyset(&set);
3510 sigaddset(&set, SIGUSR2);
3511 sigaddset(&set, SIGIO);
3512 sigaddset(&set, SIGALRM);
3513 pthread_sigmask(SIG_BLOCK, &set, NULL);
3515 sigemptyset(&set);
3516 sigaddset(&set, SIGUSR1);
3517 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3519 memset(&sigact, 0, sizeof(sigact));
3520 sigact.sa_handler = cpu_signal;
3521 sigaction(SIGUSR1, &sigact, NULL);
3524 static void unblock_io_signals(void)
3526 sigset_t set;
3528 sigemptyset(&set);
3529 sigaddset(&set, SIGUSR2);
3530 sigaddset(&set, SIGIO);
3531 sigaddset(&set, SIGALRM);
3532 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3534 sigemptyset(&set);
3535 sigaddset(&set, SIGUSR1);
3536 pthread_sigmask(SIG_BLOCK, &set, NULL);
3539 static void qemu_signal_lock(unsigned int msecs)
3541 qemu_mutex_lock(&qemu_fair_mutex);
3543 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3544 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3545 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3546 break;
3548 qemu_mutex_unlock(&qemu_fair_mutex);
3551 void qemu_mutex_lock_iothread(void)
3553 if (kvm_enabled()) {
3554 qemu_mutex_lock(&qemu_fair_mutex);
3555 qemu_mutex_lock(&qemu_global_mutex);
3556 qemu_mutex_unlock(&qemu_fair_mutex);
3557 } else
3558 qemu_signal_lock(100);
3561 void qemu_mutex_unlock_iothread(void)
3563 qemu_mutex_unlock(&qemu_global_mutex);
3566 static int all_vcpus_paused(void)
3568 CPUState *penv = first_cpu;
3570 while (penv) {
3571 if (!penv->stopped)
3572 return 0;
3573 penv = (CPUState *)penv->next_cpu;
3576 return 1;
3579 static void pause_all_vcpus(void)
3581 CPUState *penv = first_cpu;
3583 while (penv) {
3584 penv->stop = 1;
3585 qemu_thread_signal(penv->thread, SIGUSR1);
3586 qemu_cpu_kick(penv);
3587 penv = (CPUState *)penv->next_cpu;
3590 while (!all_vcpus_paused()) {
3591 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3592 penv = first_cpu;
3593 while (penv) {
3594 qemu_thread_signal(penv->thread, SIGUSR1);
3595 penv = (CPUState *)penv->next_cpu;
3600 static void resume_all_vcpus(void)
3602 CPUState *penv = first_cpu;
3604 while (penv) {
3605 penv->stop = 0;
3606 penv->stopped = 0;
3607 qemu_thread_signal(penv->thread, SIGUSR1);
3608 qemu_cpu_kick(penv);
3609 penv = (CPUState *)penv->next_cpu;
3613 static void tcg_init_vcpu(void *_env)
3615 CPUState *env = _env;
3616 /* share a single thread for all cpus with TCG */
3617 if (!tcg_cpu_thread) {
3618 env->thread = qemu_mallocz(sizeof(QemuThread));
3619 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3620 qemu_cond_init(env->halt_cond);
3621 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3622 while (env->created == 0)
3623 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3624 tcg_cpu_thread = env->thread;
3625 tcg_halt_cond = env->halt_cond;
3626 } else {
3627 env->thread = tcg_cpu_thread;
3628 env->halt_cond = tcg_halt_cond;
3632 static void kvm_start_vcpu(CPUState *env)
3634 env->thread = qemu_mallocz(sizeof(QemuThread));
3635 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3636 qemu_cond_init(env->halt_cond);
3637 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3638 while (env->created == 0)
3639 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3642 void qemu_init_vcpu(void *_env)
3644 CPUState *env = _env;
3646 env->nr_cores = smp_cores;
3647 env->nr_threads = smp_threads;
3648 if (kvm_enabled())
3649 kvm_start_vcpu(env);
3650 else
3651 tcg_init_vcpu(env);
3654 void qemu_notify_event(void)
3656 qemu_event_increment();
3659 void vm_stop(int reason)
3661 QemuThread me;
3662 qemu_thread_self(&me);
3664 if (!qemu_thread_equal(&me, &io_thread)) {
3665 qemu_system_vmstop_request(reason);
3667 * FIXME: should not return to device code in case
3668 * vm_stop() has been requested.
3670 if (cpu_single_env) {
3671 cpu_exit(cpu_single_env);
3672 cpu_single_env->stop = 1;
3674 return;
3676 do_vm_stop(reason);
3679 #endif
3682 #ifdef _WIN32
3683 static void host_main_loop_wait(int *timeout)
3685 int ret, ret2, i;
3686 PollingEntry *pe;
3689 /* XXX: need to suppress polling by better using win32 events */
3690 ret = 0;
3691 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3692 ret |= pe->func(pe->opaque);
3694 if (ret == 0) {
3695 int err;
3696 WaitObjects *w = &wait_objects;
3698 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3699 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3700 if (w->func[ret - WAIT_OBJECT_0])
3701 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3703 /* Check for additional signaled events */
3704 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3706 /* Check if event is signaled */
3707 ret2 = WaitForSingleObject(w->events[i], 0);
3708 if(ret2 == WAIT_OBJECT_0) {
3709 if (w->func[i])
3710 w->func[i](w->opaque[i]);
3711 } else if (ret2 == WAIT_TIMEOUT) {
3712 } else {
3713 err = GetLastError();
3714 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3717 } else if (ret == WAIT_TIMEOUT) {
3718 } else {
3719 err = GetLastError();
3720 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3724 *timeout = 0;
3726 #else
3727 static void host_main_loop_wait(int *timeout)
3730 #endif
3732 void main_loop_wait(int timeout)
3734 IOHandlerRecord *ioh;
3735 fd_set rfds, wfds, xfds;
3736 int ret, nfds;
3737 struct timeval tv;
3739 qemu_bh_update_timeout(&timeout);
3741 host_main_loop_wait(&timeout);
3743 /* poll any events */
3744 /* XXX: separate device handlers from system ones */
3745 nfds = -1;
3746 FD_ZERO(&rfds);
3747 FD_ZERO(&wfds);
3748 FD_ZERO(&xfds);
3749 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3750 if (ioh->deleted)
3751 continue;
3752 if (ioh->fd_read &&
3753 (!ioh->fd_read_poll ||
3754 ioh->fd_read_poll(ioh->opaque) != 0)) {
3755 FD_SET(ioh->fd, &rfds);
3756 if (ioh->fd > nfds)
3757 nfds = ioh->fd;
3759 if (ioh->fd_write) {
3760 FD_SET(ioh->fd, &wfds);
3761 if (ioh->fd > nfds)
3762 nfds = ioh->fd;
3766 tv.tv_sec = timeout / 1000;
3767 tv.tv_usec = (timeout % 1000) * 1000;
3769 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3771 qemu_mutex_unlock_iothread();
3772 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3773 qemu_mutex_lock_iothread();
3774 if (ret > 0) {
3775 IOHandlerRecord **pioh;
3777 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3778 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3779 ioh->fd_read(ioh->opaque);
3781 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3782 ioh->fd_write(ioh->opaque);
3786 /* remove deleted IO handlers */
3787 pioh = &first_io_handler;
3788 while (*pioh) {
3789 ioh = *pioh;
3790 if (ioh->deleted) {
3791 *pioh = ioh->next;
3792 qemu_free(ioh);
3793 } else
3794 pioh = &ioh->next;
3798 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3800 /* rearm timer, if not periodic */
3801 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3802 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3803 qemu_rearm_alarm_timer(alarm_timer);
3806 /* vm time timers */
3807 if (vm_running) {
3808 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3809 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3810 qemu_get_clock(vm_clock));
3813 /* real time timers */
3814 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3815 qemu_get_clock(rt_clock));
3817 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3818 qemu_get_clock(host_clock));
3820 /* Check bottom-halves last in case any of the earlier events triggered
3821 them. */
3822 qemu_bh_poll();
3826 static int qemu_cpu_exec(CPUState *env)
3828 int ret;
3829 #ifdef CONFIG_PROFILER
3830 int64_t ti;
3831 #endif
3833 #ifdef CONFIG_PROFILER
3834 ti = profile_getclock();
3835 #endif
3836 if (use_icount) {
3837 int64_t count;
3838 int decr;
3839 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3840 env->icount_decr.u16.low = 0;
3841 env->icount_extra = 0;
3842 count = qemu_next_deadline();
3843 count = (count + (1 << icount_time_shift) - 1)
3844 >> icount_time_shift;
3845 qemu_icount += count;
3846 decr = (count > 0xffff) ? 0xffff : count;
3847 count -= decr;
3848 env->icount_decr.u16.low = decr;
3849 env->icount_extra = count;
3851 ret = cpu_exec(env);
3852 #ifdef CONFIG_PROFILER
3853 qemu_time += profile_getclock() - ti;
3854 #endif
3855 if (use_icount) {
3856 /* Fold pending instructions back into the
3857 instruction counter, and clear the interrupt flag. */
3858 qemu_icount -= (env->icount_decr.u16.low
3859 + env->icount_extra);
3860 env->icount_decr.u32 = 0;
3861 env->icount_extra = 0;
3863 return ret;
3866 static void tcg_cpu_exec(void)
3868 int ret = 0;
3870 if (next_cpu == NULL)
3871 next_cpu = first_cpu;
3872 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3873 CPUState *env = cur_cpu = next_cpu;
3875 if (!vm_running)
3876 break;
3877 if (timer_alarm_pending) {
3878 timer_alarm_pending = 0;
3879 break;
3881 if (cpu_can_run(env))
3882 ret = qemu_cpu_exec(env);
3883 if (ret == EXCP_DEBUG) {
3884 gdb_set_stop_cpu(env);
3885 debug_requested = 1;
3886 break;
3891 static int cpu_has_work(CPUState *env)
3893 if (env->stop)
3894 return 1;
3895 if (env->stopped)
3896 return 0;
3897 if (!env->halted)
3898 return 1;
3899 if (qemu_cpu_has_work(env))
3900 return 1;
3901 return 0;
3904 static int tcg_has_work(void)
3906 CPUState *env;
3908 for (env = first_cpu; env != NULL; env = env->next_cpu)
3909 if (cpu_has_work(env))
3910 return 1;
3911 return 0;
3914 static int qemu_calculate_timeout(void)
3916 #ifndef CONFIG_IOTHREAD
3917 int timeout;
3919 if (!vm_running)
3920 timeout = 5000;
3921 else if (tcg_has_work())
3922 timeout = 0;
3923 else if (!use_icount)
3924 timeout = 5000;
3925 else {
3926 /* XXX: use timeout computed from timers */
3927 int64_t add;
3928 int64_t delta;
3929 /* Advance virtual time to the next event. */
3930 if (use_icount == 1) {
3931 /* When not using an adaptive execution frequency
3932 we tend to get badly out of sync with real time,
3933 so just delay for a reasonable amount of time. */
3934 delta = 0;
3935 } else {
3936 delta = cpu_get_icount() - cpu_get_clock();
3938 if (delta > 0) {
3939 /* If virtual time is ahead of real time then just
3940 wait for IO. */
3941 timeout = (delta / 1000000) + 1;
3942 } else {
3943 /* Wait for either IO to occur or the next
3944 timer event. */
3945 add = qemu_next_deadline();
3946 /* We advance the timer before checking for IO.
3947 Limit the amount we advance so that early IO
3948 activity won't get the guest too far ahead. */
3949 if (add > 10000000)
3950 add = 10000000;
3951 delta += add;
3952 add = (add + (1 << icount_time_shift) - 1)
3953 >> icount_time_shift;
3954 qemu_icount += add;
3955 timeout = delta / 1000000;
3956 if (timeout < 0)
3957 timeout = 0;
3961 return timeout;
3962 #else /* CONFIG_IOTHREAD */
3963 return 1000;
3964 #endif
3967 static int vm_can_run(void)
3969 if (powerdown_requested)
3970 return 0;
3971 if (reset_requested)
3972 return 0;
3973 if (shutdown_requested)
3974 return 0;
3975 if (debug_requested)
3976 return 0;
3977 return 1;
3980 qemu_irq qemu_system_powerdown;
3982 static void main_loop(void)
3984 int r;
3986 #ifdef CONFIG_IOTHREAD
3987 qemu_system_ready = 1;
3988 qemu_cond_broadcast(&qemu_system_cond);
3989 #endif
3991 for (;;) {
3992 do {
3993 #ifdef CONFIG_PROFILER
3994 int64_t ti;
3995 #endif
3996 #ifndef CONFIG_IOTHREAD
3997 tcg_cpu_exec();
3998 #endif
3999 #ifdef CONFIG_PROFILER
4000 ti = profile_getclock();
4001 #endif
4002 main_loop_wait(qemu_calculate_timeout());
4003 #ifdef CONFIG_PROFILER
4004 dev_time += profile_getclock() - ti;
4005 #endif
4006 } while (vm_can_run());
4008 if (qemu_debug_requested()) {
4009 monitor_protocol_event(QEVENT_DEBUG, NULL);
4010 vm_stop(EXCP_DEBUG);
4012 if (qemu_shutdown_requested()) {
4013 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4014 if (no_shutdown) {
4015 vm_stop(0);
4016 no_shutdown = 0;
4017 } else
4018 break;
4020 if (qemu_reset_requested()) {
4021 monitor_protocol_event(QEVENT_RESET, NULL);
4022 pause_all_vcpus();
4023 qemu_system_reset();
4024 resume_all_vcpus();
4026 if (qemu_powerdown_requested()) {
4027 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4028 qemu_irq_raise(qemu_system_powerdown);
4030 if ((r = qemu_vmstop_requested())) {
4031 monitor_protocol_event(QEVENT_STOP, NULL);
4032 vm_stop(r);
4035 pause_all_vcpus();
4038 static void version(void)
4040 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4043 static void help(int exitcode)
4045 const char *options_help =
4046 #define DEF(option, opt_arg, opt_enum, opt_help) \
4047 opt_help
4048 #define DEFHEADING(text) stringify(text) "\n"
4049 #include "qemu-options.h"
4050 #undef DEF
4051 #undef DEFHEADING
4052 #undef GEN_DOCS
4054 version();
4055 printf("usage: %s [options] [disk_image]\n"
4056 "\n"
4057 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4058 "\n"
4059 "%s\n"
4060 "During emulation, the following keys are useful:\n"
4061 "ctrl-alt-f toggle full screen\n"
4062 "ctrl-alt-n switch to virtual console 'n'\n"
4063 "ctrl-alt toggle mouse and keyboard grab\n"
4064 "\n"
4065 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4066 "qemu",
4067 options_help);
4068 exit(exitcode);
4071 #define HAS_ARG 0x0001
4073 enum {
4074 #define DEF(option, opt_arg, opt_enum, opt_help) \
4075 opt_enum,
4076 #define DEFHEADING(text)
4077 #include "qemu-options.h"
4078 #undef DEF
4079 #undef DEFHEADING
4080 #undef GEN_DOCS
4083 typedef struct QEMUOption {
4084 const char *name;
4085 int flags;
4086 int index;
4087 } QEMUOption;
4089 static const QEMUOption qemu_options[] = {
4090 { "h", 0, QEMU_OPTION_h },
4091 #define DEF(option, opt_arg, opt_enum, opt_help) \
4092 { option, opt_arg, opt_enum },
4093 #define DEFHEADING(text)
4094 #include "qemu-options.h"
4095 #undef DEF
4096 #undef DEFHEADING
4097 #undef GEN_DOCS
4098 { NULL },
4101 #ifdef HAS_AUDIO
4102 struct soundhw soundhw[] = {
4103 #ifdef HAS_AUDIO_CHOICE
4104 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4106 "pcspk",
4107 "PC speaker",
4110 { .init_isa = pcspk_audio_init }
4112 #endif
4114 #ifdef CONFIG_SB16
4116 "sb16",
4117 "Creative Sound Blaster 16",
4120 { .init_isa = SB16_init }
4122 #endif
4124 #ifdef CONFIG_CS4231A
4126 "cs4231a",
4127 "CS4231A",
4130 { .init_isa = cs4231a_init }
4132 #endif
4134 #ifdef CONFIG_ADLIB
4136 "adlib",
4137 #ifdef HAS_YMF262
4138 "Yamaha YMF262 (OPL3)",
4139 #else
4140 "Yamaha YM3812 (OPL2)",
4141 #endif
4144 { .init_isa = Adlib_init }
4146 #endif
4148 #ifdef CONFIG_GUS
4150 "gus",
4151 "Gravis Ultrasound GF1",
4154 { .init_isa = GUS_init }
4156 #endif
4158 #ifdef CONFIG_AC97
4160 "ac97",
4161 "Intel 82801AA AC97 Audio",
4164 { .init_pci = ac97_init }
4166 #endif
4168 #ifdef CONFIG_ES1370
4170 "es1370",
4171 "ENSONIQ AudioPCI ES1370",
4174 { .init_pci = es1370_init }
4176 #endif
4178 #endif /* HAS_AUDIO_CHOICE */
4180 { NULL, NULL, 0, 0, { NULL } }
4183 static void select_soundhw (const char *optarg)
4185 struct soundhw *c;
4187 if (*optarg == '?') {
4188 show_valid_cards:
4190 printf ("Valid sound card names (comma separated):\n");
4191 for (c = soundhw; c->name; ++c) {
4192 printf ("%-11s %s\n", c->name, c->descr);
4194 printf ("\n-soundhw all will enable all of the above\n");
4195 exit (*optarg != '?');
4197 else {
4198 size_t l;
4199 const char *p;
4200 char *e;
4201 int bad_card = 0;
4203 if (!strcmp (optarg, "all")) {
4204 for (c = soundhw; c->name; ++c) {
4205 c->enabled = 1;
4207 return;
4210 p = optarg;
4211 while (*p) {
4212 e = strchr (p, ',');
4213 l = !e ? strlen (p) : (size_t) (e - p);
4215 for (c = soundhw; c->name; ++c) {
4216 if (!strncmp (c->name, p, l) && !c->name[l]) {
4217 c->enabled = 1;
4218 break;
4222 if (!c->name) {
4223 if (l > 80) {
4224 fprintf (stderr,
4225 "Unknown sound card name (too big to show)\n");
4227 else {
4228 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4229 (int) l, p);
4231 bad_card = 1;
4233 p += l + (e != NULL);
4236 if (bad_card)
4237 goto show_valid_cards;
4240 #endif
4242 static void select_vgahw (const char *p)
4244 const char *opts;
4246 default_vga = 0;
4247 vga_interface_type = VGA_NONE;
4248 if (strstart(p, "std", &opts)) {
4249 vga_interface_type = VGA_STD;
4250 } else if (strstart(p, "cirrus", &opts)) {
4251 vga_interface_type = VGA_CIRRUS;
4252 } else if (strstart(p, "vmware", &opts)) {
4253 vga_interface_type = VGA_VMWARE;
4254 } else if (strstart(p, "xenfb", &opts)) {
4255 vga_interface_type = VGA_XENFB;
4256 } else if (!strstart(p, "none", &opts)) {
4257 invalid_vga:
4258 fprintf(stderr, "Unknown vga type: %s\n", p);
4259 exit(1);
4261 while (*opts) {
4262 const char *nextopt;
4264 if (strstart(opts, ",retrace=", &nextopt)) {
4265 opts = nextopt;
4266 if (strstart(opts, "dumb", &nextopt))
4267 vga_retrace_method = VGA_RETRACE_DUMB;
4268 else if (strstart(opts, "precise", &nextopt))
4269 vga_retrace_method = VGA_RETRACE_PRECISE;
4270 else goto invalid_vga;
4271 } else goto invalid_vga;
4272 opts = nextopt;
4276 #ifdef TARGET_I386
4277 static int balloon_parse(const char *arg)
4279 QemuOpts *opts;
4281 if (strcmp(arg, "none") == 0) {
4282 return 0;
4285 if (!strncmp(arg, "virtio", 6)) {
4286 if (arg[6] == ',') {
4287 /* have params -> parse them */
4288 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4289 if (!opts)
4290 return -1;
4291 } else {
4292 /* create empty opts */
4293 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4295 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4296 return 0;
4299 return -1;
4301 #endif
4303 #ifdef _WIN32
4304 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4306 exit(STATUS_CONTROL_C_EXIT);
4307 return TRUE;
4309 #endif
4311 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4313 int ret;
4315 if(strlen(str) != 36)
4316 return -1;
4318 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4319 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4320 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4322 if(ret != 16)
4323 return -1;
4325 #ifdef TARGET_I386
4326 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4327 #endif
4329 return 0;
4332 #ifndef _WIN32
4334 static void termsig_handler(int signal)
4336 qemu_system_shutdown_request();
4339 static void sigchld_handler(int signal)
4341 waitpid(-1, NULL, WNOHANG);
4344 static void sighandler_setup(void)
4346 struct sigaction act;
4348 memset(&act, 0, sizeof(act));
4349 act.sa_handler = termsig_handler;
4350 sigaction(SIGINT, &act, NULL);
4351 sigaction(SIGHUP, &act, NULL);
4352 sigaction(SIGTERM, &act, NULL);
4354 act.sa_handler = sigchld_handler;
4355 act.sa_flags = SA_NOCLDSTOP;
4356 sigaction(SIGCHLD, &act, NULL);
4359 #endif
4361 #ifdef _WIN32
4362 /* Look for support files in the same directory as the executable. */
4363 static char *find_datadir(const char *argv0)
4365 char *p;
4366 char buf[MAX_PATH];
4367 DWORD len;
4369 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4370 if (len == 0) {
4371 return NULL;
4374 buf[len] = 0;
4375 p = buf + len - 1;
4376 while (p != buf && *p != '\\')
4377 p--;
4378 *p = 0;
4379 if (access(buf, R_OK) == 0) {
4380 return qemu_strdup(buf);
4382 return NULL;
4384 #else /* !_WIN32 */
4386 /* Find a likely location for support files using the location of the binary.
4387 For installed binaries this will be "$bindir/../share/qemu". When
4388 running from the build tree this will be "$bindir/../pc-bios". */
4389 #define SHARE_SUFFIX "/share/qemu"
4390 #define BUILD_SUFFIX "/pc-bios"
4391 static char *find_datadir(const char *argv0)
4393 char *dir;
4394 char *p = NULL;
4395 char *res;
4396 char buf[PATH_MAX];
4397 size_t max_len;
4399 #if defined(__linux__)
4401 int len;
4402 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4403 if (len > 0) {
4404 buf[len] = 0;
4405 p = buf;
4408 #elif defined(__FreeBSD__)
4410 int len;
4411 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4412 if (len > 0) {
4413 buf[len] = 0;
4414 p = buf;
4417 #endif
4418 /* If we don't have any way of figuring out the actual executable
4419 location then try argv[0]. */
4420 if (!p) {
4421 p = realpath(argv0, buf);
4422 if (!p) {
4423 return NULL;
4426 dir = dirname(p);
4427 dir = dirname(dir);
4429 max_len = strlen(dir) +
4430 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4431 res = qemu_mallocz(max_len);
4432 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4433 if (access(res, R_OK)) {
4434 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4435 if (access(res, R_OK)) {
4436 qemu_free(res);
4437 res = NULL;
4441 return res;
4443 #undef SHARE_SUFFIX
4444 #undef BUILD_SUFFIX
4445 #endif
4447 char *qemu_find_file(int type, const char *name)
4449 int len;
4450 const char *subdir;
4451 char *buf;
4453 /* If name contains path separators then try it as a straight path. */
4454 if ((strchr(name, '/') || strchr(name, '\\'))
4455 && access(name, R_OK) == 0) {
4456 return qemu_strdup(name);
4458 switch (type) {
4459 case QEMU_FILE_TYPE_BIOS:
4460 subdir = "";
4461 break;
4462 case QEMU_FILE_TYPE_KEYMAP:
4463 subdir = "keymaps/";
4464 break;
4465 default:
4466 abort();
4468 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4469 buf = qemu_mallocz(len);
4470 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4471 if (access(buf, R_OK)) {
4472 qemu_free(buf);
4473 return NULL;
4475 return buf;
4478 static int device_help_func(QemuOpts *opts, void *opaque)
4480 return qdev_device_help(opts);
4483 static int device_init_func(QemuOpts *opts, void *opaque)
4485 DeviceState *dev;
4487 dev = qdev_device_add(opts);
4488 if (!dev)
4489 return -1;
4490 return 0;
4493 static int chardev_init_func(QemuOpts *opts, void *opaque)
4495 CharDriverState *chr;
4497 chr = qemu_chr_open_opts(opts, NULL);
4498 if (!chr)
4499 return -1;
4500 return 0;
4503 static int mon_init_func(QemuOpts *opts, void *opaque)
4505 CharDriverState *chr;
4506 const char *chardev;
4507 const char *mode;
4508 int flags;
4510 mode = qemu_opt_get(opts, "mode");
4511 if (mode == NULL) {
4512 mode = "readline";
4514 if (strcmp(mode, "readline") == 0) {
4515 flags = MONITOR_USE_READLINE;
4516 } else if (strcmp(mode, "control") == 0) {
4517 flags = MONITOR_USE_CONTROL;
4518 } else {
4519 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4520 exit(1);
4523 if (qemu_opt_get_bool(opts, "default", 0))
4524 flags |= MONITOR_IS_DEFAULT;
4526 chardev = qemu_opt_get(opts, "chardev");
4527 chr = qemu_chr_find(chardev);
4528 if (chr == NULL) {
4529 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4530 exit(1);
4533 monitor_init(chr, flags);
4534 return 0;
4537 static void monitor_parse(const char *optarg, const char *mode)
4539 static int monitor_device_index = 0;
4540 QemuOpts *opts;
4541 const char *p;
4542 char label[32];
4543 int def = 0;
4545 if (strstart(optarg, "chardev:", &p)) {
4546 snprintf(label, sizeof(label), "%s", p);
4547 } else {
4548 if (monitor_device_index) {
4549 snprintf(label, sizeof(label), "monitor%d",
4550 monitor_device_index);
4551 } else {
4552 snprintf(label, sizeof(label), "monitor");
4553 def = 1;
4555 opts = qemu_chr_parse_compat(label, optarg);
4556 if (!opts) {
4557 fprintf(stderr, "parse error: %s\n", optarg);
4558 exit(1);
4562 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4563 if (!opts) {
4564 fprintf(stderr, "duplicate chardev: %s\n", label);
4565 exit(1);
4567 qemu_opt_set(opts, "mode", mode);
4568 qemu_opt_set(opts, "chardev", label);
4569 if (def)
4570 qemu_opt_set(opts, "default", "on");
4571 monitor_device_index++;
4574 struct device_config {
4575 enum {
4576 DEV_USB, /* -usbdevice */
4577 DEV_BT, /* -bt */
4578 DEV_SERIAL, /* -serial */
4579 DEV_PARALLEL, /* -parallel */
4580 DEV_VIRTCON, /* -virtioconsole */
4581 DEV_DEBUGCON, /* -debugcon */
4582 } type;
4583 const char *cmdline;
4584 QTAILQ_ENTRY(device_config) next;
4586 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4588 static void add_device_config(int type, const char *cmdline)
4590 struct device_config *conf;
4592 conf = qemu_mallocz(sizeof(*conf));
4593 conf->type = type;
4594 conf->cmdline = cmdline;
4595 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4598 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4600 struct device_config *conf;
4601 int rc;
4603 QTAILQ_FOREACH(conf, &device_configs, next) {
4604 if (conf->type != type)
4605 continue;
4606 rc = func(conf->cmdline);
4607 if (0 != rc)
4608 return rc;
4610 return 0;
4613 static int serial_parse(const char *devname)
4615 static int index = 0;
4616 char label[32];
4618 if (strcmp(devname, "none") == 0)
4619 return 0;
4620 if (index == MAX_SERIAL_PORTS) {
4621 fprintf(stderr, "qemu: too many serial ports\n");
4622 exit(1);
4624 snprintf(label, sizeof(label), "serial%d", index);
4625 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4626 if (!serial_hds[index]) {
4627 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4628 devname, strerror(errno));
4629 return -1;
4631 index++;
4632 return 0;
4635 static int parallel_parse(const char *devname)
4637 static int index = 0;
4638 char label[32];
4640 if (strcmp(devname, "none") == 0)
4641 return 0;
4642 if (index == MAX_PARALLEL_PORTS) {
4643 fprintf(stderr, "qemu: too many parallel ports\n");
4644 exit(1);
4646 snprintf(label, sizeof(label), "parallel%d", index);
4647 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4648 if (!parallel_hds[index]) {
4649 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4650 devname, strerror(errno));
4651 return -1;
4653 index++;
4654 return 0;
4657 static int virtcon_parse(const char *devname)
4659 static int index = 0;
4660 char label[32];
4661 QemuOpts *bus_opts, *dev_opts;
4663 if (strcmp(devname, "none") == 0)
4664 return 0;
4665 if (index == MAX_VIRTIO_CONSOLES) {
4666 fprintf(stderr, "qemu: too many virtio consoles\n");
4667 exit(1);
4670 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4671 qemu_opt_set(bus_opts, "driver", "virtio-serial");
4673 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4674 qemu_opt_set(dev_opts, "driver", "virtconsole");
4676 snprintf(label, sizeof(label), "virtcon%d", index);
4677 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4678 if (!virtcon_hds[index]) {
4679 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4680 devname, strerror(errno));
4681 return -1;
4683 qemu_opt_set(dev_opts, "chardev", label);
4685 index++;
4686 return 0;
4689 static int debugcon_parse(const char *devname)
4691 QemuOpts *opts;
4693 if (!qemu_chr_open("debugcon", devname, NULL)) {
4694 exit(1);
4696 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4697 if (!opts) {
4698 fprintf(stderr, "qemu: already have a debugcon device\n");
4699 exit(1);
4701 qemu_opt_set(opts, "driver", "isa-debugcon");
4702 qemu_opt_set(opts, "chardev", "debugcon");
4703 return 0;
4706 static const QEMUOption *lookup_opt(int argc, char **argv,
4707 const char **poptarg, int *poptind)
4709 const QEMUOption *popt;
4710 int optind = *poptind;
4711 char *r = argv[optind];
4712 const char *optarg;
4714 optind++;
4715 /* Treat --foo the same as -foo. */
4716 if (r[1] == '-')
4717 r++;
4718 popt = qemu_options;
4719 for(;;) {
4720 if (!popt->name) {
4721 fprintf(stderr, "%s: invalid option -- '%s'\n",
4722 argv[0], r);
4723 exit(1);
4725 if (!strcmp(popt->name, r + 1))
4726 break;
4727 popt++;
4729 if (popt->flags & HAS_ARG) {
4730 if (optind >= argc) {
4731 fprintf(stderr, "%s: option '%s' requires an argument\n",
4732 argv[0], r);
4733 exit(1);
4735 optarg = argv[optind++];
4736 } else {
4737 optarg = NULL;
4740 *poptarg = optarg;
4741 *poptind = optind;
4743 return popt;
4746 int main(int argc, char **argv, char **envp)
4748 const char *gdbstub_dev = NULL;
4749 uint32_t boot_devices_bitmap = 0;
4750 int i;
4751 int snapshot, linux_boot, net_boot;
4752 const char *initrd_filename;
4753 const char *kernel_filename, *kernel_cmdline;
4754 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4755 DisplayState *ds;
4756 DisplayChangeListener *dcl;
4757 int cyls, heads, secs, translation;
4758 QemuOpts *hda_opts = NULL, *opts;
4759 int optind;
4760 const char *optarg;
4761 const char *loadvm = NULL;
4762 QEMUMachine *machine;
4763 const char *cpu_model;
4764 #ifndef _WIN32
4765 int fds[2];
4766 #endif
4767 int tb_size;
4768 const char *pid_file = NULL;
4769 const char *incoming = NULL;
4770 #ifndef _WIN32
4771 int fd = 0;
4772 struct passwd *pwd = NULL;
4773 const char *chroot_dir = NULL;
4774 const char *run_as = NULL;
4775 #endif
4776 CPUState *env;
4777 int show_vnc_port = 0;
4778 int defconfig = 1;
4780 init_clocks();
4782 qemu_errors_to_file(stderr);
4783 qemu_cache_utils_init(envp);
4785 QLIST_INIT (&vm_change_state_head);
4786 #ifndef _WIN32
4788 struct sigaction act;
4789 sigfillset(&act.sa_mask);
4790 act.sa_flags = 0;
4791 act.sa_handler = SIG_IGN;
4792 sigaction(SIGPIPE, &act, NULL);
4794 #else
4795 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4796 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4797 QEMU to run on a single CPU */
4799 HANDLE h;
4800 DWORD mask, smask;
4801 int i;
4802 h = GetCurrentProcess();
4803 if (GetProcessAffinityMask(h, &mask, &smask)) {
4804 for(i = 0; i < 32; i++) {
4805 if (mask & (1 << i))
4806 break;
4808 if (i != 32) {
4809 mask = 1 << i;
4810 SetProcessAffinityMask(h, mask);
4814 #endif
4816 module_call_init(MODULE_INIT_MACHINE);
4817 machine = find_default_machine();
4818 cpu_model = NULL;
4819 initrd_filename = NULL;
4820 ram_size = 0;
4821 snapshot = 0;
4822 kernel_filename = NULL;
4823 kernel_cmdline = "";
4824 cyls = heads = secs = 0;
4825 translation = BIOS_ATA_TRANSLATION_AUTO;
4827 for (i = 0; i < MAX_NODES; i++) {
4828 node_mem[i] = 0;
4829 node_cpumask[i] = 0;
4832 nb_numa_nodes = 0;
4833 nb_nics = 0;
4835 tb_size = 0;
4836 autostart= 1;
4838 /* first pass of option parsing */
4839 optind = 1;
4840 while (optind < argc) {
4841 if (argv[optind][0] != '-') {
4842 /* disk image */
4843 optind++;
4844 continue;
4845 } else {
4846 const QEMUOption *popt;
4848 popt = lookup_opt(argc, argv, &optarg, &optind);
4849 switch (popt->index) {
4850 case QEMU_OPTION_nodefconfig:
4851 defconfig=0;
4852 break;
4857 if (defconfig) {
4858 FILE *fp;
4859 fp = fopen(CONFIG_QEMU_CONFDIR "/qemu.conf", "r");
4860 if (fp) {
4861 if (qemu_config_parse(fp) != 0) {
4862 exit(1);
4864 fclose(fp);
4867 fp = fopen(CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf", "r");
4868 if (fp) {
4869 if (qemu_config_parse(fp) != 0) {
4870 exit(1);
4872 fclose(fp);
4876 /* second pass of option parsing */
4877 optind = 1;
4878 for(;;) {
4879 if (optind >= argc)
4880 break;
4881 if (argv[optind][0] != '-') {
4882 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4883 } else {
4884 const QEMUOption *popt;
4886 popt = lookup_opt(argc, argv, &optarg, &optind);
4887 switch(popt->index) {
4888 case QEMU_OPTION_M:
4889 machine = find_machine(optarg);
4890 if (!machine) {
4891 QEMUMachine *m;
4892 printf("Supported machines are:\n");
4893 for(m = first_machine; m != NULL; m = m->next) {
4894 if (m->alias)
4895 printf("%-10s %s (alias of %s)\n",
4896 m->alias, m->desc, m->name);
4897 printf("%-10s %s%s\n",
4898 m->name, m->desc,
4899 m->is_default ? " (default)" : "");
4901 exit(*optarg != '?');
4903 break;
4904 case QEMU_OPTION_cpu:
4905 /* hw initialization will check this */
4906 if (*optarg == '?') {
4907 /* XXX: implement xxx_cpu_list for targets that still miss it */
4908 #if defined(cpu_list)
4909 cpu_list(stdout, &fprintf);
4910 #endif
4911 exit(0);
4912 } else {
4913 cpu_model = optarg;
4915 break;
4916 case QEMU_OPTION_initrd:
4917 initrd_filename = optarg;
4918 break;
4919 case QEMU_OPTION_hda:
4920 if (cyls == 0)
4921 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4922 else
4923 hda_opts = drive_add(optarg, HD_ALIAS
4924 ",cyls=%d,heads=%d,secs=%d%s",
4925 0, cyls, heads, secs,
4926 translation == BIOS_ATA_TRANSLATION_LBA ?
4927 ",trans=lba" :
4928 translation == BIOS_ATA_TRANSLATION_NONE ?
4929 ",trans=none" : "");
4930 break;
4931 case QEMU_OPTION_hdb:
4932 case QEMU_OPTION_hdc:
4933 case QEMU_OPTION_hdd:
4934 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4935 break;
4936 case QEMU_OPTION_drive:
4937 drive_add(NULL, "%s", optarg);
4938 break;
4939 case QEMU_OPTION_set:
4940 if (qemu_set_option(optarg) != 0)
4941 exit(1);
4942 break;
4943 case QEMU_OPTION_global:
4944 if (qemu_global_option(optarg) != 0)
4945 exit(1);
4946 break;
4947 case QEMU_OPTION_mtdblock:
4948 drive_add(optarg, MTD_ALIAS);
4949 break;
4950 case QEMU_OPTION_sd:
4951 drive_add(optarg, SD_ALIAS);
4952 break;
4953 case QEMU_OPTION_pflash:
4954 drive_add(optarg, PFLASH_ALIAS);
4955 break;
4956 case QEMU_OPTION_snapshot:
4957 snapshot = 1;
4958 break;
4959 case QEMU_OPTION_hdachs:
4961 const char *p;
4962 p = optarg;
4963 cyls = strtol(p, (char **)&p, 0);
4964 if (cyls < 1 || cyls > 16383)
4965 goto chs_fail;
4966 if (*p != ',')
4967 goto chs_fail;
4968 p++;
4969 heads = strtol(p, (char **)&p, 0);
4970 if (heads < 1 || heads > 16)
4971 goto chs_fail;
4972 if (*p != ',')
4973 goto chs_fail;
4974 p++;
4975 secs = strtol(p, (char **)&p, 0);
4976 if (secs < 1 || secs > 63)
4977 goto chs_fail;
4978 if (*p == ',') {
4979 p++;
4980 if (!strcmp(p, "none"))
4981 translation = BIOS_ATA_TRANSLATION_NONE;
4982 else if (!strcmp(p, "lba"))
4983 translation = BIOS_ATA_TRANSLATION_LBA;
4984 else if (!strcmp(p, "auto"))
4985 translation = BIOS_ATA_TRANSLATION_AUTO;
4986 else
4987 goto chs_fail;
4988 } else if (*p != '\0') {
4989 chs_fail:
4990 fprintf(stderr, "qemu: invalid physical CHS format\n");
4991 exit(1);
4993 if (hda_opts != NULL) {
4994 char num[16];
4995 snprintf(num, sizeof(num), "%d", cyls);
4996 qemu_opt_set(hda_opts, "cyls", num);
4997 snprintf(num, sizeof(num), "%d", heads);
4998 qemu_opt_set(hda_opts, "heads", num);
4999 snprintf(num, sizeof(num), "%d", secs);
5000 qemu_opt_set(hda_opts, "secs", num);
5001 if (translation == BIOS_ATA_TRANSLATION_LBA)
5002 qemu_opt_set(hda_opts, "trans", "lba");
5003 if (translation == BIOS_ATA_TRANSLATION_NONE)
5004 qemu_opt_set(hda_opts, "trans", "none");
5007 break;
5008 case QEMU_OPTION_numa:
5009 if (nb_numa_nodes >= MAX_NODES) {
5010 fprintf(stderr, "qemu: too many NUMA nodes\n");
5011 exit(1);
5013 numa_add(optarg);
5014 break;
5015 case QEMU_OPTION_nographic:
5016 display_type = DT_NOGRAPHIC;
5017 break;
5018 #ifdef CONFIG_CURSES
5019 case QEMU_OPTION_curses:
5020 display_type = DT_CURSES;
5021 break;
5022 #endif
5023 case QEMU_OPTION_portrait:
5024 graphic_rotate = 1;
5025 break;
5026 case QEMU_OPTION_kernel:
5027 kernel_filename = optarg;
5028 break;
5029 case QEMU_OPTION_append:
5030 kernel_cmdline = optarg;
5031 break;
5032 case QEMU_OPTION_cdrom:
5033 drive_add(optarg, CDROM_ALIAS);
5034 break;
5035 case QEMU_OPTION_boot:
5037 static const char * const params[] = {
5038 "order", "once", "menu", NULL
5040 char buf[sizeof(boot_devices)];
5041 char *standard_boot_devices;
5042 int legacy = 0;
5044 if (!strchr(optarg, '=')) {
5045 legacy = 1;
5046 pstrcpy(buf, sizeof(buf), optarg);
5047 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5048 fprintf(stderr,
5049 "qemu: unknown boot parameter '%s' in '%s'\n",
5050 buf, optarg);
5051 exit(1);
5054 if (legacy ||
5055 get_param_value(buf, sizeof(buf), "order", optarg)) {
5056 boot_devices_bitmap = parse_bootdevices(buf);
5057 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5059 if (!legacy) {
5060 if (get_param_value(buf, sizeof(buf),
5061 "once", optarg)) {
5062 boot_devices_bitmap |= parse_bootdevices(buf);
5063 standard_boot_devices = qemu_strdup(boot_devices);
5064 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5065 qemu_register_reset(restore_boot_devices,
5066 standard_boot_devices);
5068 if (get_param_value(buf, sizeof(buf),
5069 "menu", optarg)) {
5070 if (!strcmp(buf, "on")) {
5071 boot_menu = 1;
5072 } else if (!strcmp(buf, "off")) {
5073 boot_menu = 0;
5074 } else {
5075 fprintf(stderr,
5076 "qemu: invalid option value '%s'\n",
5077 buf);
5078 exit(1);
5083 break;
5084 case QEMU_OPTION_fda:
5085 case QEMU_OPTION_fdb:
5086 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5087 break;
5088 #ifdef TARGET_I386
5089 case QEMU_OPTION_no_fd_bootchk:
5090 fd_bootchk = 0;
5091 break;
5092 #endif
5093 case QEMU_OPTION_netdev:
5094 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5095 exit(1);
5097 break;
5098 case QEMU_OPTION_net:
5099 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5100 exit(1);
5102 break;
5103 #ifdef CONFIG_SLIRP
5104 case QEMU_OPTION_tftp:
5105 legacy_tftp_prefix = optarg;
5106 break;
5107 case QEMU_OPTION_bootp:
5108 legacy_bootp_filename = optarg;
5109 break;
5110 #ifndef _WIN32
5111 case QEMU_OPTION_smb:
5112 if (net_slirp_smb(optarg) < 0)
5113 exit(1);
5114 break;
5115 #endif
5116 case QEMU_OPTION_redir:
5117 if (net_slirp_redir(optarg) < 0)
5118 exit(1);
5119 break;
5120 #endif
5121 case QEMU_OPTION_bt:
5122 add_device_config(DEV_BT, optarg);
5123 break;
5124 #ifdef HAS_AUDIO
5125 case QEMU_OPTION_audio_help:
5126 AUD_help ();
5127 exit (0);
5128 break;
5129 case QEMU_OPTION_soundhw:
5130 select_soundhw (optarg);
5131 break;
5132 #endif
5133 case QEMU_OPTION_h:
5134 help(0);
5135 break;
5136 case QEMU_OPTION_version:
5137 version();
5138 exit(0);
5139 break;
5140 case QEMU_OPTION_m: {
5141 uint64_t value;
5142 char *ptr;
5144 value = strtoul(optarg, &ptr, 10);
5145 switch (*ptr) {
5146 case 0: case 'M': case 'm':
5147 value <<= 20;
5148 break;
5149 case 'G': case 'g':
5150 value <<= 30;
5151 break;
5152 default:
5153 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5154 exit(1);
5157 /* On 32-bit hosts, QEMU is limited by virtual address space */
5158 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5159 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5160 exit(1);
5162 if (value != (uint64_t)(ram_addr_t)value) {
5163 fprintf(stderr, "qemu: ram size too large\n");
5164 exit(1);
5166 ram_size = value;
5167 break;
5169 case QEMU_OPTION_d:
5171 int mask;
5172 const CPULogItem *item;
5174 mask = cpu_str_to_log_mask(optarg);
5175 if (!mask) {
5176 printf("Log items (comma separated):\n");
5177 for(item = cpu_log_items; item->mask != 0; item++) {
5178 printf("%-10s %s\n", item->name, item->help);
5180 exit(1);
5182 cpu_set_log(mask);
5184 break;
5185 case QEMU_OPTION_s:
5186 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5187 break;
5188 case QEMU_OPTION_gdb:
5189 gdbstub_dev = optarg;
5190 break;
5191 case QEMU_OPTION_L:
5192 data_dir = optarg;
5193 break;
5194 case QEMU_OPTION_bios:
5195 bios_name = optarg;
5196 break;
5197 case QEMU_OPTION_singlestep:
5198 singlestep = 1;
5199 break;
5200 case QEMU_OPTION_S:
5201 autostart = 0;
5202 break;
5203 case QEMU_OPTION_k:
5204 keyboard_layout = optarg;
5205 break;
5206 case QEMU_OPTION_localtime:
5207 rtc_utc = 0;
5208 break;
5209 case QEMU_OPTION_vga:
5210 select_vgahw (optarg);
5211 break;
5212 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5213 case QEMU_OPTION_g:
5215 const char *p;
5216 int w, h, depth;
5217 p = optarg;
5218 w = strtol(p, (char **)&p, 10);
5219 if (w <= 0) {
5220 graphic_error:
5221 fprintf(stderr, "qemu: invalid resolution or depth\n");
5222 exit(1);
5224 if (*p != 'x')
5225 goto graphic_error;
5226 p++;
5227 h = strtol(p, (char **)&p, 10);
5228 if (h <= 0)
5229 goto graphic_error;
5230 if (*p == 'x') {
5231 p++;
5232 depth = strtol(p, (char **)&p, 10);
5233 if (depth != 8 && depth != 15 && depth != 16 &&
5234 depth != 24 && depth != 32)
5235 goto graphic_error;
5236 } else if (*p == '\0') {
5237 depth = graphic_depth;
5238 } else {
5239 goto graphic_error;
5242 graphic_width = w;
5243 graphic_height = h;
5244 graphic_depth = depth;
5246 break;
5247 #endif
5248 case QEMU_OPTION_echr:
5250 char *r;
5251 term_escape_char = strtol(optarg, &r, 0);
5252 if (r == optarg)
5253 printf("Bad argument to echr\n");
5254 break;
5256 case QEMU_OPTION_monitor:
5257 monitor_parse(optarg, "readline");
5258 default_monitor = 0;
5259 break;
5260 case QEMU_OPTION_qmp:
5261 monitor_parse(optarg, "control");
5262 default_monitor = 0;
5263 break;
5264 case QEMU_OPTION_mon:
5265 opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5266 if (!opts) {
5267 fprintf(stderr, "parse error: %s\n", optarg);
5268 exit(1);
5270 default_monitor = 0;
5271 break;
5272 case QEMU_OPTION_chardev:
5273 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5274 if (!opts) {
5275 fprintf(stderr, "parse error: %s\n", optarg);
5276 exit(1);
5278 break;
5279 case QEMU_OPTION_serial:
5280 add_device_config(DEV_SERIAL, optarg);
5281 default_serial = 0;
5282 break;
5283 case QEMU_OPTION_watchdog:
5284 if (watchdog) {
5285 fprintf(stderr,
5286 "qemu: only one watchdog option may be given\n");
5287 return 1;
5289 watchdog = optarg;
5290 break;
5291 case QEMU_OPTION_watchdog_action:
5292 if (select_watchdog_action(optarg) == -1) {
5293 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5294 exit(1);
5296 break;
5297 case QEMU_OPTION_virtiocon:
5298 add_device_config(DEV_VIRTCON, optarg);
5299 default_virtcon = 0;
5300 break;
5301 case QEMU_OPTION_parallel:
5302 add_device_config(DEV_PARALLEL, optarg);
5303 default_parallel = 0;
5304 break;
5305 case QEMU_OPTION_debugcon:
5306 add_device_config(DEV_DEBUGCON, optarg);
5307 break;
5308 case QEMU_OPTION_loadvm:
5309 loadvm = optarg;
5310 break;
5311 case QEMU_OPTION_full_screen:
5312 full_screen = 1;
5313 break;
5314 #ifdef CONFIG_SDL
5315 case QEMU_OPTION_no_frame:
5316 no_frame = 1;
5317 break;
5318 case QEMU_OPTION_alt_grab:
5319 alt_grab = 1;
5320 break;
5321 case QEMU_OPTION_ctrl_grab:
5322 ctrl_grab = 1;
5323 break;
5324 case QEMU_OPTION_no_quit:
5325 no_quit = 1;
5326 break;
5327 case QEMU_OPTION_sdl:
5328 display_type = DT_SDL;
5329 break;
5330 #endif
5331 case QEMU_OPTION_pidfile:
5332 pid_file = optarg;
5333 break;
5334 #ifdef TARGET_I386
5335 case QEMU_OPTION_win2k_hack:
5336 win2k_install_hack = 1;
5337 break;
5338 case QEMU_OPTION_rtc_td_hack:
5339 rtc_td_hack = 1;
5340 break;
5341 case QEMU_OPTION_acpitable:
5342 if(acpi_table_add(optarg) < 0) {
5343 fprintf(stderr, "Wrong acpi table provided\n");
5344 exit(1);
5346 break;
5347 case QEMU_OPTION_smbios:
5348 if(smbios_entry_add(optarg) < 0) {
5349 fprintf(stderr, "Wrong smbios provided\n");
5350 exit(1);
5352 break;
5353 #endif
5354 #ifdef CONFIG_KVM
5355 case QEMU_OPTION_enable_kvm:
5356 kvm_allowed = 1;
5357 break;
5358 #endif
5359 case QEMU_OPTION_usb:
5360 usb_enabled = 1;
5361 break;
5362 case QEMU_OPTION_usbdevice:
5363 usb_enabled = 1;
5364 add_device_config(DEV_USB, optarg);
5365 break;
5366 case QEMU_OPTION_device:
5367 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5368 exit(1);
5370 break;
5371 case QEMU_OPTION_smp:
5372 smp_parse(optarg);
5373 if (smp_cpus < 1) {
5374 fprintf(stderr, "Invalid number of CPUs\n");
5375 exit(1);
5377 if (max_cpus < smp_cpus) {
5378 fprintf(stderr, "maxcpus must be equal to or greater than "
5379 "smp\n");
5380 exit(1);
5382 if (max_cpus > 255) {
5383 fprintf(stderr, "Unsupported number of maxcpus\n");
5384 exit(1);
5386 break;
5387 case QEMU_OPTION_vnc:
5388 display_type = DT_VNC;
5389 vnc_display = optarg;
5390 break;
5391 #ifdef TARGET_I386
5392 case QEMU_OPTION_no_acpi:
5393 acpi_enabled = 0;
5394 break;
5395 case QEMU_OPTION_no_hpet:
5396 no_hpet = 1;
5397 break;
5398 case QEMU_OPTION_balloon:
5399 if (balloon_parse(optarg) < 0) {
5400 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5401 exit(1);
5403 break;
5404 #endif
5405 case QEMU_OPTION_no_reboot:
5406 no_reboot = 1;
5407 break;
5408 case QEMU_OPTION_no_shutdown:
5409 no_shutdown = 1;
5410 break;
5411 case QEMU_OPTION_show_cursor:
5412 cursor_hide = 0;
5413 break;
5414 case QEMU_OPTION_uuid:
5415 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5416 fprintf(stderr, "Fail to parse UUID string."
5417 " Wrong format.\n");
5418 exit(1);
5420 break;
5421 #ifndef _WIN32
5422 case QEMU_OPTION_daemonize:
5423 daemonize = 1;
5424 break;
5425 #endif
5426 case QEMU_OPTION_option_rom:
5427 if (nb_option_roms >= MAX_OPTION_ROMS) {
5428 fprintf(stderr, "Too many option ROMs\n");
5429 exit(1);
5431 option_rom[nb_option_roms] = optarg;
5432 nb_option_roms++;
5433 break;
5434 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5435 case QEMU_OPTION_semihosting:
5436 semihosting_enabled = 1;
5437 break;
5438 #endif
5439 case QEMU_OPTION_name:
5440 qemu_name = qemu_strdup(optarg);
5442 char *p = strchr(qemu_name, ',');
5443 if (p != NULL) {
5444 *p++ = 0;
5445 if (strncmp(p, "process=", 8)) {
5446 fprintf(stderr, "Unknown subargument %s to -name", p);
5447 exit(1);
5449 p += 8;
5450 set_proc_name(p);
5453 break;
5454 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5455 case QEMU_OPTION_prom_env:
5456 if (nb_prom_envs >= MAX_PROM_ENVS) {
5457 fprintf(stderr, "Too many prom variables\n");
5458 exit(1);
5460 prom_envs[nb_prom_envs] = optarg;
5461 nb_prom_envs++;
5462 break;
5463 #endif
5464 #ifdef TARGET_ARM
5465 case QEMU_OPTION_old_param:
5466 old_param = 1;
5467 break;
5468 #endif
5469 case QEMU_OPTION_clock:
5470 configure_alarms(optarg);
5471 break;
5472 case QEMU_OPTION_startdate:
5473 configure_rtc_date_offset(optarg, 1);
5474 break;
5475 case QEMU_OPTION_rtc:
5476 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5477 if (!opts) {
5478 fprintf(stderr, "parse error: %s\n", optarg);
5479 exit(1);
5481 configure_rtc(opts);
5482 break;
5483 case QEMU_OPTION_tb_size:
5484 tb_size = strtol(optarg, NULL, 0);
5485 if (tb_size < 0)
5486 tb_size = 0;
5487 break;
5488 case QEMU_OPTION_icount:
5489 use_icount = 1;
5490 if (strcmp(optarg, "auto") == 0) {
5491 icount_time_shift = -1;
5492 } else {
5493 icount_time_shift = strtol(optarg, NULL, 0);
5495 break;
5496 case QEMU_OPTION_incoming:
5497 incoming = optarg;
5498 break;
5499 case QEMU_OPTION_nodefaults:
5500 default_serial = 0;
5501 default_parallel = 0;
5502 default_virtcon = 0;
5503 default_monitor = 0;
5504 default_vga = 0;
5505 default_net = 0;
5506 default_floppy = 0;
5507 default_cdrom = 0;
5508 default_sdcard = 0;
5509 break;
5510 #ifndef _WIN32
5511 case QEMU_OPTION_chroot:
5512 chroot_dir = optarg;
5513 break;
5514 case QEMU_OPTION_runas:
5515 run_as = optarg;
5516 break;
5517 #endif
5518 #ifdef CONFIG_XEN
5519 case QEMU_OPTION_xen_domid:
5520 xen_domid = atoi(optarg);
5521 break;
5522 case QEMU_OPTION_xen_create:
5523 xen_mode = XEN_CREATE;
5524 break;
5525 case QEMU_OPTION_xen_attach:
5526 xen_mode = XEN_ATTACH;
5527 break;
5528 #endif
5529 case QEMU_OPTION_readconfig:
5531 FILE *fp;
5532 fp = fopen(optarg, "r");
5533 if (fp == NULL) {
5534 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5535 exit(1);
5537 if (qemu_config_parse(fp) != 0) {
5538 exit(1);
5540 fclose(fp);
5541 break;
5543 case QEMU_OPTION_writeconfig:
5545 FILE *fp;
5546 if (strcmp(optarg, "-") == 0) {
5547 fp = stdout;
5548 } else {
5549 fp = fopen(optarg, "w");
5550 if (fp == NULL) {
5551 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5552 exit(1);
5555 qemu_config_write(fp);
5556 fclose(fp);
5557 break;
5563 /* If no data_dir is specified then try to find it relative to the
5564 executable path. */
5565 if (!data_dir) {
5566 data_dir = find_datadir(argv[0]);
5568 /* If all else fails use the install patch specified when building. */
5569 if (!data_dir) {
5570 data_dir = CONFIG_QEMU_SHAREDIR;
5574 * Default to max_cpus = smp_cpus, in case the user doesn't
5575 * specify a max_cpus value.
5577 if (!max_cpus)
5578 max_cpus = smp_cpus;
5580 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5581 if (smp_cpus > machine->max_cpus) {
5582 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5583 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5584 machine->max_cpus);
5585 exit(1);
5588 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5589 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5591 if (machine->no_serial) {
5592 default_serial = 0;
5594 if (machine->no_parallel) {
5595 default_parallel = 0;
5597 if (!machine->use_virtcon) {
5598 default_virtcon = 0;
5600 if (machine->no_vga) {
5601 default_vga = 0;
5603 if (machine->no_floppy) {
5604 default_floppy = 0;
5606 if (machine->no_cdrom) {
5607 default_cdrom = 0;
5609 if (machine->no_sdcard) {
5610 default_sdcard = 0;
5613 if (display_type == DT_NOGRAPHIC) {
5614 if (default_parallel)
5615 add_device_config(DEV_PARALLEL, "null");
5616 if (default_serial && default_monitor) {
5617 add_device_config(DEV_SERIAL, "mon:stdio");
5618 } else if (default_virtcon && default_monitor) {
5619 add_device_config(DEV_VIRTCON, "mon:stdio");
5620 } else {
5621 if (default_serial)
5622 add_device_config(DEV_SERIAL, "stdio");
5623 if (default_virtcon)
5624 add_device_config(DEV_VIRTCON, "stdio");
5625 if (default_monitor)
5626 monitor_parse("stdio", "readline");
5628 } else {
5629 if (default_serial)
5630 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5631 if (default_parallel)
5632 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5633 if (default_monitor)
5634 monitor_parse("vc:80Cx24C", "readline");
5635 if (default_virtcon)
5636 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5638 if (default_vga)
5639 vga_interface_type = VGA_CIRRUS;
5641 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5642 exit(1);
5644 #ifndef _WIN32
5645 if (daemonize) {
5646 pid_t pid;
5648 if (pipe(fds) == -1)
5649 exit(1);
5651 pid = fork();
5652 if (pid > 0) {
5653 uint8_t status;
5654 ssize_t len;
5656 close(fds[1]);
5658 again:
5659 len = read(fds[0], &status, 1);
5660 if (len == -1 && (errno == EINTR))
5661 goto again;
5663 if (len != 1)
5664 exit(1);
5665 else if (status == 1) {
5666 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5667 exit(1);
5668 } else
5669 exit(0);
5670 } else if (pid < 0)
5671 exit(1);
5673 close(fds[0]);
5674 qemu_set_cloexec(fds[1]);
5676 setsid();
5678 pid = fork();
5679 if (pid > 0)
5680 exit(0);
5681 else if (pid < 0)
5682 exit(1);
5684 umask(027);
5686 signal(SIGTSTP, SIG_IGN);
5687 signal(SIGTTOU, SIG_IGN);
5688 signal(SIGTTIN, SIG_IGN);
5690 #endif
5692 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5693 #ifndef _WIN32
5694 if (daemonize) {
5695 uint8_t status = 1;
5696 if (write(fds[1], &status, 1) != 1) {
5697 perror("daemonize. Writing to pipe\n");
5699 } else
5700 #endif
5701 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5702 exit(1);
5705 if (kvm_enabled()) {
5706 int ret;
5708 ret = kvm_init(smp_cpus);
5709 if (ret < 0) {
5710 fprintf(stderr, "failed to initialize KVM\n");
5711 exit(1);
5715 if (qemu_init_main_loop()) {
5716 fprintf(stderr, "qemu_init_main_loop failed\n");
5717 exit(1);
5719 linux_boot = (kernel_filename != NULL);
5721 if (!linux_boot && *kernel_cmdline != '\0') {
5722 fprintf(stderr, "-append only allowed with -kernel option\n");
5723 exit(1);
5726 if (!linux_boot && initrd_filename != NULL) {
5727 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5728 exit(1);
5731 #ifndef _WIN32
5732 /* Win32 doesn't support line-buffering and requires size >= 2 */
5733 setvbuf(stdout, NULL, _IOLBF, 0);
5734 #endif
5736 if (init_timer_alarm() < 0) {
5737 fprintf(stderr, "could not initialize alarm timer\n");
5738 exit(1);
5740 if (use_icount && icount_time_shift < 0) {
5741 use_icount = 2;
5742 /* 125MIPS seems a reasonable initial guess at the guest speed.
5743 It will be corrected fairly quickly anyway. */
5744 icount_time_shift = 3;
5745 init_icount_adjust();
5748 #ifdef _WIN32
5749 socket_init();
5750 #endif
5752 if (net_init_clients() < 0) {
5753 exit(1);
5756 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5757 net_set_boot_mask(net_boot);
5759 /* init the bluetooth world */
5760 if (foreach_device_config(DEV_BT, bt_parse))
5761 exit(1);
5763 /* init the memory */
5764 if (ram_size == 0)
5765 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5767 /* init the dynamic translator */
5768 cpu_exec_init_all(tb_size * 1024 * 1024);
5770 bdrv_init_with_whitelist();
5772 blk_mig_init();
5774 if (default_cdrom) {
5775 /* we always create the cdrom drive, even if no disk is there */
5776 drive_add(NULL, CDROM_ALIAS);
5779 if (default_floppy) {
5780 /* we always create at least one floppy */
5781 drive_add(NULL, FD_ALIAS, 0);
5784 if (default_sdcard) {
5785 /* we always create one sd slot, even if no card is in it */
5786 drive_add(NULL, SD_ALIAS);
5789 /* open the virtual block devices */
5790 if (snapshot)
5791 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5792 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5793 exit(1);
5795 vmstate_register(0, &vmstate_timers ,&timers_state);
5796 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5797 ram_load, NULL);
5799 if (nb_numa_nodes > 0) {
5800 int i;
5802 if (nb_numa_nodes > smp_cpus) {
5803 nb_numa_nodes = smp_cpus;
5806 /* If no memory size if given for any node, assume the default case
5807 * and distribute the available memory equally across all nodes
5809 for (i = 0; i < nb_numa_nodes; i++) {
5810 if (node_mem[i] != 0)
5811 break;
5813 if (i == nb_numa_nodes) {
5814 uint64_t usedmem = 0;
5816 /* On Linux, the each node's border has to be 8MB aligned,
5817 * the final node gets the rest.
5819 for (i = 0; i < nb_numa_nodes - 1; i++) {
5820 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5821 usedmem += node_mem[i];
5823 node_mem[i] = ram_size - usedmem;
5826 for (i = 0; i < nb_numa_nodes; i++) {
5827 if (node_cpumask[i] != 0)
5828 break;
5830 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5831 * must cope with this anyway, because there are BIOSes out there in
5832 * real machines which also use this scheme.
5834 if (i == nb_numa_nodes) {
5835 for (i = 0; i < smp_cpus; i++) {
5836 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5841 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5842 exit(1);
5843 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5844 exit(1);
5845 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5846 exit(1);
5847 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5848 exit(1);
5850 module_call_init(MODULE_INIT_DEVICE);
5852 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
5853 exit(0);
5855 if (watchdog) {
5856 i = select_watchdog(watchdog);
5857 if (i > 0)
5858 exit (i == 1 ? 1 : 0);
5861 if (machine->compat_props) {
5862 qdev_prop_register_global_list(machine->compat_props);
5864 qemu_add_globals();
5866 machine->init(ram_size, boot_devices,
5867 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5870 #ifndef _WIN32
5871 /* must be after terminal init, SDL library changes signal handlers */
5872 sighandler_setup();
5873 #endif
5875 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5876 for (i = 0; i < nb_numa_nodes; i++) {
5877 if (node_cpumask[i] & (1 << env->cpu_index)) {
5878 env->numa_node = i;
5883 current_machine = machine;
5885 /* init USB devices */
5886 if (usb_enabled) {
5887 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5888 exit(1);
5891 /* init generic devices */
5892 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5893 exit(1);
5895 if (!display_state)
5896 dumb_display_init();
5897 /* just use the first displaystate for the moment */
5898 ds = display_state;
5900 if (display_type == DT_DEFAULT) {
5901 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5902 display_type = DT_SDL;
5903 #else
5904 display_type = DT_VNC;
5905 vnc_display = "localhost:0,to=99";
5906 show_vnc_port = 1;
5907 #endif
5911 switch (display_type) {
5912 case DT_NOGRAPHIC:
5913 break;
5914 #if defined(CONFIG_CURSES)
5915 case DT_CURSES:
5916 curses_display_init(ds, full_screen);
5917 break;
5918 #endif
5919 #if defined(CONFIG_SDL)
5920 case DT_SDL:
5921 sdl_display_init(ds, full_screen, no_frame);
5922 break;
5923 #elif defined(CONFIG_COCOA)
5924 case DT_SDL:
5925 cocoa_display_init(ds, full_screen);
5926 break;
5927 #endif
5928 case DT_VNC:
5929 vnc_display_init(ds);
5930 if (vnc_display_open(ds, vnc_display) < 0)
5931 exit(1);
5933 if (show_vnc_port) {
5934 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5936 break;
5937 default:
5938 break;
5940 dpy_resize(ds);
5942 dcl = ds->listeners;
5943 while (dcl != NULL) {
5944 if (dcl->dpy_refresh != NULL) {
5945 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5946 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5948 dcl = dcl->next;
5951 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5952 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5953 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5956 text_consoles_set_display(display_state);
5958 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
5959 exit(1);
5961 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5962 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5963 gdbstub_dev);
5964 exit(1);
5967 qdev_machine_creation_done();
5969 if (rom_load_all() != 0) {
5970 fprintf(stderr, "rom loading failed\n");
5971 exit(1);
5974 qemu_system_reset();
5975 if (loadvm) {
5976 if (load_vmstate(cur_mon, loadvm) < 0) {
5977 autostart = 0;
5981 if (incoming) {
5982 qemu_start_incoming_migration(incoming);
5983 } else if (autostart) {
5984 vm_start();
5987 #ifndef _WIN32
5988 if (daemonize) {
5989 uint8_t status = 0;
5990 ssize_t len;
5992 again1:
5993 len = write(fds[1], &status, 1);
5994 if (len == -1 && (errno == EINTR))
5995 goto again1;
5997 if (len != 1)
5998 exit(1);
6000 if (chdir("/")) {
6001 perror("not able to chdir to /");
6002 exit(1);
6004 TFR(fd = qemu_open("/dev/null", O_RDWR));
6005 if (fd == -1)
6006 exit(1);
6009 if (run_as) {
6010 pwd = getpwnam(run_as);
6011 if (!pwd) {
6012 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6013 exit(1);
6017 if (chroot_dir) {
6018 if (chroot(chroot_dir) < 0) {
6019 fprintf(stderr, "chroot failed\n");
6020 exit(1);
6022 if (chdir("/")) {
6023 perror("not able to chdir to /");
6024 exit(1);
6028 if (run_as) {
6029 if (setgid(pwd->pw_gid) < 0) {
6030 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6031 exit(1);
6033 if (setuid(pwd->pw_uid) < 0) {
6034 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6035 exit(1);
6037 if (setuid(0) != -1) {
6038 fprintf(stderr, "Dropping privileges failed\n");
6039 exit(1);
6043 if (daemonize) {
6044 dup2(fd, 0);
6045 dup2(fd, 1);
6046 dup2(fd, 2);
6048 close(fd);
6050 #endif
6052 main_loop();
6053 quit_timers();
6054 net_cleanup();
6056 return 0;