eepro100: Add missing SCB register names
[qemu.git] / vl.c
blobdb7a178f88c33b193aa2c0b3a53901d22c6bbb30
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 DisplayType display_type = DT_DEFAULT;
186 const char* keyboard_layout = NULL;
187 ram_addr_t ram_size;
188 int nb_nics;
189 NICInfo nd_table[MAX_NICS];
190 int vm_running;
191 int autostart;
192 static int rtc_utc = 1;
193 static int rtc_date_offset = -1; /* -1 means no change */
194 QEMUClock *rtc_clock;
195 int vga_interface_type = VGA_NONE;
196 #ifdef TARGET_SPARC
197 int graphic_width = 1024;
198 int graphic_height = 768;
199 int graphic_depth = 8;
200 #else
201 int graphic_width = 800;
202 int graphic_height = 600;
203 int graphic_depth = 15;
204 #endif
205 static int full_screen = 0;
206 #ifdef CONFIG_SDL
207 static int no_frame = 0;
208 #endif
209 int no_quit = 0;
210 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
211 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
212 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
213 #ifdef TARGET_I386
214 int win2k_install_hack = 0;
215 int rtc_td_hack = 0;
216 #endif
217 int usb_enabled = 0;
218 int singlestep = 0;
219 int smp_cpus = 1;
220 int max_cpus = 0;
221 int smp_cores = 1;
222 int smp_threads = 1;
223 const char *vnc_display;
224 int acpi_enabled = 1;
225 int no_hpet = 0;
226 int fd_bootchk = 1;
227 int no_reboot = 0;
228 int no_shutdown = 0;
229 int cursor_hide = 1;
230 int graphic_rotate = 0;
231 uint8_t irq0override = 1;
232 #ifndef _WIN32
233 int daemonize = 0;
234 #endif
235 const char *watchdog;
236 const char *option_rom[MAX_OPTION_ROMS];
237 int nb_option_roms;
238 int semihosting_enabled = 0;
239 #ifdef TARGET_ARM
240 int old_param = 0;
241 #endif
242 const char *qemu_name;
243 int alt_grab = 0;
244 int ctrl_grab = 0;
245 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
246 unsigned int nb_prom_envs = 0;
247 const char *prom_envs[MAX_PROM_ENVS];
248 #endif
249 int boot_menu;
251 int nb_numa_nodes;
252 uint64_t node_mem[MAX_NODES];
253 uint64_t node_cpumask[MAX_NODES];
255 static CPUState *cur_cpu;
256 static CPUState *next_cpu;
257 static int timer_alarm_pending = 1;
258 /* Conversion factor from emulated instructions to virtual clock ticks. */
259 static int icount_time_shift;
260 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
261 #define MAX_ICOUNT_SHIFT 10
262 /* Compensate for varying guest execution speed. */
263 static int64_t qemu_icount_bias;
264 static QEMUTimer *icount_rt_timer;
265 static QEMUTimer *icount_vm_timer;
266 static QEMUTimer *nographic_timer;
268 uint8_t qemu_uuid[16];
270 static QEMUBootSetHandler *boot_set_handler;
271 static void *boot_set_opaque;
273 #ifdef SIGRTMIN
274 #define SIG_IPI (SIGRTMIN+4)
275 #else
276 #define SIG_IPI SIGUSR1
277 #endif
279 static int default_serial = 1;
280 static int default_parallel = 1;
281 static int default_virtcon = 1;
282 static int default_monitor = 1;
283 static int default_vga = 1;
284 static int default_floppy = 1;
285 static int default_cdrom = 1;
286 static int default_sdcard = 1;
288 static struct {
289 const char *driver;
290 int *flag;
291 } default_list[] = {
292 { .driver = "isa-serial", .flag = &default_serial },
293 { .driver = "isa-parallel", .flag = &default_parallel },
294 { .driver = "isa-fdc", .flag = &default_floppy },
295 { .driver = "ide-drive", .flag = &default_cdrom },
296 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
297 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
298 { .driver = "virtio-serial", .flag = &default_virtcon },
299 { .driver = "VGA", .flag = &default_vga },
300 { .driver = "cirrus-vga", .flag = &default_vga },
301 { .driver = "vmware-svga", .flag = &default_vga },
304 static int default_driver_check(QemuOpts *opts, void *opaque)
306 const char *driver = qemu_opt_get(opts, "driver");
307 int i;
309 if (!driver)
310 return 0;
311 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
312 if (strcmp(default_list[i].driver, driver) != 0)
313 continue;
314 *(default_list[i].flag) = 0;
316 return 0;
319 /***********************************************************/
320 /* x86 ISA bus support */
322 target_phys_addr_t isa_mem_base = 0;
323 PicState2 *isa_pic;
325 /***********************************************************/
326 void hw_error(const char *fmt, ...)
328 va_list ap;
329 CPUState *env;
331 va_start(ap, fmt);
332 fprintf(stderr, "qemu: hardware error: ");
333 vfprintf(stderr, fmt, ap);
334 fprintf(stderr, "\n");
335 for(env = first_cpu; env != NULL; env = env->next_cpu) {
336 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
337 #ifdef TARGET_I386
338 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
339 #else
340 cpu_dump_state(env, stderr, fprintf, 0);
341 #endif
343 va_end(ap);
344 abort();
347 static void set_proc_name(const char *s)
349 #if defined(__linux__) && defined(PR_SET_NAME)
350 char name[16];
351 if (!s)
352 return;
353 name[sizeof(name) - 1] = 0;
354 strncpy(name, s, sizeof(name));
355 /* Could rewrite argv[0] too, but that's a bit more complicated.
356 This simple way is enough for `top'. */
357 prctl(PR_SET_NAME, name);
358 #endif
361 /***************/
362 /* ballooning */
364 static QEMUBalloonEvent *qemu_balloon_event;
365 void *qemu_balloon_event_opaque;
367 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
369 qemu_balloon_event = func;
370 qemu_balloon_event_opaque = opaque;
373 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
375 if (qemu_balloon_event) {
376 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
377 return 1;
378 } else {
379 return 0;
383 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
385 if (qemu_balloon_event) {
386 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
387 return 1;
388 } else {
389 return 0;
394 /***********************************************************/
395 /* real time host monotonic timer */
397 /* compute with 96 bit intermediate result: (a*b)/c */
398 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
400 union {
401 uint64_t ll;
402 struct {
403 #ifdef HOST_WORDS_BIGENDIAN
404 uint32_t high, low;
405 #else
406 uint32_t low, high;
407 #endif
408 } l;
409 } u, res;
410 uint64_t rl, rh;
412 u.ll = a;
413 rl = (uint64_t)u.l.low * (uint64_t)b;
414 rh = (uint64_t)u.l.high * (uint64_t)b;
415 rh += (rl >> 32);
416 res.l.high = rh / c;
417 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
418 return res.ll;
421 static int64_t get_clock_realtime(void)
423 struct timeval tv;
425 gettimeofday(&tv, NULL);
426 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
429 #ifdef WIN32
431 static int64_t clock_freq;
433 static void init_get_clock(void)
435 LARGE_INTEGER freq;
436 int ret;
437 ret = QueryPerformanceFrequency(&freq);
438 if (ret == 0) {
439 fprintf(stderr, "Could not calibrate ticks\n");
440 exit(1);
442 clock_freq = freq.QuadPart;
445 static int64_t get_clock(void)
447 LARGE_INTEGER ti;
448 QueryPerformanceCounter(&ti);
449 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
452 #else
454 static int use_rt_clock;
456 static void init_get_clock(void)
458 use_rt_clock = 0;
459 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
460 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
462 struct timespec ts;
463 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
464 use_rt_clock = 1;
467 #endif
470 static int64_t get_clock(void)
472 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
473 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
474 if (use_rt_clock) {
475 struct timespec ts;
476 clock_gettime(CLOCK_MONOTONIC, &ts);
477 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
478 } else
479 #endif
481 /* XXX: using gettimeofday leads to problems if the date
482 changes, so it should be avoided. */
483 return get_clock_realtime();
486 #endif
488 /* Return the virtual CPU time, based on the instruction counter. */
489 static int64_t cpu_get_icount(void)
491 int64_t icount;
492 CPUState *env = cpu_single_env;;
493 icount = qemu_icount;
494 if (env) {
495 if (!can_do_io(env))
496 fprintf(stderr, "Bad clock read\n");
497 icount -= (env->icount_decr.u16.low + env->icount_extra);
499 return qemu_icount_bias + (icount << icount_time_shift);
502 /***********************************************************/
503 /* guest cycle counter */
505 typedef struct TimersState {
506 int64_t cpu_ticks_prev;
507 int64_t cpu_ticks_offset;
508 int64_t cpu_clock_offset;
509 int32_t cpu_ticks_enabled;
510 int64_t dummy;
511 } TimersState;
513 TimersState timers_state;
515 /* return the host CPU cycle counter and handle stop/restart */
516 int64_t cpu_get_ticks(void)
518 if (use_icount) {
519 return cpu_get_icount();
521 if (!timers_state.cpu_ticks_enabled) {
522 return timers_state.cpu_ticks_offset;
523 } else {
524 int64_t ticks;
525 ticks = cpu_get_real_ticks();
526 if (timers_state.cpu_ticks_prev > ticks) {
527 /* Note: non increasing ticks may happen if the host uses
528 software suspend */
529 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
531 timers_state.cpu_ticks_prev = ticks;
532 return ticks + timers_state.cpu_ticks_offset;
536 /* return the host CPU monotonic timer and handle stop/restart */
537 static int64_t cpu_get_clock(void)
539 int64_t ti;
540 if (!timers_state.cpu_ticks_enabled) {
541 return timers_state.cpu_clock_offset;
542 } else {
543 ti = get_clock();
544 return ti + timers_state.cpu_clock_offset;
548 /* enable cpu_get_ticks() */
549 void cpu_enable_ticks(void)
551 if (!timers_state.cpu_ticks_enabled) {
552 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
553 timers_state.cpu_clock_offset -= get_clock();
554 timers_state.cpu_ticks_enabled = 1;
558 /* disable cpu_get_ticks() : the clock is stopped. You must not call
559 cpu_get_ticks() after that. */
560 void cpu_disable_ticks(void)
562 if (timers_state.cpu_ticks_enabled) {
563 timers_state.cpu_ticks_offset = cpu_get_ticks();
564 timers_state.cpu_clock_offset = cpu_get_clock();
565 timers_state.cpu_ticks_enabled = 0;
569 /***********************************************************/
570 /* timers */
572 #define QEMU_CLOCK_REALTIME 0
573 #define QEMU_CLOCK_VIRTUAL 1
574 #define QEMU_CLOCK_HOST 2
576 struct QEMUClock {
577 int type;
578 /* XXX: add frequency */
581 struct QEMUTimer {
582 QEMUClock *clock;
583 int64_t expire_time;
584 QEMUTimerCB *cb;
585 void *opaque;
586 struct QEMUTimer *next;
589 struct qemu_alarm_timer {
590 char const *name;
591 unsigned int flags;
593 int (*start)(struct qemu_alarm_timer *t);
594 void (*stop)(struct qemu_alarm_timer *t);
595 void (*rearm)(struct qemu_alarm_timer *t);
596 void *priv;
599 #define ALARM_FLAG_DYNTICKS 0x1
600 #define ALARM_FLAG_EXPIRED 0x2
602 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
604 return t && (t->flags & ALARM_FLAG_DYNTICKS);
607 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
609 if (!alarm_has_dynticks(t))
610 return;
612 t->rearm(t);
615 /* TODO: MIN_TIMER_REARM_US should be optimized */
616 #define MIN_TIMER_REARM_US 250
618 static struct qemu_alarm_timer *alarm_timer;
620 #ifdef _WIN32
622 struct qemu_alarm_win32 {
623 MMRESULT timerId;
624 unsigned int period;
625 } alarm_win32_data = {0, -1};
627 static int win32_start_timer(struct qemu_alarm_timer *t);
628 static void win32_stop_timer(struct qemu_alarm_timer *t);
629 static void win32_rearm_timer(struct qemu_alarm_timer *t);
631 #else
633 static int unix_start_timer(struct qemu_alarm_timer *t);
634 static void unix_stop_timer(struct qemu_alarm_timer *t);
636 #ifdef __linux__
638 static int dynticks_start_timer(struct qemu_alarm_timer *t);
639 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
640 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
642 static int hpet_start_timer(struct qemu_alarm_timer *t);
643 static void hpet_stop_timer(struct qemu_alarm_timer *t);
645 static int rtc_start_timer(struct qemu_alarm_timer *t);
646 static void rtc_stop_timer(struct qemu_alarm_timer *t);
648 #endif /* __linux__ */
650 #endif /* _WIN32 */
652 /* Correlation between real and virtual time is always going to be
653 fairly approximate, so ignore small variation.
654 When the guest is idle real and virtual time will be aligned in
655 the IO wait loop. */
656 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
658 static void icount_adjust(void)
660 int64_t cur_time;
661 int64_t cur_icount;
662 int64_t delta;
663 static int64_t last_delta;
664 /* If the VM is not running, then do nothing. */
665 if (!vm_running)
666 return;
668 cur_time = cpu_get_clock();
669 cur_icount = qemu_get_clock(vm_clock);
670 delta = cur_icount - cur_time;
671 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
672 if (delta > 0
673 && last_delta + ICOUNT_WOBBLE < delta * 2
674 && icount_time_shift > 0) {
675 /* The guest is getting too far ahead. Slow time down. */
676 icount_time_shift--;
678 if (delta < 0
679 && last_delta - ICOUNT_WOBBLE > delta * 2
680 && icount_time_shift < MAX_ICOUNT_SHIFT) {
681 /* The guest is getting too far behind. Speed time up. */
682 icount_time_shift++;
684 last_delta = delta;
685 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
688 static void icount_adjust_rt(void * opaque)
690 qemu_mod_timer(icount_rt_timer,
691 qemu_get_clock(rt_clock) + 1000);
692 icount_adjust();
695 static void icount_adjust_vm(void * opaque)
697 qemu_mod_timer(icount_vm_timer,
698 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
699 icount_adjust();
702 static void init_icount_adjust(void)
704 /* Have both realtime and virtual time triggers for speed adjustment.
705 The realtime trigger catches emulated time passing too slowly,
706 the virtual time trigger catches emulated time passing too fast.
707 Realtime triggers occur even when idle, so use them less frequently
708 than VM triggers. */
709 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
710 qemu_mod_timer(icount_rt_timer,
711 qemu_get_clock(rt_clock) + 1000);
712 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
713 qemu_mod_timer(icount_vm_timer,
714 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
717 static struct qemu_alarm_timer alarm_timers[] = {
718 #ifndef _WIN32
719 #ifdef __linux__
720 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
721 dynticks_stop_timer, dynticks_rearm_timer, NULL},
722 /* HPET - if available - is preferred */
723 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
724 /* ...otherwise try RTC */
725 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
726 #endif
727 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
728 #else
729 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
730 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
731 {"win32", 0, win32_start_timer,
732 win32_stop_timer, NULL, &alarm_win32_data},
733 #endif
734 {NULL, }
737 static void show_available_alarms(void)
739 int i;
741 printf("Available alarm timers, in order of precedence:\n");
742 for (i = 0; alarm_timers[i].name; i++)
743 printf("%s\n", alarm_timers[i].name);
746 static void configure_alarms(char const *opt)
748 int i;
749 int cur = 0;
750 int count = ARRAY_SIZE(alarm_timers) - 1;
751 char *arg;
752 char *name;
753 struct qemu_alarm_timer tmp;
755 if (!strcmp(opt, "?")) {
756 show_available_alarms();
757 exit(0);
760 arg = qemu_strdup(opt);
762 /* Reorder the array */
763 name = strtok(arg, ",");
764 while (name) {
765 for (i = 0; i < count && alarm_timers[i].name; i++) {
766 if (!strcmp(alarm_timers[i].name, name))
767 break;
770 if (i == count) {
771 fprintf(stderr, "Unknown clock %s\n", name);
772 goto next;
775 if (i < cur)
776 /* Ignore */
777 goto next;
779 /* Swap */
780 tmp = alarm_timers[i];
781 alarm_timers[i] = alarm_timers[cur];
782 alarm_timers[cur] = tmp;
784 cur++;
785 next:
786 name = strtok(NULL, ",");
789 qemu_free(arg);
791 if (cur) {
792 /* Disable remaining timers */
793 for (i = cur; i < count; i++)
794 alarm_timers[i].name = NULL;
795 } else {
796 show_available_alarms();
797 exit(1);
801 #define QEMU_NUM_CLOCKS 3
803 QEMUClock *rt_clock;
804 QEMUClock *vm_clock;
805 QEMUClock *host_clock;
807 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
809 static QEMUClock *qemu_new_clock(int type)
811 QEMUClock *clock;
812 clock = qemu_mallocz(sizeof(QEMUClock));
813 clock->type = type;
814 return clock;
817 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
819 QEMUTimer *ts;
821 ts = qemu_mallocz(sizeof(QEMUTimer));
822 ts->clock = clock;
823 ts->cb = cb;
824 ts->opaque = opaque;
825 return ts;
828 void qemu_free_timer(QEMUTimer *ts)
830 qemu_free(ts);
833 /* stop a timer, but do not dealloc it */
834 void qemu_del_timer(QEMUTimer *ts)
836 QEMUTimer **pt, *t;
838 /* NOTE: this code must be signal safe because
839 qemu_timer_expired() can be called from a signal. */
840 pt = &active_timers[ts->clock->type];
841 for(;;) {
842 t = *pt;
843 if (!t)
844 break;
845 if (t == ts) {
846 *pt = t->next;
847 break;
849 pt = &t->next;
853 /* modify the current timer so that it will be fired when current_time
854 >= expire_time. The corresponding callback will be called. */
855 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
857 QEMUTimer **pt, *t;
859 qemu_del_timer(ts);
861 /* add the timer in the sorted list */
862 /* NOTE: this code must be signal safe because
863 qemu_timer_expired() can be called from a signal. */
864 pt = &active_timers[ts->clock->type];
865 for(;;) {
866 t = *pt;
867 if (!t)
868 break;
869 if (t->expire_time > expire_time)
870 break;
871 pt = &t->next;
873 ts->expire_time = expire_time;
874 ts->next = *pt;
875 *pt = ts;
877 /* Rearm if necessary */
878 if (pt == &active_timers[ts->clock->type]) {
879 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
880 qemu_rearm_alarm_timer(alarm_timer);
882 /* Interrupt execution to force deadline recalculation. */
883 if (use_icount)
884 qemu_notify_event();
888 int qemu_timer_pending(QEMUTimer *ts)
890 QEMUTimer *t;
891 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
892 if (t == ts)
893 return 1;
895 return 0;
898 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
900 if (!timer_head)
901 return 0;
902 return (timer_head->expire_time <= current_time);
905 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
907 QEMUTimer *ts;
909 for(;;) {
910 ts = *ptimer_head;
911 if (!ts || ts->expire_time > current_time)
912 break;
913 /* remove timer from the list before calling the callback */
914 *ptimer_head = ts->next;
915 ts->next = NULL;
917 /* run the callback (the timer list can be modified) */
918 ts->cb(ts->opaque);
922 int64_t qemu_get_clock(QEMUClock *clock)
924 switch(clock->type) {
925 case QEMU_CLOCK_REALTIME:
926 return get_clock() / 1000000;
927 default:
928 case QEMU_CLOCK_VIRTUAL:
929 if (use_icount) {
930 return cpu_get_icount();
931 } else {
932 return cpu_get_clock();
934 case QEMU_CLOCK_HOST:
935 return get_clock_realtime();
939 int64_t qemu_get_clock_ns(QEMUClock *clock)
941 switch(clock->type) {
942 case QEMU_CLOCK_REALTIME:
943 return get_clock();
944 default:
945 case QEMU_CLOCK_VIRTUAL:
946 if (use_icount) {
947 return cpu_get_icount();
948 } else {
949 return cpu_get_clock();
951 case QEMU_CLOCK_HOST:
952 return get_clock_realtime();
956 static void init_clocks(void)
958 init_get_clock();
959 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
960 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
961 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
963 rtc_clock = host_clock;
966 /* save a timer */
967 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
969 uint64_t expire_time;
971 if (qemu_timer_pending(ts)) {
972 expire_time = ts->expire_time;
973 } else {
974 expire_time = -1;
976 qemu_put_be64(f, expire_time);
979 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
981 uint64_t expire_time;
983 expire_time = qemu_get_be64(f);
984 if (expire_time != -1) {
985 qemu_mod_timer(ts, expire_time);
986 } else {
987 qemu_del_timer(ts);
991 static const VMStateDescription vmstate_timers = {
992 .name = "timer",
993 .version_id = 2,
994 .minimum_version_id = 1,
995 .minimum_version_id_old = 1,
996 .fields = (VMStateField []) {
997 VMSTATE_INT64(cpu_ticks_offset, TimersState),
998 VMSTATE_INT64(dummy, TimersState),
999 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1000 VMSTATE_END_OF_LIST()
1004 static void qemu_event_increment(void);
1006 #ifdef _WIN32
1007 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1008 DWORD_PTR dwUser, DWORD_PTR dw1,
1009 DWORD_PTR dw2)
1010 #else
1011 static void host_alarm_handler(int host_signum)
1012 #endif
1014 #if 0
1015 #define DISP_FREQ 1000
1017 static int64_t delta_min = INT64_MAX;
1018 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1019 static int count;
1020 ti = qemu_get_clock(vm_clock);
1021 if (last_clock != 0) {
1022 delta = ti - last_clock;
1023 if (delta < delta_min)
1024 delta_min = delta;
1025 if (delta > delta_max)
1026 delta_max = delta;
1027 delta_cum += delta;
1028 if (++count == DISP_FREQ) {
1029 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1030 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1031 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1032 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1033 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1034 count = 0;
1035 delta_min = INT64_MAX;
1036 delta_max = 0;
1037 delta_cum = 0;
1040 last_clock = ti;
1042 #endif
1043 if (alarm_has_dynticks(alarm_timer) ||
1044 (!use_icount &&
1045 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1046 qemu_get_clock(vm_clock))) ||
1047 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1048 qemu_get_clock(rt_clock)) ||
1049 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1050 qemu_get_clock(host_clock))) {
1051 qemu_event_increment();
1052 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1054 #ifndef CONFIG_IOTHREAD
1055 if (next_cpu) {
1056 /* stop the currently executing cpu because a timer occured */
1057 cpu_exit(next_cpu);
1059 #endif
1060 timer_alarm_pending = 1;
1061 qemu_notify_event();
1065 static int64_t qemu_next_deadline(void)
1067 /* To avoid problems with overflow limit this to 2^32. */
1068 int64_t delta = INT32_MAX;
1070 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1071 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1072 qemu_get_clock(vm_clock);
1074 if (active_timers[QEMU_CLOCK_HOST]) {
1075 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1076 qemu_get_clock(host_clock);
1077 if (hdelta < delta)
1078 delta = hdelta;
1081 if (delta < 0)
1082 delta = 0;
1084 return delta;
1087 #if defined(__linux__)
1088 static uint64_t qemu_next_deadline_dyntick(void)
1090 int64_t delta;
1091 int64_t rtdelta;
1093 if (use_icount)
1094 delta = INT32_MAX;
1095 else
1096 delta = (qemu_next_deadline() + 999) / 1000;
1098 if (active_timers[QEMU_CLOCK_REALTIME]) {
1099 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1100 qemu_get_clock(rt_clock))*1000;
1101 if (rtdelta < delta)
1102 delta = rtdelta;
1105 if (delta < MIN_TIMER_REARM_US)
1106 delta = MIN_TIMER_REARM_US;
1108 return delta;
1110 #endif
1112 #ifndef _WIN32
1114 /* Sets a specific flag */
1115 static int fcntl_setfl(int fd, int flag)
1117 int flags;
1119 flags = fcntl(fd, F_GETFL);
1120 if (flags == -1)
1121 return -errno;
1123 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1124 return -errno;
1126 return 0;
1129 #if defined(__linux__)
1131 #define RTC_FREQ 1024
1133 static void enable_sigio_timer(int fd)
1135 struct sigaction act;
1137 /* timer signal */
1138 sigfillset(&act.sa_mask);
1139 act.sa_flags = 0;
1140 act.sa_handler = host_alarm_handler;
1142 sigaction(SIGIO, &act, NULL);
1143 fcntl_setfl(fd, O_ASYNC);
1144 fcntl(fd, F_SETOWN, getpid());
1147 static int hpet_start_timer(struct qemu_alarm_timer *t)
1149 struct hpet_info info;
1150 int r, fd;
1152 fd = qemu_open("/dev/hpet", O_RDONLY);
1153 if (fd < 0)
1154 return -1;
1156 /* Set frequency */
1157 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1158 if (r < 0) {
1159 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1160 "error, but for better emulation accuracy type:\n"
1161 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1162 goto fail;
1165 /* Check capabilities */
1166 r = ioctl(fd, HPET_INFO, &info);
1167 if (r < 0)
1168 goto fail;
1170 /* Enable periodic mode */
1171 r = ioctl(fd, HPET_EPI, 0);
1172 if (info.hi_flags && (r < 0))
1173 goto fail;
1175 /* Enable interrupt */
1176 r = ioctl(fd, HPET_IE_ON, 0);
1177 if (r < 0)
1178 goto fail;
1180 enable_sigio_timer(fd);
1181 t->priv = (void *)(long)fd;
1183 return 0;
1184 fail:
1185 close(fd);
1186 return -1;
1189 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1191 int fd = (long)t->priv;
1193 close(fd);
1196 static int rtc_start_timer(struct qemu_alarm_timer *t)
1198 int rtc_fd;
1199 unsigned long current_rtc_freq = 0;
1201 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1202 if (rtc_fd < 0)
1203 return -1;
1204 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1205 if (current_rtc_freq != RTC_FREQ &&
1206 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1207 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1208 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1209 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1210 goto fail;
1212 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1213 fail:
1214 close(rtc_fd);
1215 return -1;
1218 enable_sigio_timer(rtc_fd);
1220 t->priv = (void *)(long)rtc_fd;
1222 return 0;
1225 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1227 int rtc_fd = (long)t->priv;
1229 close(rtc_fd);
1232 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1234 struct sigevent ev;
1235 timer_t host_timer;
1236 struct sigaction act;
1238 sigfillset(&act.sa_mask);
1239 act.sa_flags = 0;
1240 act.sa_handler = host_alarm_handler;
1242 sigaction(SIGALRM, &act, NULL);
1245 * Initialize ev struct to 0 to avoid valgrind complaining
1246 * about uninitialized data in timer_create call
1248 memset(&ev, 0, sizeof(ev));
1249 ev.sigev_value.sival_int = 0;
1250 ev.sigev_notify = SIGEV_SIGNAL;
1251 ev.sigev_signo = SIGALRM;
1253 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1254 perror("timer_create");
1256 /* disable dynticks */
1257 fprintf(stderr, "Dynamic Ticks disabled\n");
1259 return -1;
1262 t->priv = (void *)(long)host_timer;
1264 return 0;
1267 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1269 timer_t host_timer = (timer_t)(long)t->priv;
1271 timer_delete(host_timer);
1274 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1276 timer_t host_timer = (timer_t)(long)t->priv;
1277 struct itimerspec timeout;
1278 int64_t nearest_delta_us = INT64_MAX;
1279 int64_t current_us;
1281 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1282 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1283 !active_timers[QEMU_CLOCK_HOST])
1284 return;
1286 nearest_delta_us = qemu_next_deadline_dyntick();
1288 /* check whether a timer is already running */
1289 if (timer_gettime(host_timer, &timeout)) {
1290 perror("gettime");
1291 fprintf(stderr, "Internal timer error: aborting\n");
1292 exit(1);
1294 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1295 if (current_us && current_us <= nearest_delta_us)
1296 return;
1298 timeout.it_interval.tv_sec = 0;
1299 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1300 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1301 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1302 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1303 perror("settime");
1304 fprintf(stderr, "Internal timer error: aborting\n");
1305 exit(1);
1309 #endif /* defined(__linux__) */
1311 static int unix_start_timer(struct qemu_alarm_timer *t)
1313 struct sigaction act;
1314 struct itimerval itv;
1315 int err;
1317 /* timer signal */
1318 sigfillset(&act.sa_mask);
1319 act.sa_flags = 0;
1320 act.sa_handler = host_alarm_handler;
1322 sigaction(SIGALRM, &act, NULL);
1324 itv.it_interval.tv_sec = 0;
1325 /* for i386 kernel 2.6 to get 1 ms */
1326 itv.it_interval.tv_usec = 999;
1327 itv.it_value.tv_sec = 0;
1328 itv.it_value.tv_usec = 10 * 1000;
1330 err = setitimer(ITIMER_REAL, &itv, NULL);
1331 if (err)
1332 return -1;
1334 return 0;
1337 static void unix_stop_timer(struct qemu_alarm_timer *t)
1339 struct itimerval itv;
1341 memset(&itv, 0, sizeof(itv));
1342 setitimer(ITIMER_REAL, &itv, NULL);
1345 #endif /* !defined(_WIN32) */
1348 #ifdef _WIN32
1350 static int win32_start_timer(struct qemu_alarm_timer *t)
1352 TIMECAPS tc;
1353 struct qemu_alarm_win32 *data = t->priv;
1354 UINT flags;
1356 memset(&tc, 0, sizeof(tc));
1357 timeGetDevCaps(&tc, sizeof(tc));
1359 if (data->period < tc.wPeriodMin)
1360 data->period = tc.wPeriodMin;
1362 timeBeginPeriod(data->period);
1364 flags = TIME_CALLBACK_FUNCTION;
1365 if (alarm_has_dynticks(t))
1366 flags |= TIME_ONESHOT;
1367 else
1368 flags |= TIME_PERIODIC;
1370 data->timerId = timeSetEvent(1, // interval (ms)
1371 data->period, // resolution
1372 host_alarm_handler, // function
1373 (DWORD)t, // parameter
1374 flags);
1376 if (!data->timerId) {
1377 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1378 GetLastError());
1379 timeEndPeriod(data->period);
1380 return -1;
1383 return 0;
1386 static void win32_stop_timer(struct qemu_alarm_timer *t)
1388 struct qemu_alarm_win32 *data = t->priv;
1390 timeKillEvent(data->timerId);
1391 timeEndPeriod(data->period);
1394 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1396 struct qemu_alarm_win32 *data = t->priv;
1398 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1399 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1400 !active_timers[QEMU_CLOCK_HOST])
1401 return;
1403 timeKillEvent(data->timerId);
1405 data->timerId = timeSetEvent(1,
1406 data->period,
1407 host_alarm_handler,
1408 (DWORD)t,
1409 TIME_ONESHOT | TIME_PERIODIC);
1411 if (!data->timerId) {
1412 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1413 GetLastError());
1415 timeEndPeriod(data->period);
1416 exit(1);
1420 #endif /* _WIN32 */
1422 static int init_timer_alarm(void)
1424 struct qemu_alarm_timer *t = NULL;
1425 int i, err = -1;
1427 for (i = 0; alarm_timers[i].name; i++) {
1428 t = &alarm_timers[i];
1430 err = t->start(t);
1431 if (!err)
1432 break;
1435 if (err) {
1436 err = -ENOENT;
1437 goto fail;
1440 alarm_timer = t;
1442 return 0;
1444 fail:
1445 return err;
1448 static void quit_timers(void)
1450 alarm_timer->stop(alarm_timer);
1451 alarm_timer = NULL;
1454 /***********************************************************/
1455 /* host time/date access */
1456 void qemu_get_timedate(struct tm *tm, int offset)
1458 time_t ti;
1459 struct tm *ret;
1461 time(&ti);
1462 ti += offset;
1463 if (rtc_date_offset == -1) {
1464 if (rtc_utc)
1465 ret = gmtime(&ti);
1466 else
1467 ret = localtime(&ti);
1468 } else {
1469 ti -= rtc_date_offset;
1470 ret = gmtime(&ti);
1473 memcpy(tm, ret, sizeof(struct tm));
1476 int qemu_timedate_diff(struct tm *tm)
1478 time_t seconds;
1480 if (rtc_date_offset == -1)
1481 if (rtc_utc)
1482 seconds = mktimegm(tm);
1483 else
1484 seconds = mktime(tm);
1485 else
1486 seconds = mktimegm(tm) + rtc_date_offset;
1488 return seconds - time(NULL);
1491 static void configure_rtc_date_offset(const char *startdate, int legacy)
1493 time_t rtc_start_date;
1494 struct tm tm;
1496 if (!strcmp(startdate, "now") && legacy) {
1497 rtc_date_offset = -1;
1498 } else {
1499 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1500 &tm.tm_year,
1501 &tm.tm_mon,
1502 &tm.tm_mday,
1503 &tm.tm_hour,
1504 &tm.tm_min,
1505 &tm.tm_sec) == 6) {
1506 /* OK */
1507 } else if (sscanf(startdate, "%d-%d-%d",
1508 &tm.tm_year,
1509 &tm.tm_mon,
1510 &tm.tm_mday) == 3) {
1511 tm.tm_hour = 0;
1512 tm.tm_min = 0;
1513 tm.tm_sec = 0;
1514 } else {
1515 goto date_fail;
1517 tm.tm_year -= 1900;
1518 tm.tm_mon--;
1519 rtc_start_date = mktimegm(&tm);
1520 if (rtc_start_date == -1) {
1521 date_fail:
1522 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1523 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1524 exit(1);
1526 rtc_date_offset = time(NULL) - rtc_start_date;
1530 static void configure_rtc(QemuOpts *opts)
1532 const char *value;
1534 value = qemu_opt_get(opts, "base");
1535 if (value) {
1536 if (!strcmp(value, "utc")) {
1537 rtc_utc = 1;
1538 } else if (!strcmp(value, "localtime")) {
1539 rtc_utc = 0;
1540 } else {
1541 configure_rtc_date_offset(value, 0);
1544 value = qemu_opt_get(opts, "clock");
1545 if (value) {
1546 if (!strcmp(value, "host")) {
1547 rtc_clock = host_clock;
1548 } else if (!strcmp(value, "vm")) {
1549 rtc_clock = vm_clock;
1550 } else {
1551 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1552 exit(1);
1555 #ifdef CONFIG_TARGET_I386
1556 value = qemu_opt_get(opts, "driftfix");
1557 if (value) {
1558 if (!strcmp(buf, "slew")) {
1559 rtc_td_hack = 1;
1560 } else if (!strcmp(buf, "none")) {
1561 rtc_td_hack = 0;
1562 } else {
1563 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1564 exit(1);
1567 #endif
1570 #ifdef _WIN32
1571 static void socket_cleanup(void)
1573 WSACleanup();
1576 static int socket_init(void)
1578 WSADATA Data;
1579 int ret, err;
1581 ret = WSAStartup(MAKEWORD(2,2), &Data);
1582 if (ret != 0) {
1583 err = WSAGetLastError();
1584 fprintf(stderr, "WSAStartup: %d\n", err);
1585 return -1;
1587 atexit(socket_cleanup);
1588 return 0;
1590 #endif
1592 /***********************************************************/
1593 /* Bluetooth support */
1594 static int nb_hcis;
1595 static int cur_hci;
1596 static struct HCIInfo *hci_table[MAX_NICS];
1598 static struct bt_vlan_s {
1599 struct bt_scatternet_s net;
1600 int id;
1601 struct bt_vlan_s *next;
1602 } *first_bt_vlan;
1604 /* find or alloc a new bluetooth "VLAN" */
1605 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1607 struct bt_vlan_s **pvlan, *vlan;
1608 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1609 if (vlan->id == id)
1610 return &vlan->net;
1612 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1613 vlan->id = id;
1614 pvlan = &first_bt_vlan;
1615 while (*pvlan != NULL)
1616 pvlan = &(*pvlan)->next;
1617 *pvlan = vlan;
1618 return &vlan->net;
1621 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1625 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1627 return -ENOTSUP;
1630 static struct HCIInfo null_hci = {
1631 .cmd_send = null_hci_send,
1632 .sco_send = null_hci_send,
1633 .acl_send = null_hci_send,
1634 .bdaddr_set = null_hci_addr_set,
1637 struct HCIInfo *qemu_next_hci(void)
1639 if (cur_hci == nb_hcis)
1640 return &null_hci;
1642 return hci_table[cur_hci++];
1645 static struct HCIInfo *hci_init(const char *str)
1647 char *endp;
1648 struct bt_scatternet_s *vlan = 0;
1650 if (!strcmp(str, "null"))
1651 /* null */
1652 return &null_hci;
1653 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1654 /* host[:hciN] */
1655 return bt_host_hci(str[4] ? str + 5 : "hci0");
1656 else if (!strncmp(str, "hci", 3)) {
1657 /* hci[,vlan=n] */
1658 if (str[3]) {
1659 if (!strncmp(str + 3, ",vlan=", 6)) {
1660 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1661 if (*endp)
1662 vlan = 0;
1664 } else
1665 vlan = qemu_find_bt_vlan(0);
1666 if (vlan)
1667 return bt_new_hci(vlan);
1670 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1672 return 0;
1675 static int bt_hci_parse(const char *str)
1677 struct HCIInfo *hci;
1678 bdaddr_t bdaddr;
1680 if (nb_hcis >= MAX_NICS) {
1681 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1682 return -1;
1685 hci = hci_init(str);
1686 if (!hci)
1687 return -1;
1689 bdaddr.b[0] = 0x52;
1690 bdaddr.b[1] = 0x54;
1691 bdaddr.b[2] = 0x00;
1692 bdaddr.b[3] = 0x12;
1693 bdaddr.b[4] = 0x34;
1694 bdaddr.b[5] = 0x56 + nb_hcis;
1695 hci->bdaddr_set(hci, bdaddr.b);
1697 hci_table[nb_hcis++] = hci;
1699 return 0;
1702 static void bt_vhci_add(int vlan_id)
1704 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1706 if (!vlan->slave)
1707 fprintf(stderr, "qemu: warning: adding a VHCI to "
1708 "an empty scatternet %i\n", vlan_id);
1710 bt_vhci_init(bt_new_hci(vlan));
1713 static struct bt_device_s *bt_device_add(const char *opt)
1715 struct bt_scatternet_s *vlan;
1716 int vlan_id = 0;
1717 char *endp = strstr(opt, ",vlan=");
1718 int len = (endp ? endp - opt : strlen(opt)) + 1;
1719 char devname[10];
1721 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1723 if (endp) {
1724 vlan_id = strtol(endp + 6, &endp, 0);
1725 if (*endp) {
1726 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1727 return 0;
1731 vlan = qemu_find_bt_vlan(vlan_id);
1733 if (!vlan->slave)
1734 fprintf(stderr, "qemu: warning: adding a slave device to "
1735 "an empty scatternet %i\n", vlan_id);
1737 if (!strcmp(devname, "keyboard"))
1738 return bt_keyboard_init(vlan);
1740 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1741 return 0;
1744 static int bt_parse(const char *opt)
1746 const char *endp, *p;
1747 int vlan;
1749 if (strstart(opt, "hci", &endp)) {
1750 if (!*endp || *endp == ',') {
1751 if (*endp)
1752 if (!strstart(endp, ",vlan=", 0))
1753 opt = endp + 1;
1755 return bt_hci_parse(opt);
1757 } else if (strstart(opt, "vhci", &endp)) {
1758 if (!*endp || *endp == ',') {
1759 if (*endp) {
1760 if (strstart(endp, ",vlan=", &p)) {
1761 vlan = strtol(p, (char **) &endp, 0);
1762 if (*endp) {
1763 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1764 return 1;
1766 } else {
1767 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1768 return 1;
1770 } else
1771 vlan = 0;
1773 bt_vhci_add(vlan);
1774 return 0;
1776 } else if (strstart(opt, "device:", &endp))
1777 return !bt_device_add(endp);
1779 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1780 return 1;
1783 /***********************************************************/
1784 /* QEMU Block devices */
1786 #define HD_ALIAS "index=%d,media=disk"
1787 #define CDROM_ALIAS "index=2,media=cdrom"
1788 #define FD_ALIAS "index=%d,if=floppy"
1789 #define PFLASH_ALIAS "if=pflash"
1790 #define MTD_ALIAS "if=mtd"
1791 #define SD_ALIAS "index=0,if=sd"
1793 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1795 va_list ap;
1796 char optstr[1024];
1797 QemuOpts *opts;
1799 va_start(ap, fmt);
1800 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1801 va_end(ap);
1803 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1804 if (!opts) {
1805 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1806 __FUNCTION__, optstr);
1807 return NULL;
1809 if (file)
1810 qemu_opt_set(opts, "file", file);
1811 return opts;
1814 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1816 DriveInfo *dinfo;
1818 /* seek interface, bus and unit */
1820 QTAILQ_FOREACH(dinfo, &drives, next) {
1821 if (dinfo->type == type &&
1822 dinfo->bus == bus &&
1823 dinfo->unit == unit)
1824 return dinfo;
1827 return NULL;
1830 DriveInfo *drive_get_by_id(const char *id)
1832 DriveInfo *dinfo;
1834 QTAILQ_FOREACH(dinfo, &drives, next) {
1835 if (strcmp(id, dinfo->id))
1836 continue;
1837 return dinfo;
1839 return NULL;
1842 int drive_get_max_bus(BlockInterfaceType type)
1844 int max_bus;
1845 DriveInfo *dinfo;
1847 max_bus = -1;
1848 QTAILQ_FOREACH(dinfo, &drives, next) {
1849 if(dinfo->type == type &&
1850 dinfo->bus > max_bus)
1851 max_bus = dinfo->bus;
1853 return max_bus;
1856 const char *drive_get_serial(BlockDriverState *bdrv)
1858 DriveInfo *dinfo;
1860 QTAILQ_FOREACH(dinfo, &drives, next) {
1861 if (dinfo->bdrv == bdrv)
1862 return dinfo->serial;
1865 return "\0";
1868 BlockInterfaceErrorAction drive_get_on_error(
1869 BlockDriverState *bdrv, int is_read)
1871 DriveInfo *dinfo;
1873 QTAILQ_FOREACH(dinfo, &drives, next) {
1874 if (dinfo->bdrv == bdrv)
1875 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1878 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1881 static void bdrv_format_print(void *opaque, const char *name)
1883 fprintf(stderr, " %s", name);
1886 void drive_uninit(DriveInfo *dinfo)
1888 qemu_opts_del(dinfo->opts);
1889 bdrv_delete(dinfo->bdrv);
1890 QTAILQ_REMOVE(&drives, dinfo, next);
1891 qemu_free(dinfo);
1894 static int parse_block_error_action(const char *buf, int is_read)
1896 if (!strcmp(buf, "ignore")) {
1897 return BLOCK_ERR_IGNORE;
1898 } else if (!is_read && !strcmp(buf, "enospc")) {
1899 return BLOCK_ERR_STOP_ENOSPC;
1900 } else if (!strcmp(buf, "stop")) {
1901 return BLOCK_ERR_STOP_ANY;
1902 } else if (!strcmp(buf, "report")) {
1903 return BLOCK_ERR_REPORT;
1904 } else {
1905 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1906 buf, is_read ? "read" : "write");
1907 return -1;
1911 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1912 int *fatal_error)
1914 const char *buf;
1915 const char *file = NULL;
1916 char devname[128];
1917 const char *serial;
1918 const char *mediastr = "";
1919 BlockInterfaceType type;
1920 enum { MEDIA_DISK, MEDIA_CDROM } media;
1921 int bus_id, unit_id;
1922 int cyls, heads, secs, translation;
1923 BlockDriver *drv = NULL;
1924 QEMUMachine *machine = opaque;
1925 int max_devs;
1926 int index;
1927 int cache;
1928 int aio = 0;
1929 int ro = 0;
1930 int bdrv_flags;
1931 int on_read_error, on_write_error;
1932 const char *devaddr;
1933 DriveInfo *dinfo;
1934 int snapshot = 0;
1936 *fatal_error = 1;
1938 translation = BIOS_ATA_TRANSLATION_AUTO;
1939 cache = 1;
1941 if (machine && machine->use_scsi) {
1942 type = IF_SCSI;
1943 max_devs = MAX_SCSI_DEVS;
1944 pstrcpy(devname, sizeof(devname), "scsi");
1945 } else {
1946 type = IF_IDE;
1947 max_devs = MAX_IDE_DEVS;
1948 pstrcpy(devname, sizeof(devname), "ide");
1950 media = MEDIA_DISK;
1952 /* extract parameters */
1953 bus_id = qemu_opt_get_number(opts, "bus", 0);
1954 unit_id = qemu_opt_get_number(opts, "unit", -1);
1955 index = qemu_opt_get_number(opts, "index", -1);
1957 cyls = qemu_opt_get_number(opts, "cyls", 0);
1958 heads = qemu_opt_get_number(opts, "heads", 0);
1959 secs = qemu_opt_get_number(opts, "secs", 0);
1961 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1962 ro = qemu_opt_get_bool(opts, "readonly", 0);
1964 file = qemu_opt_get(opts, "file");
1965 serial = qemu_opt_get(opts, "serial");
1967 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1968 pstrcpy(devname, sizeof(devname), buf);
1969 if (!strcmp(buf, "ide")) {
1970 type = IF_IDE;
1971 max_devs = MAX_IDE_DEVS;
1972 } else if (!strcmp(buf, "scsi")) {
1973 type = IF_SCSI;
1974 max_devs = MAX_SCSI_DEVS;
1975 } else if (!strcmp(buf, "floppy")) {
1976 type = IF_FLOPPY;
1977 max_devs = 0;
1978 } else if (!strcmp(buf, "pflash")) {
1979 type = IF_PFLASH;
1980 max_devs = 0;
1981 } else if (!strcmp(buf, "mtd")) {
1982 type = IF_MTD;
1983 max_devs = 0;
1984 } else if (!strcmp(buf, "sd")) {
1985 type = IF_SD;
1986 max_devs = 0;
1987 } else if (!strcmp(buf, "virtio")) {
1988 type = IF_VIRTIO;
1989 max_devs = 0;
1990 } else if (!strcmp(buf, "xen")) {
1991 type = IF_XEN;
1992 max_devs = 0;
1993 } else if (!strcmp(buf, "none")) {
1994 type = IF_NONE;
1995 max_devs = 0;
1996 } else {
1997 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1998 return NULL;
2002 if (cyls || heads || secs) {
2003 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2004 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2005 return NULL;
2007 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2008 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2009 return NULL;
2011 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2012 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2013 return NULL;
2017 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2018 if (!cyls) {
2019 fprintf(stderr,
2020 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2021 buf);
2022 return NULL;
2024 if (!strcmp(buf, "none"))
2025 translation = BIOS_ATA_TRANSLATION_NONE;
2026 else if (!strcmp(buf, "lba"))
2027 translation = BIOS_ATA_TRANSLATION_LBA;
2028 else if (!strcmp(buf, "auto"))
2029 translation = BIOS_ATA_TRANSLATION_AUTO;
2030 else {
2031 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2032 return NULL;
2036 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2037 if (!strcmp(buf, "disk")) {
2038 media = MEDIA_DISK;
2039 } else if (!strcmp(buf, "cdrom")) {
2040 if (cyls || secs || heads) {
2041 fprintf(stderr,
2042 "qemu: '%s' invalid physical CHS format\n", buf);
2043 return NULL;
2045 media = MEDIA_CDROM;
2046 } else {
2047 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2048 return NULL;
2052 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2053 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2054 cache = 0;
2055 else if (!strcmp(buf, "writethrough"))
2056 cache = 1;
2057 else if (!strcmp(buf, "writeback"))
2058 cache = 2;
2059 else {
2060 fprintf(stderr, "qemu: invalid cache option\n");
2061 return NULL;
2065 #ifdef CONFIG_LINUX_AIO
2066 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2067 if (!strcmp(buf, "threads"))
2068 aio = 0;
2069 else if (!strcmp(buf, "native"))
2070 aio = 1;
2071 else {
2072 fprintf(stderr, "qemu: invalid aio option\n");
2073 return NULL;
2076 #endif
2078 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2079 if (strcmp(buf, "?") == 0) {
2080 fprintf(stderr, "qemu: Supported formats:");
2081 bdrv_iterate_format(bdrv_format_print, NULL);
2082 fprintf(stderr, "\n");
2083 return NULL;
2085 drv = bdrv_find_whitelisted_format(buf);
2086 if (!drv) {
2087 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2088 return NULL;
2092 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2093 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2094 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2095 fprintf(stderr, "werror is no supported by this format\n");
2096 return NULL;
2099 on_write_error = parse_block_error_action(buf, 0);
2100 if (on_write_error < 0) {
2101 return NULL;
2105 on_read_error = BLOCK_ERR_REPORT;
2106 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2107 if (type != IF_IDE && type != IF_VIRTIO) {
2108 fprintf(stderr, "rerror is no supported by this format\n");
2109 return NULL;
2112 on_read_error = parse_block_error_action(buf, 1);
2113 if (on_read_error < 0) {
2114 return NULL;
2118 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2119 if (type != IF_VIRTIO) {
2120 fprintf(stderr, "addr is not supported\n");
2121 return NULL;
2125 /* compute bus and unit according index */
2127 if (index != -1) {
2128 if (bus_id != 0 || unit_id != -1) {
2129 fprintf(stderr,
2130 "qemu: index cannot be used with bus and unit\n");
2131 return NULL;
2133 if (max_devs == 0)
2135 unit_id = index;
2136 bus_id = 0;
2137 } else {
2138 unit_id = index % max_devs;
2139 bus_id = index / max_devs;
2143 /* if user doesn't specify a unit_id,
2144 * try to find the first free
2147 if (unit_id == -1) {
2148 unit_id = 0;
2149 while (drive_get(type, bus_id, unit_id) != NULL) {
2150 unit_id++;
2151 if (max_devs && unit_id >= max_devs) {
2152 unit_id -= max_devs;
2153 bus_id++;
2158 /* check unit id */
2160 if (max_devs && unit_id >= max_devs) {
2161 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2162 unit_id, max_devs - 1);
2163 return NULL;
2167 * ignore multiple definitions
2170 if (drive_get(type, bus_id, unit_id) != NULL) {
2171 *fatal_error = 0;
2172 return NULL;
2175 /* init */
2177 dinfo = qemu_mallocz(sizeof(*dinfo));
2178 if ((buf = qemu_opts_id(opts)) != NULL) {
2179 dinfo->id = qemu_strdup(buf);
2180 } else {
2181 /* no id supplied -> create one */
2182 dinfo->id = qemu_mallocz(32);
2183 if (type == IF_IDE || type == IF_SCSI)
2184 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2185 if (max_devs)
2186 snprintf(dinfo->id, 32, "%s%i%s%i",
2187 devname, bus_id, mediastr, unit_id);
2188 else
2189 snprintf(dinfo->id, 32, "%s%s%i",
2190 devname, mediastr, unit_id);
2192 dinfo->bdrv = bdrv_new(dinfo->id);
2193 dinfo->devaddr = devaddr;
2194 dinfo->type = type;
2195 dinfo->bus = bus_id;
2196 dinfo->unit = unit_id;
2197 dinfo->on_read_error = on_read_error;
2198 dinfo->on_write_error = on_write_error;
2199 dinfo->opts = opts;
2200 if (serial)
2201 strncpy(dinfo->serial, serial, sizeof(serial));
2202 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2204 switch(type) {
2205 case IF_IDE:
2206 case IF_SCSI:
2207 case IF_XEN:
2208 case IF_NONE:
2209 switch(media) {
2210 case MEDIA_DISK:
2211 if (cyls != 0) {
2212 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2213 bdrv_set_translation_hint(dinfo->bdrv, translation);
2215 break;
2216 case MEDIA_CDROM:
2217 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2218 break;
2220 break;
2221 case IF_SD:
2222 /* FIXME: This isn't really a floppy, but it's a reasonable
2223 approximation. */
2224 case IF_FLOPPY:
2225 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2226 break;
2227 case IF_PFLASH:
2228 case IF_MTD:
2229 break;
2230 case IF_VIRTIO:
2231 /* add virtio block device */
2232 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2233 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2234 qemu_opt_set(opts, "drive", dinfo->id);
2235 if (devaddr)
2236 qemu_opt_set(opts, "addr", devaddr);
2237 break;
2238 case IF_COUNT:
2239 abort();
2241 if (!file) {
2242 *fatal_error = 0;
2243 return NULL;
2245 bdrv_flags = 0;
2246 if (snapshot) {
2247 bdrv_flags |= BDRV_O_SNAPSHOT;
2248 cache = 2; /* always use write-back with snapshot */
2250 if (cache == 0) /* no caching */
2251 bdrv_flags |= BDRV_O_NOCACHE;
2252 else if (cache == 2) /* write-back */
2253 bdrv_flags |= BDRV_O_CACHE_WB;
2255 if (aio == 1) {
2256 bdrv_flags |= BDRV_O_NATIVE_AIO;
2257 } else {
2258 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2261 if (ro == 1) {
2262 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2263 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2264 return NULL;
2268 * cdrom is read-only. Set it now, after above interface checking
2269 * since readonly attribute not explicitly required, so no error.
2271 if (media == MEDIA_CDROM) {
2272 ro = 1;
2274 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2276 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2277 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2278 file, strerror(errno));
2279 return NULL;
2282 if (bdrv_key_required(dinfo->bdrv))
2283 autostart = 0;
2284 *fatal_error = 0;
2285 return dinfo;
2288 static int drive_init_func(QemuOpts *opts, void *opaque)
2290 QEMUMachine *machine = opaque;
2291 int fatal_error = 0;
2293 if (drive_init(opts, machine, &fatal_error) == NULL) {
2294 if (fatal_error)
2295 return 1;
2297 return 0;
2300 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2302 if (NULL == qemu_opt_get(opts, "snapshot")) {
2303 qemu_opt_set(opts, "snapshot", "on");
2305 return 0;
2308 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2310 boot_set_handler = func;
2311 boot_set_opaque = opaque;
2314 int qemu_boot_set(const char *boot_devices)
2316 if (!boot_set_handler) {
2317 return -EINVAL;
2319 return boot_set_handler(boot_set_opaque, boot_devices);
2322 static int parse_bootdevices(char *devices)
2324 /* We just do some generic consistency checks */
2325 const char *p;
2326 int bitmap = 0;
2328 for (p = devices; *p != '\0'; p++) {
2329 /* Allowed boot devices are:
2330 * a-b: floppy disk drives
2331 * c-f: IDE disk drives
2332 * g-m: machine implementation dependant drives
2333 * n-p: network devices
2334 * It's up to each machine implementation to check if the given boot
2335 * devices match the actual hardware implementation and firmware
2336 * features.
2338 if (*p < 'a' || *p > 'p') {
2339 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2340 exit(1);
2342 if (bitmap & (1 << (*p - 'a'))) {
2343 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2344 exit(1);
2346 bitmap |= 1 << (*p - 'a');
2348 return bitmap;
2351 static void restore_boot_devices(void *opaque)
2353 char *standard_boot_devices = opaque;
2355 qemu_boot_set(standard_boot_devices);
2357 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2358 qemu_free(standard_boot_devices);
2361 static void numa_add(const char *optarg)
2363 char option[128];
2364 char *endptr;
2365 unsigned long long value, endvalue;
2366 int nodenr;
2368 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2369 if (!strcmp(option, "node")) {
2370 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2371 nodenr = nb_numa_nodes;
2372 } else {
2373 nodenr = strtoull(option, NULL, 10);
2376 if (get_param_value(option, 128, "mem", optarg) == 0) {
2377 node_mem[nodenr] = 0;
2378 } else {
2379 value = strtoull(option, &endptr, 0);
2380 switch (*endptr) {
2381 case 0: case 'M': case 'm':
2382 value <<= 20;
2383 break;
2384 case 'G': case 'g':
2385 value <<= 30;
2386 break;
2388 node_mem[nodenr] = value;
2390 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2391 node_cpumask[nodenr] = 0;
2392 } else {
2393 value = strtoull(option, &endptr, 10);
2394 if (value >= 64) {
2395 value = 63;
2396 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2397 } else {
2398 if (*endptr == '-') {
2399 endvalue = strtoull(endptr+1, &endptr, 10);
2400 if (endvalue >= 63) {
2401 endvalue = 62;
2402 fprintf(stderr,
2403 "only 63 CPUs in NUMA mode supported.\n");
2405 value = (2ULL << endvalue) - (1ULL << value);
2406 } else {
2407 value = 1ULL << value;
2410 node_cpumask[nodenr] = value;
2412 nb_numa_nodes++;
2414 return;
2417 static void smp_parse(const char *optarg)
2419 int smp, sockets = 0, threads = 0, cores = 0;
2420 char *endptr;
2421 char option[128];
2423 smp = strtoul(optarg, &endptr, 10);
2424 if (endptr != optarg) {
2425 if (*endptr == ',') {
2426 endptr++;
2429 if (get_param_value(option, 128, "sockets", endptr) != 0)
2430 sockets = strtoull(option, NULL, 10);
2431 if (get_param_value(option, 128, "cores", endptr) != 0)
2432 cores = strtoull(option, NULL, 10);
2433 if (get_param_value(option, 128, "threads", endptr) != 0)
2434 threads = strtoull(option, NULL, 10);
2435 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2436 max_cpus = strtoull(option, NULL, 10);
2438 /* compute missing values, prefer sockets over cores over threads */
2439 if (smp == 0 || sockets == 0) {
2440 sockets = sockets > 0 ? sockets : 1;
2441 cores = cores > 0 ? cores : 1;
2442 threads = threads > 0 ? threads : 1;
2443 if (smp == 0) {
2444 smp = cores * threads * sockets;
2446 } else {
2447 if (cores == 0) {
2448 threads = threads > 0 ? threads : 1;
2449 cores = smp / (sockets * threads);
2450 } else {
2451 if (sockets) {
2452 threads = smp / (cores * sockets);
2456 smp_cpus = smp;
2457 smp_cores = cores > 0 ? cores : 1;
2458 smp_threads = threads > 0 ? threads : 1;
2459 if (max_cpus == 0)
2460 max_cpus = smp_cpus;
2463 /***********************************************************/
2464 /* USB devices */
2466 static int usb_device_add(const char *devname, int is_hotplug)
2468 const char *p;
2469 USBDevice *dev = NULL;
2471 if (!usb_enabled)
2472 return -1;
2474 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2475 dev = usbdevice_create(devname);
2476 if (dev)
2477 goto done;
2479 /* the other ones */
2480 if (strstart(devname, "host:", &p)) {
2481 dev = usb_host_device_open(p);
2482 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2483 dev = usb_bt_init(devname[2] ? hci_init(p) :
2484 bt_new_hci(qemu_find_bt_vlan(0)));
2485 } else {
2486 return -1;
2488 if (!dev)
2489 return -1;
2491 done:
2492 return 0;
2495 static int usb_device_del(const char *devname)
2497 int bus_num, addr;
2498 const char *p;
2500 if (strstart(devname, "host:", &p))
2501 return usb_host_device_close(p);
2503 if (!usb_enabled)
2504 return -1;
2506 p = strchr(devname, '.');
2507 if (!p)
2508 return -1;
2509 bus_num = strtoul(devname, NULL, 0);
2510 addr = strtoul(p + 1, NULL, 0);
2512 return usb_device_delete_addr(bus_num, addr);
2515 static int usb_parse(const char *cmdline)
2517 int r;
2518 r = usb_device_add(cmdline, 0);
2519 if (r < 0) {
2520 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2522 return r;
2525 void do_usb_add(Monitor *mon, const QDict *qdict)
2527 const char *devname = qdict_get_str(qdict, "devname");
2528 if (usb_device_add(devname, 1) < 0) {
2529 qemu_error("could not add USB device '%s'\n", devname);
2533 void do_usb_del(Monitor *mon, const QDict *qdict)
2535 const char *devname = qdict_get_str(qdict, "devname");
2536 if (usb_device_del(devname) < 0) {
2537 qemu_error("could not delete USB device '%s'\n", devname);
2541 /***********************************************************/
2542 /* PCMCIA/Cardbus */
2544 static struct pcmcia_socket_entry_s {
2545 PCMCIASocket *socket;
2546 struct pcmcia_socket_entry_s *next;
2547 } *pcmcia_sockets = 0;
2549 void pcmcia_socket_register(PCMCIASocket *socket)
2551 struct pcmcia_socket_entry_s *entry;
2553 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2554 entry->socket = socket;
2555 entry->next = pcmcia_sockets;
2556 pcmcia_sockets = entry;
2559 void pcmcia_socket_unregister(PCMCIASocket *socket)
2561 struct pcmcia_socket_entry_s *entry, **ptr;
2563 ptr = &pcmcia_sockets;
2564 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2565 if (entry->socket == socket) {
2566 *ptr = entry->next;
2567 qemu_free(entry);
2571 void pcmcia_info(Monitor *mon)
2573 struct pcmcia_socket_entry_s *iter;
2575 if (!pcmcia_sockets)
2576 monitor_printf(mon, "No PCMCIA sockets\n");
2578 for (iter = pcmcia_sockets; iter; iter = iter->next)
2579 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2580 iter->socket->attached ? iter->socket->card_string :
2581 "Empty");
2584 /***********************************************************/
2585 /* I/O handling */
2587 typedef struct IOHandlerRecord {
2588 int fd;
2589 IOCanRWHandler *fd_read_poll;
2590 IOHandler *fd_read;
2591 IOHandler *fd_write;
2592 int deleted;
2593 void *opaque;
2594 /* temporary data */
2595 struct pollfd *ufd;
2596 struct IOHandlerRecord *next;
2597 } IOHandlerRecord;
2599 static IOHandlerRecord *first_io_handler;
2601 /* XXX: fd_read_poll should be suppressed, but an API change is
2602 necessary in the character devices to suppress fd_can_read(). */
2603 int qemu_set_fd_handler2(int fd,
2604 IOCanRWHandler *fd_read_poll,
2605 IOHandler *fd_read,
2606 IOHandler *fd_write,
2607 void *opaque)
2609 IOHandlerRecord **pioh, *ioh;
2611 if (!fd_read && !fd_write) {
2612 pioh = &first_io_handler;
2613 for(;;) {
2614 ioh = *pioh;
2615 if (ioh == NULL)
2616 break;
2617 if (ioh->fd == fd) {
2618 ioh->deleted = 1;
2619 break;
2621 pioh = &ioh->next;
2623 } else {
2624 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2625 if (ioh->fd == fd)
2626 goto found;
2628 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2629 ioh->next = first_io_handler;
2630 first_io_handler = ioh;
2631 found:
2632 ioh->fd = fd;
2633 ioh->fd_read_poll = fd_read_poll;
2634 ioh->fd_read = fd_read;
2635 ioh->fd_write = fd_write;
2636 ioh->opaque = opaque;
2637 ioh->deleted = 0;
2639 return 0;
2642 int qemu_set_fd_handler(int fd,
2643 IOHandler *fd_read,
2644 IOHandler *fd_write,
2645 void *opaque)
2647 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2650 #ifdef _WIN32
2651 /***********************************************************/
2652 /* Polling handling */
2654 typedef struct PollingEntry {
2655 PollingFunc *func;
2656 void *opaque;
2657 struct PollingEntry *next;
2658 } PollingEntry;
2660 static PollingEntry *first_polling_entry;
2662 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2664 PollingEntry **ppe, *pe;
2665 pe = qemu_mallocz(sizeof(PollingEntry));
2666 pe->func = func;
2667 pe->opaque = opaque;
2668 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2669 *ppe = pe;
2670 return 0;
2673 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2675 PollingEntry **ppe, *pe;
2676 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2677 pe = *ppe;
2678 if (pe->func == func && pe->opaque == opaque) {
2679 *ppe = pe->next;
2680 qemu_free(pe);
2681 break;
2686 /***********************************************************/
2687 /* Wait objects support */
2688 typedef struct WaitObjects {
2689 int num;
2690 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2691 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2692 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2693 } WaitObjects;
2695 static WaitObjects wait_objects = {0};
2697 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2699 WaitObjects *w = &wait_objects;
2701 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2702 return -1;
2703 w->events[w->num] = handle;
2704 w->func[w->num] = func;
2705 w->opaque[w->num] = opaque;
2706 w->num++;
2707 return 0;
2710 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2712 int i, found;
2713 WaitObjects *w = &wait_objects;
2715 found = 0;
2716 for (i = 0; i < w->num; i++) {
2717 if (w->events[i] == handle)
2718 found = 1;
2719 if (found) {
2720 w->events[i] = w->events[i + 1];
2721 w->func[i] = w->func[i + 1];
2722 w->opaque[i] = w->opaque[i + 1];
2725 if (found)
2726 w->num--;
2728 #endif
2730 /***********************************************************/
2731 /* ram save/restore */
2733 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2734 #define RAM_SAVE_FLAG_COMPRESS 0x02
2735 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2736 #define RAM_SAVE_FLAG_PAGE 0x08
2737 #define RAM_SAVE_FLAG_EOS 0x10
2739 static int is_dup_page(uint8_t *page, uint8_t ch)
2741 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2742 uint32_t *array = (uint32_t *)page;
2743 int i;
2745 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2746 if (array[i] != val)
2747 return 0;
2750 return 1;
2753 static int ram_save_block(QEMUFile *f)
2755 static ram_addr_t current_addr = 0;
2756 ram_addr_t saved_addr = current_addr;
2757 ram_addr_t addr = 0;
2758 int found = 0;
2760 while (addr < last_ram_offset) {
2761 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2762 uint8_t *p;
2764 cpu_physical_memory_reset_dirty(current_addr,
2765 current_addr + TARGET_PAGE_SIZE,
2766 MIGRATION_DIRTY_FLAG);
2768 p = qemu_get_ram_ptr(current_addr);
2770 if (is_dup_page(p, *p)) {
2771 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2772 qemu_put_byte(f, *p);
2773 } else {
2774 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2775 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2778 found = 1;
2779 break;
2781 addr += TARGET_PAGE_SIZE;
2782 current_addr = (saved_addr + addr) % last_ram_offset;
2785 return found;
2788 static uint64_t bytes_transferred;
2790 static ram_addr_t ram_save_remaining(void)
2792 ram_addr_t addr;
2793 ram_addr_t count = 0;
2795 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2796 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2797 count++;
2800 return count;
2803 uint64_t ram_bytes_remaining(void)
2805 return ram_save_remaining() * TARGET_PAGE_SIZE;
2808 uint64_t ram_bytes_transferred(void)
2810 return bytes_transferred;
2813 uint64_t ram_bytes_total(void)
2815 return last_ram_offset;
2818 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2820 ram_addr_t addr;
2821 uint64_t bytes_transferred_last;
2822 double bwidth = 0;
2823 uint64_t expected_time = 0;
2825 if (stage < 0) {
2826 cpu_physical_memory_set_dirty_tracking(0);
2827 return 0;
2830 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2831 qemu_file_set_error(f);
2832 return 0;
2835 if (stage == 1) {
2836 bytes_transferred = 0;
2838 /* Make sure all dirty bits are set */
2839 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2840 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2841 cpu_physical_memory_set_dirty(addr);
2844 /* Enable dirty memory tracking */
2845 cpu_physical_memory_set_dirty_tracking(1);
2847 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2850 bytes_transferred_last = bytes_transferred;
2851 bwidth = qemu_get_clock_ns(rt_clock);
2853 while (!qemu_file_rate_limit(f)) {
2854 int ret;
2856 ret = ram_save_block(f);
2857 bytes_transferred += ret * TARGET_PAGE_SIZE;
2858 if (ret == 0) /* no more blocks */
2859 break;
2862 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
2863 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2865 /* if we haven't transferred anything this round, force expected_time to a
2866 * a very high value, but without crashing */
2867 if (bwidth == 0)
2868 bwidth = 0.000001;
2870 /* try transferring iterative blocks of memory */
2871 if (stage == 3) {
2872 /* flush all remaining blocks regardless of rate limiting */
2873 while (ram_save_block(f) != 0) {
2874 bytes_transferred += TARGET_PAGE_SIZE;
2876 cpu_physical_memory_set_dirty_tracking(0);
2879 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2881 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2883 return (stage == 2) && (expected_time <= migrate_max_downtime());
2886 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2888 ram_addr_t addr;
2889 int flags;
2891 if (version_id != 3)
2892 return -EINVAL;
2894 do {
2895 addr = qemu_get_be64(f);
2897 flags = addr & ~TARGET_PAGE_MASK;
2898 addr &= TARGET_PAGE_MASK;
2900 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2901 if (addr != last_ram_offset)
2902 return -EINVAL;
2905 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2906 uint8_t ch = qemu_get_byte(f);
2907 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2908 #ifndef _WIN32
2909 if (ch == 0 &&
2910 (!kvm_enabled() || kvm_has_sync_mmu())) {
2911 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2913 #endif
2914 } else if (flags & RAM_SAVE_FLAG_PAGE) {
2915 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2917 if (qemu_file_has_error(f)) {
2918 return -EIO;
2920 } while (!(flags & RAM_SAVE_FLAG_EOS));
2922 return 0;
2925 void qemu_service_io(void)
2927 qemu_notify_event();
2930 /***********************************************************/
2931 /* machine registration */
2933 static QEMUMachine *first_machine = NULL;
2934 QEMUMachine *current_machine = NULL;
2936 int qemu_register_machine(QEMUMachine *m)
2938 QEMUMachine **pm;
2939 pm = &first_machine;
2940 while (*pm != NULL)
2941 pm = &(*pm)->next;
2942 m->next = NULL;
2943 *pm = m;
2944 return 0;
2947 static QEMUMachine *find_machine(const char *name)
2949 QEMUMachine *m;
2951 for(m = first_machine; m != NULL; m = m->next) {
2952 if (!strcmp(m->name, name))
2953 return m;
2954 if (m->alias && !strcmp(m->alias, name))
2955 return m;
2957 return NULL;
2960 static QEMUMachine *find_default_machine(void)
2962 QEMUMachine *m;
2964 for(m = first_machine; m != NULL; m = m->next) {
2965 if (m->is_default) {
2966 return m;
2969 return NULL;
2972 /***********************************************************/
2973 /* main execution loop */
2975 static void gui_update(void *opaque)
2977 uint64_t interval = GUI_REFRESH_INTERVAL;
2978 DisplayState *ds = opaque;
2979 DisplayChangeListener *dcl = ds->listeners;
2981 qemu_flush_coalesced_mmio_buffer();
2982 dpy_refresh(ds);
2984 while (dcl != NULL) {
2985 if (dcl->gui_timer_interval &&
2986 dcl->gui_timer_interval < interval)
2987 interval = dcl->gui_timer_interval;
2988 dcl = dcl->next;
2990 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
2993 static void nographic_update(void *opaque)
2995 uint64_t interval = GUI_REFRESH_INTERVAL;
2997 qemu_flush_coalesced_mmio_buffer();
2998 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3001 struct vm_change_state_entry {
3002 VMChangeStateHandler *cb;
3003 void *opaque;
3004 QLIST_ENTRY (vm_change_state_entry) entries;
3007 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3009 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3010 void *opaque)
3012 VMChangeStateEntry *e;
3014 e = qemu_mallocz(sizeof (*e));
3016 e->cb = cb;
3017 e->opaque = opaque;
3018 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3019 return e;
3022 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3024 QLIST_REMOVE (e, entries);
3025 qemu_free (e);
3028 static void vm_state_notify(int running, int reason)
3030 VMChangeStateEntry *e;
3032 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3033 e->cb(e->opaque, running, reason);
3037 static void resume_all_vcpus(void);
3038 static void pause_all_vcpus(void);
3040 void vm_start(void)
3042 if (!vm_running) {
3043 cpu_enable_ticks();
3044 vm_running = 1;
3045 vm_state_notify(1, 0);
3046 qemu_rearm_alarm_timer(alarm_timer);
3047 resume_all_vcpus();
3051 /* reset/shutdown handler */
3053 typedef struct QEMUResetEntry {
3054 QTAILQ_ENTRY(QEMUResetEntry) entry;
3055 QEMUResetHandler *func;
3056 void *opaque;
3057 } QEMUResetEntry;
3059 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3060 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3061 static int reset_requested;
3062 static int shutdown_requested;
3063 static int powerdown_requested;
3064 static int debug_requested;
3065 static int vmstop_requested;
3067 int qemu_shutdown_requested(void)
3069 int r = shutdown_requested;
3070 shutdown_requested = 0;
3071 return r;
3074 int qemu_reset_requested(void)
3076 int r = reset_requested;
3077 reset_requested = 0;
3078 return r;
3081 int qemu_powerdown_requested(void)
3083 int r = powerdown_requested;
3084 powerdown_requested = 0;
3085 return r;
3088 static int qemu_debug_requested(void)
3090 int r = debug_requested;
3091 debug_requested = 0;
3092 return r;
3095 static int qemu_vmstop_requested(void)
3097 int r = vmstop_requested;
3098 vmstop_requested = 0;
3099 return r;
3102 static void do_vm_stop(int reason)
3104 if (vm_running) {
3105 cpu_disable_ticks();
3106 vm_running = 0;
3107 pause_all_vcpus();
3108 vm_state_notify(0, reason);
3112 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3114 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3116 re->func = func;
3117 re->opaque = opaque;
3118 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3121 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3123 QEMUResetEntry *re;
3125 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3126 if (re->func == func && re->opaque == opaque) {
3127 QTAILQ_REMOVE(&reset_handlers, re, entry);
3128 qemu_free(re);
3129 return;
3134 void qemu_system_reset(void)
3136 QEMUResetEntry *re, *nre;
3138 /* reset all devices */
3139 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3140 re->func(re->opaque);
3144 void qemu_system_reset_request(void)
3146 if (no_reboot) {
3147 shutdown_requested = 1;
3148 } else {
3149 reset_requested = 1;
3151 qemu_notify_event();
3154 void qemu_system_shutdown_request(void)
3156 shutdown_requested = 1;
3157 qemu_notify_event();
3160 void qemu_system_powerdown_request(void)
3162 powerdown_requested = 1;
3163 qemu_notify_event();
3166 #ifdef CONFIG_IOTHREAD
3167 static void qemu_system_vmstop_request(int reason)
3169 vmstop_requested = reason;
3170 qemu_notify_event();
3172 #endif
3174 #ifndef _WIN32
3175 static int io_thread_fd = -1;
3177 static void qemu_event_increment(void)
3179 /* Write 8 bytes to be compatible with eventfd. */
3180 static uint64_t val = 1;
3181 ssize_t ret;
3183 if (io_thread_fd == -1)
3184 return;
3186 do {
3187 ret = write(io_thread_fd, &val, sizeof(val));
3188 } while (ret < 0 && errno == EINTR);
3190 /* EAGAIN is fine, a read must be pending. */
3191 if (ret < 0 && errno != EAGAIN) {
3192 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3193 strerror(errno));
3194 exit (1);
3198 static void qemu_event_read(void *opaque)
3200 int fd = (unsigned long)opaque;
3201 ssize_t len;
3202 char buffer[512];
3204 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
3205 do {
3206 len = read(fd, buffer, sizeof(buffer));
3207 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
3210 static int qemu_event_init(void)
3212 int err;
3213 int fds[2];
3215 err = qemu_eventfd(fds);
3216 if (err == -1)
3217 return -errno;
3219 err = fcntl_setfl(fds[0], O_NONBLOCK);
3220 if (err < 0)
3221 goto fail;
3223 err = fcntl_setfl(fds[1], O_NONBLOCK);
3224 if (err < 0)
3225 goto fail;
3227 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3228 (void *)(unsigned long)fds[0]);
3230 io_thread_fd = fds[1];
3231 return 0;
3233 fail:
3234 close(fds[0]);
3235 close(fds[1]);
3236 return err;
3238 #else
3239 HANDLE qemu_event_handle;
3241 static void dummy_event_handler(void *opaque)
3245 static int qemu_event_init(void)
3247 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3248 if (!qemu_event_handle) {
3249 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3250 return -1;
3252 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3253 return 0;
3256 static void qemu_event_increment(void)
3258 if (!SetEvent(qemu_event_handle)) {
3259 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3260 GetLastError());
3261 exit (1);
3264 #endif
3266 static int cpu_can_run(CPUState *env)
3268 if (env->stop)
3269 return 0;
3270 if (env->stopped)
3271 return 0;
3272 if (!vm_running)
3273 return 0;
3274 return 1;
3277 #ifndef CONFIG_IOTHREAD
3278 static int qemu_init_main_loop(void)
3280 return qemu_event_init();
3283 void qemu_init_vcpu(void *_env)
3285 CPUState *env = _env;
3287 env->nr_cores = smp_cores;
3288 env->nr_threads = smp_threads;
3289 if (kvm_enabled())
3290 kvm_init_vcpu(env);
3291 return;
3294 int qemu_cpu_self(void *env)
3296 return 1;
3299 static void resume_all_vcpus(void)
3303 static void pause_all_vcpus(void)
3307 void qemu_cpu_kick(void *env)
3309 return;
3312 void qemu_notify_event(void)
3314 CPUState *env = cpu_single_env;
3316 if (env) {
3317 cpu_exit(env);
3321 void qemu_mutex_lock_iothread(void) {}
3322 void qemu_mutex_unlock_iothread(void) {}
3324 void vm_stop(int reason)
3326 do_vm_stop(reason);
3329 #else /* CONFIG_IOTHREAD */
3331 #include "qemu-thread.h"
3333 QemuMutex qemu_global_mutex;
3334 static QemuMutex qemu_fair_mutex;
3336 static QemuThread io_thread;
3338 static QemuThread *tcg_cpu_thread;
3339 static QemuCond *tcg_halt_cond;
3341 static int qemu_system_ready;
3342 /* cpu creation */
3343 static QemuCond qemu_cpu_cond;
3344 /* system init */
3345 static QemuCond qemu_system_cond;
3346 static QemuCond qemu_pause_cond;
3348 static void tcg_block_io_signals(void);
3349 static void kvm_block_io_signals(CPUState *env);
3350 static void unblock_io_signals(void);
3351 static int tcg_has_work(void);
3352 static int cpu_has_work(CPUState *env);
3354 static int qemu_init_main_loop(void)
3356 int ret;
3358 ret = qemu_event_init();
3359 if (ret)
3360 return ret;
3362 qemu_cond_init(&qemu_pause_cond);
3363 qemu_mutex_init(&qemu_fair_mutex);
3364 qemu_mutex_init(&qemu_global_mutex);
3365 qemu_mutex_lock(&qemu_global_mutex);
3367 unblock_io_signals();
3368 qemu_thread_self(&io_thread);
3370 return 0;
3373 static void qemu_wait_io_event_common(CPUState *env)
3375 if (env->stop) {
3376 env->stop = 0;
3377 env->stopped = 1;
3378 qemu_cond_signal(&qemu_pause_cond);
3382 static void qemu_wait_io_event(CPUState *env)
3384 while (!tcg_has_work())
3385 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3387 qemu_mutex_unlock(&qemu_global_mutex);
3390 * Users of qemu_global_mutex can be starved, having no chance
3391 * to acquire it since this path will get to it first.
3392 * So use another lock to provide fairness.
3394 qemu_mutex_lock(&qemu_fair_mutex);
3395 qemu_mutex_unlock(&qemu_fair_mutex);
3397 qemu_mutex_lock(&qemu_global_mutex);
3398 qemu_wait_io_event_common(env);
3401 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
3403 struct timespec ts;
3404 int r, e;
3405 siginfo_t siginfo;
3406 sigset_t waitset;
3408 ts.tv_sec = timeout / 1000;
3409 ts.tv_nsec = (timeout % 1000) * 1000000;
3411 sigemptyset(&waitset);
3412 sigaddset(&waitset, SIG_IPI);
3414 qemu_mutex_unlock(&qemu_global_mutex);
3415 r = sigtimedwait(&waitset, &siginfo, &ts);
3416 e = errno;
3417 qemu_mutex_lock(&qemu_global_mutex);
3419 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
3420 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
3421 exit(1);
3425 static void qemu_kvm_wait_io_event(CPUState *env)
3427 while (!cpu_has_work(env))
3428 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3430 qemu_kvm_eat_signal(env, 0);
3431 qemu_wait_io_event_common(env);
3434 static int qemu_cpu_exec(CPUState *env);
3436 static void *kvm_cpu_thread_fn(void *arg)
3438 CPUState *env = arg;
3440 qemu_thread_self(env->thread);
3441 if (kvm_enabled())
3442 kvm_init_vcpu(env);
3444 kvm_block_io_signals(env);
3446 /* signal CPU creation */
3447 qemu_mutex_lock(&qemu_global_mutex);
3448 env->created = 1;
3449 qemu_cond_signal(&qemu_cpu_cond);
3451 /* and wait for machine initialization */
3452 while (!qemu_system_ready)
3453 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3455 while (1) {
3456 if (cpu_can_run(env))
3457 qemu_cpu_exec(env);
3458 qemu_kvm_wait_io_event(env);
3461 return NULL;
3464 static void tcg_cpu_exec(void);
3466 static void *tcg_cpu_thread_fn(void *arg)
3468 CPUState *env = arg;
3470 tcg_block_io_signals();
3471 qemu_thread_self(env->thread);
3473 /* signal CPU creation */
3474 qemu_mutex_lock(&qemu_global_mutex);
3475 for (env = first_cpu; env != NULL; env = env->next_cpu)
3476 env->created = 1;
3477 qemu_cond_signal(&qemu_cpu_cond);
3479 /* and wait for machine initialization */
3480 while (!qemu_system_ready)
3481 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3483 while (1) {
3484 tcg_cpu_exec();
3485 qemu_wait_io_event(cur_cpu);
3488 return NULL;
3491 void qemu_cpu_kick(void *_env)
3493 CPUState *env = _env;
3494 qemu_cond_broadcast(env->halt_cond);
3495 if (kvm_enabled())
3496 qemu_thread_signal(env->thread, SIG_IPI);
3499 int qemu_cpu_self(void *_env)
3501 CPUState *env = _env;
3502 QemuThread this;
3504 qemu_thread_self(&this);
3506 return qemu_thread_equal(&this, env->thread);
3509 static void cpu_signal(int sig)
3511 if (cpu_single_env)
3512 cpu_exit(cpu_single_env);
3515 static void tcg_block_io_signals(void)
3517 sigset_t set;
3518 struct sigaction sigact;
3520 sigemptyset(&set);
3521 sigaddset(&set, SIGUSR2);
3522 sigaddset(&set, SIGIO);
3523 sigaddset(&set, SIGALRM);
3524 sigaddset(&set, SIGCHLD);
3525 pthread_sigmask(SIG_BLOCK, &set, NULL);
3527 sigemptyset(&set);
3528 sigaddset(&set, SIG_IPI);
3529 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3531 memset(&sigact, 0, sizeof(sigact));
3532 sigact.sa_handler = cpu_signal;
3533 sigaction(SIG_IPI, &sigact, NULL);
3536 static void dummy_signal(int sig)
3540 static void kvm_block_io_signals(CPUState *env)
3542 int r;
3543 sigset_t set;
3544 struct sigaction sigact;
3546 sigemptyset(&set);
3547 sigaddset(&set, SIGUSR2);
3548 sigaddset(&set, SIGIO);
3549 sigaddset(&set, SIGALRM);
3550 sigaddset(&set, SIGCHLD);
3551 sigaddset(&set, SIG_IPI);
3552 pthread_sigmask(SIG_BLOCK, &set, NULL);
3554 pthread_sigmask(SIG_BLOCK, NULL, &set);
3555 sigdelset(&set, SIG_IPI);
3557 memset(&sigact, 0, sizeof(sigact));
3558 sigact.sa_handler = dummy_signal;
3559 sigaction(SIG_IPI, &sigact, NULL);
3561 r = kvm_set_signal_mask(env, &set);
3562 if (r) {
3563 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
3564 exit(1);
3568 static void unblock_io_signals(void)
3570 sigset_t set;
3572 sigemptyset(&set);
3573 sigaddset(&set, SIGUSR2);
3574 sigaddset(&set, SIGIO);
3575 sigaddset(&set, SIGALRM);
3576 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3578 sigemptyset(&set);
3579 sigaddset(&set, SIG_IPI);
3580 pthread_sigmask(SIG_BLOCK, &set, NULL);
3583 static void qemu_signal_lock(unsigned int msecs)
3585 qemu_mutex_lock(&qemu_fair_mutex);
3587 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3588 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
3589 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3590 break;
3592 qemu_mutex_unlock(&qemu_fair_mutex);
3595 void qemu_mutex_lock_iothread(void)
3597 if (kvm_enabled()) {
3598 qemu_mutex_lock(&qemu_fair_mutex);
3599 qemu_mutex_lock(&qemu_global_mutex);
3600 qemu_mutex_unlock(&qemu_fair_mutex);
3601 } else
3602 qemu_signal_lock(100);
3605 void qemu_mutex_unlock_iothread(void)
3607 qemu_mutex_unlock(&qemu_global_mutex);
3610 static int all_vcpus_paused(void)
3612 CPUState *penv = first_cpu;
3614 while (penv) {
3615 if (!penv->stopped)
3616 return 0;
3617 penv = (CPUState *)penv->next_cpu;
3620 return 1;
3623 static void pause_all_vcpus(void)
3625 CPUState *penv = first_cpu;
3627 while (penv) {
3628 penv->stop = 1;
3629 qemu_thread_signal(penv->thread, SIG_IPI);
3630 qemu_cpu_kick(penv);
3631 penv = (CPUState *)penv->next_cpu;
3634 while (!all_vcpus_paused()) {
3635 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3636 penv = first_cpu;
3637 while (penv) {
3638 qemu_thread_signal(penv->thread, SIG_IPI);
3639 penv = (CPUState *)penv->next_cpu;
3644 static void resume_all_vcpus(void)
3646 CPUState *penv = first_cpu;
3648 while (penv) {
3649 penv->stop = 0;
3650 penv->stopped = 0;
3651 qemu_thread_signal(penv->thread, SIG_IPI);
3652 qemu_cpu_kick(penv);
3653 penv = (CPUState *)penv->next_cpu;
3657 static void tcg_init_vcpu(void *_env)
3659 CPUState *env = _env;
3660 /* share a single thread for all cpus with TCG */
3661 if (!tcg_cpu_thread) {
3662 env->thread = qemu_mallocz(sizeof(QemuThread));
3663 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3664 qemu_cond_init(env->halt_cond);
3665 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3666 while (env->created == 0)
3667 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3668 tcg_cpu_thread = env->thread;
3669 tcg_halt_cond = env->halt_cond;
3670 } else {
3671 env->thread = tcg_cpu_thread;
3672 env->halt_cond = tcg_halt_cond;
3676 static void kvm_start_vcpu(CPUState *env)
3678 env->thread = qemu_mallocz(sizeof(QemuThread));
3679 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3680 qemu_cond_init(env->halt_cond);
3681 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3682 while (env->created == 0)
3683 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3686 void qemu_init_vcpu(void *_env)
3688 CPUState *env = _env;
3690 env->nr_cores = smp_cores;
3691 env->nr_threads = smp_threads;
3692 if (kvm_enabled())
3693 kvm_start_vcpu(env);
3694 else
3695 tcg_init_vcpu(env);
3698 void qemu_notify_event(void)
3700 qemu_event_increment();
3703 void vm_stop(int reason)
3705 QemuThread me;
3706 qemu_thread_self(&me);
3708 if (!qemu_thread_equal(&me, &io_thread)) {
3709 qemu_system_vmstop_request(reason);
3711 * FIXME: should not return to device code in case
3712 * vm_stop() has been requested.
3714 if (cpu_single_env) {
3715 cpu_exit(cpu_single_env);
3716 cpu_single_env->stop = 1;
3718 return;
3720 do_vm_stop(reason);
3723 #endif
3726 #ifdef _WIN32
3727 static void host_main_loop_wait(int *timeout)
3729 int ret, ret2, i;
3730 PollingEntry *pe;
3733 /* XXX: need to suppress polling by better using win32 events */
3734 ret = 0;
3735 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3736 ret |= pe->func(pe->opaque);
3738 if (ret == 0) {
3739 int err;
3740 WaitObjects *w = &wait_objects;
3742 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3743 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3744 if (w->func[ret - WAIT_OBJECT_0])
3745 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3747 /* Check for additional signaled events */
3748 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3750 /* Check if event is signaled */
3751 ret2 = WaitForSingleObject(w->events[i], 0);
3752 if(ret2 == WAIT_OBJECT_0) {
3753 if (w->func[i])
3754 w->func[i](w->opaque[i]);
3755 } else if (ret2 == WAIT_TIMEOUT) {
3756 } else {
3757 err = GetLastError();
3758 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3761 } else if (ret == WAIT_TIMEOUT) {
3762 } else {
3763 err = GetLastError();
3764 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3768 *timeout = 0;
3770 #else
3771 static void host_main_loop_wait(int *timeout)
3774 #endif
3776 void main_loop_wait(int timeout)
3778 IOHandlerRecord *ioh;
3779 fd_set rfds, wfds, xfds;
3780 int ret, nfds;
3781 struct timeval tv;
3783 qemu_bh_update_timeout(&timeout);
3785 host_main_loop_wait(&timeout);
3787 /* poll any events */
3788 /* XXX: separate device handlers from system ones */
3789 nfds = -1;
3790 FD_ZERO(&rfds);
3791 FD_ZERO(&wfds);
3792 FD_ZERO(&xfds);
3793 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3794 if (ioh->deleted)
3795 continue;
3796 if (ioh->fd_read &&
3797 (!ioh->fd_read_poll ||
3798 ioh->fd_read_poll(ioh->opaque) != 0)) {
3799 FD_SET(ioh->fd, &rfds);
3800 if (ioh->fd > nfds)
3801 nfds = ioh->fd;
3803 if (ioh->fd_write) {
3804 FD_SET(ioh->fd, &wfds);
3805 if (ioh->fd > nfds)
3806 nfds = ioh->fd;
3810 tv.tv_sec = timeout / 1000;
3811 tv.tv_usec = (timeout % 1000) * 1000;
3813 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3815 qemu_mutex_unlock_iothread();
3816 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3817 qemu_mutex_lock_iothread();
3818 if (ret > 0) {
3819 IOHandlerRecord **pioh;
3821 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3822 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3823 ioh->fd_read(ioh->opaque);
3825 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3826 ioh->fd_write(ioh->opaque);
3830 /* remove deleted IO handlers */
3831 pioh = &first_io_handler;
3832 while (*pioh) {
3833 ioh = *pioh;
3834 if (ioh->deleted) {
3835 *pioh = ioh->next;
3836 qemu_free(ioh);
3837 } else
3838 pioh = &ioh->next;
3842 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3844 /* rearm timer, if not periodic */
3845 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3846 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3847 qemu_rearm_alarm_timer(alarm_timer);
3850 /* vm time timers */
3851 if (vm_running) {
3852 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3853 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3854 qemu_get_clock(vm_clock));
3857 /* real time timers */
3858 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3859 qemu_get_clock(rt_clock));
3861 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3862 qemu_get_clock(host_clock));
3864 /* Check bottom-halves last in case any of the earlier events triggered
3865 them. */
3866 qemu_bh_poll();
3870 static int qemu_cpu_exec(CPUState *env)
3872 int ret;
3873 #ifdef CONFIG_PROFILER
3874 int64_t ti;
3875 #endif
3877 #ifdef CONFIG_PROFILER
3878 ti = profile_getclock();
3879 #endif
3880 if (use_icount) {
3881 int64_t count;
3882 int decr;
3883 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3884 env->icount_decr.u16.low = 0;
3885 env->icount_extra = 0;
3886 count = qemu_next_deadline();
3887 count = (count + (1 << icount_time_shift) - 1)
3888 >> icount_time_shift;
3889 qemu_icount += count;
3890 decr = (count > 0xffff) ? 0xffff : count;
3891 count -= decr;
3892 env->icount_decr.u16.low = decr;
3893 env->icount_extra = count;
3895 ret = cpu_exec(env);
3896 #ifdef CONFIG_PROFILER
3897 qemu_time += profile_getclock() - ti;
3898 #endif
3899 if (use_icount) {
3900 /* Fold pending instructions back into the
3901 instruction counter, and clear the interrupt flag. */
3902 qemu_icount -= (env->icount_decr.u16.low
3903 + env->icount_extra);
3904 env->icount_decr.u32 = 0;
3905 env->icount_extra = 0;
3907 return ret;
3910 static void tcg_cpu_exec(void)
3912 int ret = 0;
3914 if (next_cpu == NULL)
3915 next_cpu = first_cpu;
3916 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3917 CPUState *env = cur_cpu = next_cpu;
3919 if (timer_alarm_pending) {
3920 timer_alarm_pending = 0;
3921 break;
3923 if (cpu_can_run(env))
3924 ret = qemu_cpu_exec(env);
3925 else if (env->stop)
3926 break;
3928 if (ret == EXCP_DEBUG) {
3929 gdb_set_stop_cpu(env);
3930 debug_requested = 1;
3931 break;
3936 static int cpu_has_work(CPUState *env)
3938 if (env->stop)
3939 return 1;
3940 if (env->stopped)
3941 return 0;
3942 if (!env->halted)
3943 return 1;
3944 if (qemu_cpu_has_work(env))
3945 return 1;
3946 return 0;
3949 static int tcg_has_work(void)
3951 CPUState *env;
3953 for (env = first_cpu; env != NULL; env = env->next_cpu)
3954 if (cpu_has_work(env))
3955 return 1;
3956 return 0;
3959 static int qemu_calculate_timeout(void)
3961 #ifndef CONFIG_IOTHREAD
3962 int timeout;
3964 if (!vm_running)
3965 timeout = 5000;
3966 else if (tcg_has_work())
3967 timeout = 0;
3968 else if (!use_icount)
3969 timeout = 5000;
3970 else {
3971 /* XXX: use timeout computed from timers */
3972 int64_t add;
3973 int64_t delta;
3974 /* Advance virtual time to the next event. */
3975 if (use_icount == 1) {
3976 /* When not using an adaptive execution frequency
3977 we tend to get badly out of sync with real time,
3978 so just delay for a reasonable amount of time. */
3979 delta = 0;
3980 } else {
3981 delta = cpu_get_icount() - cpu_get_clock();
3983 if (delta > 0) {
3984 /* If virtual time is ahead of real time then just
3985 wait for IO. */
3986 timeout = (delta / 1000000) + 1;
3987 } else {
3988 /* Wait for either IO to occur or the next
3989 timer event. */
3990 add = qemu_next_deadline();
3991 /* We advance the timer before checking for IO.
3992 Limit the amount we advance so that early IO
3993 activity won't get the guest too far ahead. */
3994 if (add > 10000000)
3995 add = 10000000;
3996 delta += add;
3997 add = (add + (1 << icount_time_shift) - 1)
3998 >> icount_time_shift;
3999 qemu_icount += add;
4000 timeout = delta / 1000000;
4001 if (timeout < 0)
4002 timeout = 0;
4006 return timeout;
4007 #else /* CONFIG_IOTHREAD */
4008 return 1000;
4009 #endif
4012 static int vm_can_run(void)
4014 if (powerdown_requested)
4015 return 0;
4016 if (reset_requested)
4017 return 0;
4018 if (shutdown_requested)
4019 return 0;
4020 if (debug_requested)
4021 return 0;
4022 return 1;
4025 qemu_irq qemu_system_powerdown;
4027 static void main_loop(void)
4029 int r;
4031 #ifdef CONFIG_IOTHREAD
4032 qemu_system_ready = 1;
4033 qemu_cond_broadcast(&qemu_system_cond);
4034 #endif
4036 for (;;) {
4037 do {
4038 #ifdef CONFIG_PROFILER
4039 int64_t ti;
4040 #endif
4041 #ifndef CONFIG_IOTHREAD
4042 tcg_cpu_exec();
4043 #endif
4044 #ifdef CONFIG_PROFILER
4045 ti = profile_getclock();
4046 #endif
4047 main_loop_wait(qemu_calculate_timeout());
4048 #ifdef CONFIG_PROFILER
4049 dev_time += profile_getclock() - ti;
4050 #endif
4051 } while (vm_can_run());
4053 if (qemu_debug_requested()) {
4054 monitor_protocol_event(QEVENT_DEBUG, NULL);
4055 vm_stop(EXCP_DEBUG);
4057 if (qemu_shutdown_requested()) {
4058 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4059 if (no_shutdown) {
4060 vm_stop(0);
4061 no_shutdown = 0;
4062 } else
4063 break;
4065 if (qemu_reset_requested()) {
4066 monitor_protocol_event(QEVENT_RESET, NULL);
4067 pause_all_vcpus();
4068 qemu_system_reset();
4069 resume_all_vcpus();
4071 if (qemu_powerdown_requested()) {
4072 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4073 qemu_irq_raise(qemu_system_powerdown);
4075 if ((r = qemu_vmstop_requested())) {
4076 monitor_protocol_event(QEVENT_STOP, NULL);
4077 vm_stop(r);
4080 pause_all_vcpus();
4083 static void version(void)
4085 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4088 static void help(int exitcode)
4090 const char *options_help =
4091 #define DEF(option, opt_arg, opt_enum, opt_help) \
4092 opt_help
4093 #define DEFHEADING(text) stringify(text) "\n"
4094 #include "qemu-options.h"
4095 #undef DEF
4096 #undef DEFHEADING
4097 #undef GEN_DOCS
4099 version();
4100 printf("usage: %s [options] [disk_image]\n"
4101 "\n"
4102 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4103 "\n"
4104 "%s\n"
4105 "During emulation, the following keys are useful:\n"
4106 "ctrl-alt-f toggle full screen\n"
4107 "ctrl-alt-n switch to virtual console 'n'\n"
4108 "ctrl-alt toggle mouse and keyboard grab\n"
4109 "\n"
4110 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4111 "qemu",
4112 options_help);
4113 exit(exitcode);
4116 #define HAS_ARG 0x0001
4118 enum {
4119 #define DEF(option, opt_arg, opt_enum, opt_help) \
4120 opt_enum,
4121 #define DEFHEADING(text)
4122 #include "qemu-options.h"
4123 #undef DEF
4124 #undef DEFHEADING
4125 #undef GEN_DOCS
4128 typedef struct QEMUOption {
4129 const char *name;
4130 int flags;
4131 int index;
4132 } QEMUOption;
4134 static const QEMUOption qemu_options[] = {
4135 { "h", 0, QEMU_OPTION_h },
4136 #define DEF(option, opt_arg, opt_enum, opt_help) \
4137 { option, opt_arg, opt_enum },
4138 #define DEFHEADING(text)
4139 #include "qemu-options.h"
4140 #undef DEF
4141 #undef DEFHEADING
4142 #undef GEN_DOCS
4143 { NULL },
4146 #ifdef HAS_AUDIO
4147 struct soundhw soundhw[] = {
4148 #ifdef HAS_AUDIO_CHOICE
4149 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4151 "pcspk",
4152 "PC speaker",
4155 { .init_isa = pcspk_audio_init }
4157 #endif
4159 #ifdef CONFIG_SB16
4161 "sb16",
4162 "Creative Sound Blaster 16",
4165 { .init_isa = SB16_init }
4167 #endif
4169 #ifdef CONFIG_CS4231A
4171 "cs4231a",
4172 "CS4231A",
4175 { .init_isa = cs4231a_init }
4177 #endif
4179 #ifdef CONFIG_ADLIB
4181 "adlib",
4182 #ifdef HAS_YMF262
4183 "Yamaha YMF262 (OPL3)",
4184 #else
4185 "Yamaha YM3812 (OPL2)",
4186 #endif
4189 { .init_isa = Adlib_init }
4191 #endif
4193 #ifdef CONFIG_GUS
4195 "gus",
4196 "Gravis Ultrasound GF1",
4199 { .init_isa = GUS_init }
4201 #endif
4203 #ifdef CONFIG_AC97
4205 "ac97",
4206 "Intel 82801AA AC97 Audio",
4209 { .init_pci = ac97_init }
4211 #endif
4213 #ifdef CONFIG_ES1370
4215 "es1370",
4216 "ENSONIQ AudioPCI ES1370",
4219 { .init_pci = es1370_init }
4221 #endif
4223 #endif /* HAS_AUDIO_CHOICE */
4225 { NULL, NULL, 0, 0, { NULL } }
4228 static void select_soundhw (const char *optarg)
4230 struct soundhw *c;
4232 if (*optarg == '?') {
4233 show_valid_cards:
4235 printf ("Valid sound card names (comma separated):\n");
4236 for (c = soundhw; c->name; ++c) {
4237 printf ("%-11s %s\n", c->name, c->descr);
4239 printf ("\n-soundhw all will enable all of the above\n");
4240 exit (*optarg != '?');
4242 else {
4243 size_t l;
4244 const char *p;
4245 char *e;
4246 int bad_card = 0;
4248 if (!strcmp (optarg, "all")) {
4249 for (c = soundhw; c->name; ++c) {
4250 c->enabled = 1;
4252 return;
4255 p = optarg;
4256 while (*p) {
4257 e = strchr (p, ',');
4258 l = !e ? strlen (p) : (size_t) (e - p);
4260 for (c = soundhw; c->name; ++c) {
4261 if (!strncmp (c->name, p, l) && !c->name[l]) {
4262 c->enabled = 1;
4263 break;
4267 if (!c->name) {
4268 if (l > 80) {
4269 fprintf (stderr,
4270 "Unknown sound card name (too big to show)\n");
4272 else {
4273 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4274 (int) l, p);
4276 bad_card = 1;
4278 p += l + (e != NULL);
4281 if (bad_card)
4282 goto show_valid_cards;
4285 #endif
4287 static void select_vgahw (const char *p)
4289 const char *opts;
4291 default_vga = 0;
4292 vga_interface_type = VGA_NONE;
4293 if (strstart(p, "std", &opts)) {
4294 vga_interface_type = VGA_STD;
4295 } else if (strstart(p, "cirrus", &opts)) {
4296 vga_interface_type = VGA_CIRRUS;
4297 } else if (strstart(p, "vmware", &opts)) {
4298 vga_interface_type = VGA_VMWARE;
4299 } else if (strstart(p, "xenfb", &opts)) {
4300 vga_interface_type = VGA_XENFB;
4301 } else if (!strstart(p, "none", &opts)) {
4302 invalid_vga:
4303 fprintf(stderr, "Unknown vga type: %s\n", p);
4304 exit(1);
4306 while (*opts) {
4307 const char *nextopt;
4309 if (strstart(opts, ",retrace=", &nextopt)) {
4310 opts = nextopt;
4311 if (strstart(opts, "dumb", &nextopt))
4312 vga_retrace_method = VGA_RETRACE_DUMB;
4313 else if (strstart(opts, "precise", &nextopt))
4314 vga_retrace_method = VGA_RETRACE_PRECISE;
4315 else goto invalid_vga;
4316 } else goto invalid_vga;
4317 opts = nextopt;
4321 #ifdef TARGET_I386
4322 static int balloon_parse(const char *arg)
4324 QemuOpts *opts;
4326 if (strcmp(arg, "none") == 0) {
4327 return 0;
4330 if (!strncmp(arg, "virtio", 6)) {
4331 if (arg[6] == ',') {
4332 /* have params -> parse them */
4333 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4334 if (!opts)
4335 return -1;
4336 } else {
4337 /* create empty opts */
4338 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4340 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4341 return 0;
4344 return -1;
4346 #endif
4348 #ifdef _WIN32
4349 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4351 exit(STATUS_CONTROL_C_EXIT);
4352 return TRUE;
4354 #endif
4356 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4358 int ret;
4360 if(strlen(str) != 36)
4361 return -1;
4363 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4364 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4365 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4367 if(ret != 16)
4368 return -1;
4370 #ifdef TARGET_I386
4371 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4372 #endif
4374 return 0;
4377 #ifndef _WIN32
4379 static void termsig_handler(int signal)
4381 qemu_system_shutdown_request();
4384 static void sigchld_handler(int signal)
4386 waitpid(-1, NULL, WNOHANG);
4389 static void sighandler_setup(void)
4391 struct sigaction act;
4393 memset(&act, 0, sizeof(act));
4394 act.sa_handler = termsig_handler;
4395 sigaction(SIGINT, &act, NULL);
4396 sigaction(SIGHUP, &act, NULL);
4397 sigaction(SIGTERM, &act, NULL);
4399 act.sa_handler = sigchld_handler;
4400 act.sa_flags = SA_NOCLDSTOP;
4401 sigaction(SIGCHLD, &act, NULL);
4404 #endif
4406 #ifdef _WIN32
4407 /* Look for support files in the same directory as the executable. */
4408 static char *find_datadir(const char *argv0)
4410 char *p;
4411 char buf[MAX_PATH];
4412 DWORD len;
4414 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4415 if (len == 0) {
4416 return NULL;
4419 buf[len] = 0;
4420 p = buf + len - 1;
4421 while (p != buf && *p != '\\')
4422 p--;
4423 *p = 0;
4424 if (access(buf, R_OK) == 0) {
4425 return qemu_strdup(buf);
4427 return NULL;
4429 #else /* !_WIN32 */
4431 /* Find a likely location for support files using the location of the binary.
4432 For installed binaries this will be "$bindir/../share/qemu". When
4433 running from the build tree this will be "$bindir/../pc-bios". */
4434 #define SHARE_SUFFIX "/share/qemu"
4435 #define BUILD_SUFFIX "/pc-bios"
4436 static char *find_datadir(const char *argv0)
4438 char *dir;
4439 char *p = NULL;
4440 char *res;
4441 char buf[PATH_MAX];
4442 size_t max_len;
4444 #if defined(__linux__)
4446 int len;
4447 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4448 if (len > 0) {
4449 buf[len] = 0;
4450 p = buf;
4453 #elif defined(__FreeBSD__)
4455 int len;
4456 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4457 if (len > 0) {
4458 buf[len] = 0;
4459 p = buf;
4462 #endif
4463 /* If we don't have any way of figuring out the actual executable
4464 location then try argv[0]. */
4465 if (!p) {
4466 p = realpath(argv0, buf);
4467 if (!p) {
4468 return NULL;
4471 dir = dirname(p);
4472 dir = dirname(dir);
4474 max_len = strlen(dir) +
4475 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4476 res = qemu_mallocz(max_len);
4477 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4478 if (access(res, R_OK)) {
4479 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4480 if (access(res, R_OK)) {
4481 qemu_free(res);
4482 res = NULL;
4486 return res;
4488 #undef SHARE_SUFFIX
4489 #undef BUILD_SUFFIX
4490 #endif
4492 char *qemu_find_file(int type, const char *name)
4494 int len;
4495 const char *subdir;
4496 char *buf;
4498 /* If name contains path separators then try it as a straight path. */
4499 if ((strchr(name, '/') || strchr(name, '\\'))
4500 && access(name, R_OK) == 0) {
4501 return qemu_strdup(name);
4503 switch (type) {
4504 case QEMU_FILE_TYPE_BIOS:
4505 subdir = "";
4506 break;
4507 case QEMU_FILE_TYPE_KEYMAP:
4508 subdir = "keymaps/";
4509 break;
4510 default:
4511 abort();
4513 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4514 buf = qemu_mallocz(len);
4515 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4516 if (access(buf, R_OK)) {
4517 qemu_free(buf);
4518 return NULL;
4520 return buf;
4523 static int device_help_func(QemuOpts *opts, void *opaque)
4525 return qdev_device_help(opts);
4528 static int device_init_func(QemuOpts *opts, void *opaque)
4530 DeviceState *dev;
4532 dev = qdev_device_add(opts);
4533 if (!dev)
4534 return -1;
4535 return 0;
4538 static int chardev_init_func(QemuOpts *opts, void *opaque)
4540 CharDriverState *chr;
4542 chr = qemu_chr_open_opts(opts, NULL);
4543 if (!chr)
4544 return -1;
4545 return 0;
4548 static int mon_init_func(QemuOpts *opts, void *opaque)
4550 CharDriverState *chr;
4551 const char *chardev;
4552 const char *mode;
4553 int flags;
4555 mode = qemu_opt_get(opts, "mode");
4556 if (mode == NULL) {
4557 mode = "readline";
4559 if (strcmp(mode, "readline") == 0) {
4560 flags = MONITOR_USE_READLINE;
4561 } else if (strcmp(mode, "control") == 0) {
4562 flags = MONITOR_USE_CONTROL;
4563 } else {
4564 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4565 exit(1);
4568 if (qemu_opt_get_bool(opts, "default", 0))
4569 flags |= MONITOR_IS_DEFAULT;
4571 chardev = qemu_opt_get(opts, "chardev");
4572 chr = qemu_chr_find(chardev);
4573 if (chr == NULL) {
4574 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4575 exit(1);
4578 monitor_init(chr, flags);
4579 return 0;
4582 static void monitor_parse(const char *optarg, const char *mode)
4584 static int monitor_device_index = 0;
4585 QemuOpts *opts;
4586 const char *p;
4587 char label[32];
4588 int def = 0;
4590 if (strstart(optarg, "chardev:", &p)) {
4591 snprintf(label, sizeof(label), "%s", p);
4592 } else {
4593 if (monitor_device_index) {
4594 snprintf(label, sizeof(label), "monitor%d",
4595 monitor_device_index);
4596 } else {
4597 snprintf(label, sizeof(label), "monitor");
4598 def = 1;
4600 opts = qemu_chr_parse_compat(label, optarg);
4601 if (!opts) {
4602 fprintf(stderr, "parse error: %s\n", optarg);
4603 exit(1);
4607 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4608 if (!opts) {
4609 fprintf(stderr, "duplicate chardev: %s\n", label);
4610 exit(1);
4612 qemu_opt_set(opts, "mode", mode);
4613 qemu_opt_set(opts, "chardev", label);
4614 if (def)
4615 qemu_opt_set(opts, "default", "on");
4616 monitor_device_index++;
4619 struct device_config {
4620 enum {
4621 DEV_USB, /* -usbdevice */
4622 DEV_BT, /* -bt */
4623 DEV_SERIAL, /* -serial */
4624 DEV_PARALLEL, /* -parallel */
4625 DEV_VIRTCON, /* -virtioconsole */
4626 DEV_DEBUGCON, /* -debugcon */
4627 } type;
4628 const char *cmdline;
4629 QTAILQ_ENTRY(device_config) next;
4631 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4633 static void add_device_config(int type, const char *cmdline)
4635 struct device_config *conf;
4637 conf = qemu_mallocz(sizeof(*conf));
4638 conf->type = type;
4639 conf->cmdline = cmdline;
4640 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4643 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4645 struct device_config *conf;
4646 int rc;
4648 QTAILQ_FOREACH(conf, &device_configs, next) {
4649 if (conf->type != type)
4650 continue;
4651 rc = func(conf->cmdline);
4652 if (0 != rc)
4653 return rc;
4655 return 0;
4658 static int serial_parse(const char *devname)
4660 static int index = 0;
4661 char label[32];
4663 if (strcmp(devname, "none") == 0)
4664 return 0;
4665 if (index == MAX_SERIAL_PORTS) {
4666 fprintf(stderr, "qemu: too many serial ports\n");
4667 exit(1);
4669 snprintf(label, sizeof(label), "serial%d", index);
4670 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4671 if (!serial_hds[index]) {
4672 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4673 devname, strerror(errno));
4674 return -1;
4676 index++;
4677 return 0;
4680 static int parallel_parse(const char *devname)
4682 static int index = 0;
4683 char label[32];
4685 if (strcmp(devname, "none") == 0)
4686 return 0;
4687 if (index == MAX_PARALLEL_PORTS) {
4688 fprintf(stderr, "qemu: too many parallel ports\n");
4689 exit(1);
4691 snprintf(label, sizeof(label), "parallel%d", index);
4692 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4693 if (!parallel_hds[index]) {
4694 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4695 devname, strerror(errno));
4696 return -1;
4698 index++;
4699 return 0;
4702 static int virtcon_parse(const char *devname)
4704 static int index = 0;
4705 char label[32];
4706 QemuOpts *bus_opts, *dev_opts;
4708 if (strcmp(devname, "none") == 0)
4709 return 0;
4710 if (index == MAX_VIRTIO_CONSOLES) {
4711 fprintf(stderr, "qemu: too many virtio consoles\n");
4712 exit(1);
4715 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4716 qemu_opt_set(bus_opts, "driver", "virtio-serial");
4718 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4719 qemu_opt_set(dev_opts, "driver", "virtconsole");
4721 snprintf(label, sizeof(label), "virtcon%d", index);
4722 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4723 if (!virtcon_hds[index]) {
4724 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4725 devname, strerror(errno));
4726 return -1;
4728 qemu_opt_set(dev_opts, "chardev", label);
4730 index++;
4731 return 0;
4734 static int debugcon_parse(const char *devname)
4736 QemuOpts *opts;
4738 if (!qemu_chr_open("debugcon", devname, NULL)) {
4739 exit(1);
4741 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4742 if (!opts) {
4743 fprintf(stderr, "qemu: already have a debugcon device\n");
4744 exit(1);
4746 qemu_opt_set(opts, "driver", "isa-debugcon");
4747 qemu_opt_set(opts, "chardev", "debugcon");
4748 return 0;
4751 static const QEMUOption *lookup_opt(int argc, char **argv,
4752 const char **poptarg, int *poptind)
4754 const QEMUOption *popt;
4755 int optind = *poptind;
4756 char *r = argv[optind];
4757 const char *optarg;
4759 optind++;
4760 /* Treat --foo the same as -foo. */
4761 if (r[1] == '-')
4762 r++;
4763 popt = qemu_options;
4764 for(;;) {
4765 if (!popt->name) {
4766 fprintf(stderr, "%s: invalid option -- '%s'\n",
4767 argv[0], r);
4768 exit(1);
4770 if (!strcmp(popt->name, r + 1))
4771 break;
4772 popt++;
4774 if (popt->flags & HAS_ARG) {
4775 if (optind >= argc) {
4776 fprintf(stderr, "%s: option '%s' requires an argument\n",
4777 argv[0], r);
4778 exit(1);
4780 optarg = argv[optind++];
4781 } else {
4782 optarg = NULL;
4785 *poptarg = optarg;
4786 *poptind = optind;
4788 return popt;
4791 int main(int argc, char **argv, char **envp)
4793 const char *gdbstub_dev = NULL;
4794 uint32_t boot_devices_bitmap = 0;
4795 int i;
4796 int snapshot, linux_boot, net_boot;
4797 const char *initrd_filename;
4798 const char *kernel_filename, *kernel_cmdline;
4799 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4800 DisplayState *ds;
4801 DisplayChangeListener *dcl;
4802 int cyls, heads, secs, translation;
4803 QemuOpts *hda_opts = NULL, *opts;
4804 int optind;
4805 const char *optarg;
4806 const char *loadvm = NULL;
4807 QEMUMachine *machine;
4808 const char *cpu_model;
4809 #ifndef _WIN32
4810 int fds[2];
4811 #endif
4812 int tb_size;
4813 const char *pid_file = NULL;
4814 const char *incoming = NULL;
4815 #ifndef _WIN32
4816 int fd = 0;
4817 struct passwd *pwd = NULL;
4818 const char *chroot_dir = NULL;
4819 const char *run_as = NULL;
4820 #endif
4821 CPUState *env;
4822 int show_vnc_port = 0;
4823 int defconfig = 1;
4825 init_clocks();
4827 qemu_errors_to_file(stderr);
4828 qemu_cache_utils_init(envp);
4830 QLIST_INIT (&vm_change_state_head);
4831 #ifndef _WIN32
4833 struct sigaction act;
4834 sigfillset(&act.sa_mask);
4835 act.sa_flags = 0;
4836 act.sa_handler = SIG_IGN;
4837 sigaction(SIGPIPE, &act, NULL);
4839 #else
4840 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4841 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4842 QEMU to run on a single CPU */
4844 HANDLE h;
4845 DWORD mask, smask;
4846 int i;
4847 h = GetCurrentProcess();
4848 if (GetProcessAffinityMask(h, &mask, &smask)) {
4849 for(i = 0; i < 32; i++) {
4850 if (mask & (1 << i))
4851 break;
4853 if (i != 32) {
4854 mask = 1 << i;
4855 SetProcessAffinityMask(h, mask);
4859 #endif
4861 module_call_init(MODULE_INIT_MACHINE);
4862 machine = find_default_machine();
4863 cpu_model = NULL;
4864 initrd_filename = NULL;
4865 ram_size = 0;
4866 snapshot = 0;
4867 kernel_filename = NULL;
4868 kernel_cmdline = "";
4869 cyls = heads = secs = 0;
4870 translation = BIOS_ATA_TRANSLATION_AUTO;
4872 for (i = 0; i < MAX_NODES; i++) {
4873 node_mem[i] = 0;
4874 node_cpumask[i] = 0;
4877 nb_numa_nodes = 0;
4878 nb_nics = 0;
4880 tb_size = 0;
4881 autostart= 1;
4883 /* first pass of option parsing */
4884 optind = 1;
4885 while (optind < argc) {
4886 if (argv[optind][0] != '-') {
4887 /* disk image */
4888 optind++;
4889 continue;
4890 } else {
4891 const QEMUOption *popt;
4893 popt = lookup_opt(argc, argv, &optarg, &optind);
4894 switch (popt->index) {
4895 case QEMU_OPTION_nodefconfig:
4896 defconfig=0;
4897 break;
4902 if (defconfig) {
4903 FILE *fp;
4904 fp = fopen(CONFIG_QEMU_CONFDIR "/qemu.conf", "r");
4905 if (fp) {
4906 if (qemu_config_parse(fp) != 0) {
4907 exit(1);
4909 fclose(fp);
4912 fp = fopen(CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf", "r");
4913 if (fp) {
4914 if (qemu_config_parse(fp) != 0) {
4915 exit(1);
4917 fclose(fp);
4920 #if defined(cpudef_setup)
4921 cpudef_setup(); /* parse cpu definitions in target config file */
4922 #endif
4924 /* second pass of option parsing */
4925 optind = 1;
4926 for(;;) {
4927 if (optind >= argc)
4928 break;
4929 if (argv[optind][0] != '-') {
4930 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4931 } else {
4932 const QEMUOption *popt;
4934 popt = lookup_opt(argc, argv, &optarg, &optind);
4935 switch(popt->index) {
4936 case QEMU_OPTION_M:
4937 machine = find_machine(optarg);
4938 if (!machine) {
4939 QEMUMachine *m;
4940 printf("Supported machines are:\n");
4941 for(m = first_machine; m != NULL; m = m->next) {
4942 if (m->alias)
4943 printf("%-10s %s (alias of %s)\n",
4944 m->alias, m->desc, m->name);
4945 printf("%-10s %s%s\n",
4946 m->name, m->desc,
4947 m->is_default ? " (default)" : "");
4949 exit(*optarg != '?');
4951 break;
4952 case QEMU_OPTION_cpu:
4953 /* hw initialization will check this */
4954 if (*optarg == '?') {
4955 /* XXX: implement xxx_cpu_list for targets that still miss it */
4956 #if defined(cpu_list_id)
4957 cpu_list_id(stdout, &fprintf, optarg);
4958 #elif defined(cpu_list)
4959 cpu_list(stdout, &fprintf); /* deprecated */
4960 #endif
4961 exit(0);
4962 } else {
4963 cpu_model = optarg;
4965 break;
4966 case QEMU_OPTION_initrd:
4967 initrd_filename = optarg;
4968 break;
4969 case QEMU_OPTION_hda:
4970 if (cyls == 0)
4971 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4972 else
4973 hda_opts = drive_add(optarg, HD_ALIAS
4974 ",cyls=%d,heads=%d,secs=%d%s",
4975 0, cyls, heads, secs,
4976 translation == BIOS_ATA_TRANSLATION_LBA ?
4977 ",trans=lba" :
4978 translation == BIOS_ATA_TRANSLATION_NONE ?
4979 ",trans=none" : "");
4980 break;
4981 case QEMU_OPTION_hdb:
4982 case QEMU_OPTION_hdc:
4983 case QEMU_OPTION_hdd:
4984 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4985 break;
4986 case QEMU_OPTION_drive:
4987 drive_add(NULL, "%s", optarg);
4988 break;
4989 case QEMU_OPTION_set:
4990 if (qemu_set_option(optarg) != 0)
4991 exit(1);
4992 break;
4993 case QEMU_OPTION_global:
4994 if (qemu_global_option(optarg) != 0)
4995 exit(1);
4996 break;
4997 case QEMU_OPTION_mtdblock:
4998 drive_add(optarg, MTD_ALIAS);
4999 break;
5000 case QEMU_OPTION_sd:
5001 drive_add(optarg, SD_ALIAS);
5002 break;
5003 case QEMU_OPTION_pflash:
5004 drive_add(optarg, PFLASH_ALIAS);
5005 break;
5006 case QEMU_OPTION_snapshot:
5007 snapshot = 1;
5008 break;
5009 case QEMU_OPTION_hdachs:
5011 const char *p;
5012 p = optarg;
5013 cyls = strtol(p, (char **)&p, 0);
5014 if (cyls < 1 || cyls > 16383)
5015 goto chs_fail;
5016 if (*p != ',')
5017 goto chs_fail;
5018 p++;
5019 heads = strtol(p, (char **)&p, 0);
5020 if (heads < 1 || heads > 16)
5021 goto chs_fail;
5022 if (*p != ',')
5023 goto chs_fail;
5024 p++;
5025 secs = strtol(p, (char **)&p, 0);
5026 if (secs < 1 || secs > 63)
5027 goto chs_fail;
5028 if (*p == ',') {
5029 p++;
5030 if (!strcmp(p, "none"))
5031 translation = BIOS_ATA_TRANSLATION_NONE;
5032 else if (!strcmp(p, "lba"))
5033 translation = BIOS_ATA_TRANSLATION_LBA;
5034 else if (!strcmp(p, "auto"))
5035 translation = BIOS_ATA_TRANSLATION_AUTO;
5036 else
5037 goto chs_fail;
5038 } else if (*p != '\0') {
5039 chs_fail:
5040 fprintf(stderr, "qemu: invalid physical CHS format\n");
5041 exit(1);
5043 if (hda_opts != NULL) {
5044 char num[16];
5045 snprintf(num, sizeof(num), "%d", cyls);
5046 qemu_opt_set(hda_opts, "cyls", num);
5047 snprintf(num, sizeof(num), "%d", heads);
5048 qemu_opt_set(hda_opts, "heads", num);
5049 snprintf(num, sizeof(num), "%d", secs);
5050 qemu_opt_set(hda_opts, "secs", num);
5051 if (translation == BIOS_ATA_TRANSLATION_LBA)
5052 qemu_opt_set(hda_opts, "trans", "lba");
5053 if (translation == BIOS_ATA_TRANSLATION_NONE)
5054 qemu_opt_set(hda_opts, "trans", "none");
5057 break;
5058 case QEMU_OPTION_numa:
5059 if (nb_numa_nodes >= MAX_NODES) {
5060 fprintf(stderr, "qemu: too many NUMA nodes\n");
5061 exit(1);
5063 numa_add(optarg);
5064 break;
5065 case QEMU_OPTION_nographic:
5066 display_type = DT_NOGRAPHIC;
5067 break;
5068 #ifdef CONFIG_CURSES
5069 case QEMU_OPTION_curses:
5070 display_type = DT_CURSES;
5071 break;
5072 #endif
5073 case QEMU_OPTION_portrait:
5074 graphic_rotate = 1;
5075 break;
5076 case QEMU_OPTION_kernel:
5077 kernel_filename = optarg;
5078 break;
5079 case QEMU_OPTION_append:
5080 kernel_cmdline = optarg;
5081 break;
5082 case QEMU_OPTION_cdrom:
5083 drive_add(optarg, CDROM_ALIAS);
5084 break;
5085 case QEMU_OPTION_boot:
5087 static const char * const params[] = {
5088 "order", "once", "menu", NULL
5090 char buf[sizeof(boot_devices)];
5091 char *standard_boot_devices;
5092 int legacy = 0;
5094 if (!strchr(optarg, '=')) {
5095 legacy = 1;
5096 pstrcpy(buf, sizeof(buf), optarg);
5097 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5098 fprintf(stderr,
5099 "qemu: unknown boot parameter '%s' in '%s'\n",
5100 buf, optarg);
5101 exit(1);
5104 if (legacy ||
5105 get_param_value(buf, sizeof(buf), "order", optarg)) {
5106 boot_devices_bitmap = parse_bootdevices(buf);
5107 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5109 if (!legacy) {
5110 if (get_param_value(buf, sizeof(buf),
5111 "once", optarg)) {
5112 boot_devices_bitmap |= parse_bootdevices(buf);
5113 standard_boot_devices = qemu_strdup(boot_devices);
5114 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5115 qemu_register_reset(restore_boot_devices,
5116 standard_boot_devices);
5118 if (get_param_value(buf, sizeof(buf),
5119 "menu", optarg)) {
5120 if (!strcmp(buf, "on")) {
5121 boot_menu = 1;
5122 } else if (!strcmp(buf, "off")) {
5123 boot_menu = 0;
5124 } else {
5125 fprintf(stderr,
5126 "qemu: invalid option value '%s'\n",
5127 buf);
5128 exit(1);
5133 break;
5134 case QEMU_OPTION_fda:
5135 case QEMU_OPTION_fdb:
5136 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5137 break;
5138 #ifdef TARGET_I386
5139 case QEMU_OPTION_no_fd_bootchk:
5140 fd_bootchk = 0;
5141 break;
5142 #endif
5143 case QEMU_OPTION_netdev:
5144 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5145 exit(1);
5147 break;
5148 case QEMU_OPTION_net:
5149 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5150 exit(1);
5152 break;
5153 #ifdef CONFIG_SLIRP
5154 case QEMU_OPTION_tftp:
5155 legacy_tftp_prefix = optarg;
5156 break;
5157 case QEMU_OPTION_bootp:
5158 legacy_bootp_filename = optarg;
5159 break;
5160 #ifndef _WIN32
5161 case QEMU_OPTION_smb:
5162 if (net_slirp_smb(optarg) < 0)
5163 exit(1);
5164 break;
5165 #endif
5166 case QEMU_OPTION_redir:
5167 if (net_slirp_redir(optarg) < 0)
5168 exit(1);
5169 break;
5170 #endif
5171 case QEMU_OPTION_bt:
5172 add_device_config(DEV_BT, optarg);
5173 break;
5174 #ifdef HAS_AUDIO
5175 case QEMU_OPTION_audio_help:
5176 AUD_help ();
5177 exit (0);
5178 break;
5179 case QEMU_OPTION_soundhw:
5180 select_soundhw (optarg);
5181 break;
5182 #endif
5183 case QEMU_OPTION_h:
5184 help(0);
5185 break;
5186 case QEMU_OPTION_version:
5187 version();
5188 exit(0);
5189 break;
5190 case QEMU_OPTION_m: {
5191 uint64_t value;
5192 char *ptr;
5194 value = strtoul(optarg, &ptr, 10);
5195 switch (*ptr) {
5196 case 0: case 'M': case 'm':
5197 value <<= 20;
5198 break;
5199 case 'G': case 'g':
5200 value <<= 30;
5201 break;
5202 default:
5203 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5204 exit(1);
5207 /* On 32-bit hosts, QEMU is limited by virtual address space */
5208 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5209 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5210 exit(1);
5212 if (value != (uint64_t)(ram_addr_t)value) {
5213 fprintf(stderr, "qemu: ram size too large\n");
5214 exit(1);
5216 ram_size = value;
5217 break;
5219 case QEMU_OPTION_d:
5221 int mask;
5222 const CPULogItem *item;
5224 mask = cpu_str_to_log_mask(optarg);
5225 if (!mask) {
5226 printf("Log items (comma separated):\n");
5227 for(item = cpu_log_items; item->mask != 0; item++) {
5228 printf("%-10s %s\n", item->name, item->help);
5230 exit(1);
5232 cpu_set_log(mask);
5234 break;
5235 case QEMU_OPTION_s:
5236 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5237 break;
5238 case QEMU_OPTION_gdb:
5239 gdbstub_dev = optarg;
5240 break;
5241 case QEMU_OPTION_L:
5242 data_dir = optarg;
5243 break;
5244 case QEMU_OPTION_bios:
5245 bios_name = optarg;
5246 break;
5247 case QEMU_OPTION_singlestep:
5248 singlestep = 1;
5249 break;
5250 case QEMU_OPTION_S:
5251 autostart = 0;
5252 break;
5253 case QEMU_OPTION_k:
5254 keyboard_layout = optarg;
5255 break;
5256 case QEMU_OPTION_localtime:
5257 rtc_utc = 0;
5258 break;
5259 case QEMU_OPTION_vga:
5260 select_vgahw (optarg);
5261 break;
5262 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5263 case QEMU_OPTION_g:
5265 const char *p;
5266 int w, h, depth;
5267 p = optarg;
5268 w = strtol(p, (char **)&p, 10);
5269 if (w <= 0) {
5270 graphic_error:
5271 fprintf(stderr, "qemu: invalid resolution or depth\n");
5272 exit(1);
5274 if (*p != 'x')
5275 goto graphic_error;
5276 p++;
5277 h = strtol(p, (char **)&p, 10);
5278 if (h <= 0)
5279 goto graphic_error;
5280 if (*p == 'x') {
5281 p++;
5282 depth = strtol(p, (char **)&p, 10);
5283 if (depth != 8 && depth != 15 && depth != 16 &&
5284 depth != 24 && depth != 32)
5285 goto graphic_error;
5286 } else if (*p == '\0') {
5287 depth = graphic_depth;
5288 } else {
5289 goto graphic_error;
5292 graphic_width = w;
5293 graphic_height = h;
5294 graphic_depth = depth;
5296 break;
5297 #endif
5298 case QEMU_OPTION_echr:
5300 char *r;
5301 term_escape_char = strtol(optarg, &r, 0);
5302 if (r == optarg)
5303 printf("Bad argument to echr\n");
5304 break;
5306 case QEMU_OPTION_monitor:
5307 monitor_parse(optarg, "readline");
5308 default_monitor = 0;
5309 break;
5310 case QEMU_OPTION_qmp:
5311 monitor_parse(optarg, "control");
5312 default_monitor = 0;
5313 break;
5314 case QEMU_OPTION_mon:
5315 opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5316 if (!opts) {
5317 fprintf(stderr, "parse error: %s\n", optarg);
5318 exit(1);
5320 default_monitor = 0;
5321 break;
5322 case QEMU_OPTION_chardev:
5323 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5324 if (!opts) {
5325 fprintf(stderr, "parse error: %s\n", optarg);
5326 exit(1);
5328 break;
5329 case QEMU_OPTION_serial:
5330 add_device_config(DEV_SERIAL, optarg);
5331 default_serial = 0;
5332 break;
5333 case QEMU_OPTION_watchdog:
5334 if (watchdog) {
5335 fprintf(stderr,
5336 "qemu: only one watchdog option may be given\n");
5337 return 1;
5339 watchdog = optarg;
5340 break;
5341 case QEMU_OPTION_watchdog_action:
5342 if (select_watchdog_action(optarg) == -1) {
5343 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5344 exit(1);
5346 break;
5347 case QEMU_OPTION_virtiocon:
5348 add_device_config(DEV_VIRTCON, optarg);
5349 default_virtcon = 0;
5350 break;
5351 case QEMU_OPTION_parallel:
5352 add_device_config(DEV_PARALLEL, optarg);
5353 default_parallel = 0;
5354 break;
5355 case QEMU_OPTION_debugcon:
5356 add_device_config(DEV_DEBUGCON, optarg);
5357 break;
5358 case QEMU_OPTION_loadvm:
5359 loadvm = optarg;
5360 break;
5361 case QEMU_OPTION_full_screen:
5362 full_screen = 1;
5363 break;
5364 #ifdef CONFIG_SDL
5365 case QEMU_OPTION_no_frame:
5366 no_frame = 1;
5367 break;
5368 case QEMU_OPTION_alt_grab:
5369 alt_grab = 1;
5370 break;
5371 case QEMU_OPTION_ctrl_grab:
5372 ctrl_grab = 1;
5373 break;
5374 case QEMU_OPTION_no_quit:
5375 no_quit = 1;
5376 break;
5377 case QEMU_OPTION_sdl:
5378 display_type = DT_SDL;
5379 break;
5380 #endif
5381 case QEMU_OPTION_pidfile:
5382 pid_file = optarg;
5383 break;
5384 #ifdef TARGET_I386
5385 case QEMU_OPTION_win2k_hack:
5386 win2k_install_hack = 1;
5387 break;
5388 case QEMU_OPTION_rtc_td_hack:
5389 rtc_td_hack = 1;
5390 break;
5391 case QEMU_OPTION_acpitable:
5392 if(acpi_table_add(optarg) < 0) {
5393 fprintf(stderr, "Wrong acpi table provided\n");
5394 exit(1);
5396 break;
5397 case QEMU_OPTION_smbios:
5398 if(smbios_entry_add(optarg) < 0) {
5399 fprintf(stderr, "Wrong smbios provided\n");
5400 exit(1);
5402 break;
5403 #endif
5404 #ifdef CONFIG_KVM
5405 case QEMU_OPTION_enable_kvm:
5406 kvm_allowed = 1;
5407 break;
5408 #endif
5409 case QEMU_OPTION_usb:
5410 usb_enabled = 1;
5411 break;
5412 case QEMU_OPTION_usbdevice:
5413 usb_enabled = 1;
5414 add_device_config(DEV_USB, optarg);
5415 break;
5416 case QEMU_OPTION_device:
5417 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5418 exit(1);
5420 break;
5421 case QEMU_OPTION_smp:
5422 smp_parse(optarg);
5423 if (smp_cpus < 1) {
5424 fprintf(stderr, "Invalid number of CPUs\n");
5425 exit(1);
5427 if (max_cpus < smp_cpus) {
5428 fprintf(stderr, "maxcpus must be equal to or greater than "
5429 "smp\n");
5430 exit(1);
5432 if (max_cpus > 255) {
5433 fprintf(stderr, "Unsupported number of maxcpus\n");
5434 exit(1);
5436 break;
5437 case QEMU_OPTION_vnc:
5438 display_type = DT_VNC;
5439 vnc_display = optarg;
5440 break;
5441 #ifdef TARGET_I386
5442 case QEMU_OPTION_no_acpi:
5443 acpi_enabled = 0;
5444 break;
5445 case QEMU_OPTION_no_hpet:
5446 no_hpet = 1;
5447 break;
5448 case QEMU_OPTION_balloon:
5449 if (balloon_parse(optarg) < 0) {
5450 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5451 exit(1);
5453 break;
5454 #endif
5455 case QEMU_OPTION_no_reboot:
5456 no_reboot = 1;
5457 break;
5458 case QEMU_OPTION_no_shutdown:
5459 no_shutdown = 1;
5460 break;
5461 case QEMU_OPTION_show_cursor:
5462 cursor_hide = 0;
5463 break;
5464 case QEMU_OPTION_uuid:
5465 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5466 fprintf(stderr, "Fail to parse UUID string."
5467 " Wrong format.\n");
5468 exit(1);
5470 break;
5471 #ifndef _WIN32
5472 case QEMU_OPTION_daemonize:
5473 daemonize = 1;
5474 break;
5475 #endif
5476 case QEMU_OPTION_option_rom:
5477 if (nb_option_roms >= MAX_OPTION_ROMS) {
5478 fprintf(stderr, "Too many option ROMs\n");
5479 exit(1);
5481 option_rom[nb_option_roms] = optarg;
5482 nb_option_roms++;
5483 break;
5484 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5485 case QEMU_OPTION_semihosting:
5486 semihosting_enabled = 1;
5487 break;
5488 #endif
5489 case QEMU_OPTION_name:
5490 qemu_name = qemu_strdup(optarg);
5492 char *p = strchr(qemu_name, ',');
5493 if (p != NULL) {
5494 *p++ = 0;
5495 if (strncmp(p, "process=", 8)) {
5496 fprintf(stderr, "Unknown subargument %s to -name", p);
5497 exit(1);
5499 p += 8;
5500 set_proc_name(p);
5503 break;
5504 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5505 case QEMU_OPTION_prom_env:
5506 if (nb_prom_envs >= MAX_PROM_ENVS) {
5507 fprintf(stderr, "Too many prom variables\n");
5508 exit(1);
5510 prom_envs[nb_prom_envs] = optarg;
5511 nb_prom_envs++;
5512 break;
5513 #endif
5514 #ifdef TARGET_ARM
5515 case QEMU_OPTION_old_param:
5516 old_param = 1;
5517 break;
5518 #endif
5519 case QEMU_OPTION_clock:
5520 configure_alarms(optarg);
5521 break;
5522 case QEMU_OPTION_startdate:
5523 configure_rtc_date_offset(optarg, 1);
5524 break;
5525 case QEMU_OPTION_rtc:
5526 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5527 if (!opts) {
5528 fprintf(stderr, "parse error: %s\n", optarg);
5529 exit(1);
5531 configure_rtc(opts);
5532 break;
5533 case QEMU_OPTION_tb_size:
5534 tb_size = strtol(optarg, NULL, 0);
5535 if (tb_size < 0)
5536 tb_size = 0;
5537 break;
5538 case QEMU_OPTION_icount:
5539 use_icount = 1;
5540 if (strcmp(optarg, "auto") == 0) {
5541 icount_time_shift = -1;
5542 } else {
5543 icount_time_shift = strtol(optarg, NULL, 0);
5545 break;
5546 case QEMU_OPTION_incoming:
5547 incoming = optarg;
5548 break;
5549 case QEMU_OPTION_nodefaults:
5550 default_serial = 0;
5551 default_parallel = 0;
5552 default_virtcon = 0;
5553 default_monitor = 0;
5554 default_vga = 0;
5555 default_net = 0;
5556 default_floppy = 0;
5557 default_cdrom = 0;
5558 default_sdcard = 0;
5559 break;
5560 #ifndef _WIN32
5561 case QEMU_OPTION_chroot:
5562 chroot_dir = optarg;
5563 break;
5564 case QEMU_OPTION_runas:
5565 run_as = optarg;
5566 break;
5567 #endif
5568 #ifdef CONFIG_XEN
5569 case QEMU_OPTION_xen_domid:
5570 xen_domid = atoi(optarg);
5571 break;
5572 case QEMU_OPTION_xen_create:
5573 xen_mode = XEN_CREATE;
5574 break;
5575 case QEMU_OPTION_xen_attach:
5576 xen_mode = XEN_ATTACH;
5577 break;
5578 #endif
5579 case QEMU_OPTION_readconfig:
5581 FILE *fp;
5582 fp = fopen(optarg, "r");
5583 if (fp == NULL) {
5584 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5585 exit(1);
5587 if (qemu_config_parse(fp) != 0) {
5588 exit(1);
5590 fclose(fp);
5591 break;
5593 case QEMU_OPTION_writeconfig:
5595 FILE *fp;
5596 if (strcmp(optarg, "-") == 0) {
5597 fp = stdout;
5598 } else {
5599 fp = fopen(optarg, "w");
5600 if (fp == NULL) {
5601 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5602 exit(1);
5605 qemu_config_write(fp);
5606 fclose(fp);
5607 break;
5613 /* If no data_dir is specified then try to find it relative to the
5614 executable path. */
5615 if (!data_dir) {
5616 data_dir = find_datadir(argv[0]);
5618 /* If all else fails use the install patch specified when building. */
5619 if (!data_dir) {
5620 data_dir = CONFIG_QEMU_SHAREDIR;
5624 * Default to max_cpus = smp_cpus, in case the user doesn't
5625 * specify a max_cpus value.
5627 if (!max_cpus)
5628 max_cpus = smp_cpus;
5630 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5631 if (smp_cpus > machine->max_cpus) {
5632 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5633 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5634 machine->max_cpus);
5635 exit(1);
5638 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5639 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5641 if (machine->no_serial) {
5642 default_serial = 0;
5644 if (machine->no_parallel) {
5645 default_parallel = 0;
5647 if (!machine->use_virtcon) {
5648 default_virtcon = 0;
5650 if (machine->no_vga) {
5651 default_vga = 0;
5653 if (machine->no_floppy) {
5654 default_floppy = 0;
5656 if (machine->no_cdrom) {
5657 default_cdrom = 0;
5659 if (machine->no_sdcard) {
5660 default_sdcard = 0;
5663 if (display_type == DT_NOGRAPHIC) {
5664 if (default_parallel)
5665 add_device_config(DEV_PARALLEL, "null");
5666 if (default_serial && default_monitor) {
5667 add_device_config(DEV_SERIAL, "mon:stdio");
5668 } else if (default_virtcon && default_monitor) {
5669 add_device_config(DEV_VIRTCON, "mon:stdio");
5670 } else {
5671 if (default_serial)
5672 add_device_config(DEV_SERIAL, "stdio");
5673 if (default_virtcon)
5674 add_device_config(DEV_VIRTCON, "stdio");
5675 if (default_monitor)
5676 monitor_parse("stdio", "readline");
5678 } else {
5679 if (default_serial)
5680 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5681 if (default_parallel)
5682 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5683 if (default_monitor)
5684 monitor_parse("vc:80Cx24C", "readline");
5685 if (default_virtcon)
5686 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5688 if (default_vga)
5689 vga_interface_type = VGA_CIRRUS;
5691 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5692 exit(1);
5694 #ifndef _WIN32
5695 if (daemonize) {
5696 pid_t pid;
5698 if (pipe(fds) == -1)
5699 exit(1);
5701 pid = fork();
5702 if (pid > 0) {
5703 uint8_t status;
5704 ssize_t len;
5706 close(fds[1]);
5708 again:
5709 len = read(fds[0], &status, 1);
5710 if (len == -1 && (errno == EINTR))
5711 goto again;
5713 if (len != 1)
5714 exit(1);
5715 else if (status == 1) {
5716 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5717 exit(1);
5718 } else
5719 exit(0);
5720 } else if (pid < 0)
5721 exit(1);
5723 close(fds[0]);
5724 qemu_set_cloexec(fds[1]);
5726 setsid();
5728 pid = fork();
5729 if (pid > 0)
5730 exit(0);
5731 else if (pid < 0)
5732 exit(1);
5734 umask(027);
5736 signal(SIGTSTP, SIG_IGN);
5737 signal(SIGTTOU, SIG_IGN);
5738 signal(SIGTTIN, SIG_IGN);
5740 #endif
5742 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5743 #ifndef _WIN32
5744 if (daemonize) {
5745 uint8_t status = 1;
5746 if (write(fds[1], &status, 1) != 1) {
5747 perror("daemonize. Writing to pipe\n");
5749 } else
5750 #endif
5751 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5752 exit(1);
5755 if (kvm_enabled()) {
5756 int ret;
5758 ret = kvm_init(smp_cpus);
5759 if (ret < 0) {
5760 fprintf(stderr, "failed to initialize KVM\n");
5761 exit(1);
5765 if (qemu_init_main_loop()) {
5766 fprintf(stderr, "qemu_init_main_loop failed\n");
5767 exit(1);
5769 linux_boot = (kernel_filename != NULL);
5771 if (!linux_boot && *kernel_cmdline != '\0') {
5772 fprintf(stderr, "-append only allowed with -kernel option\n");
5773 exit(1);
5776 if (!linux_boot && initrd_filename != NULL) {
5777 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5778 exit(1);
5781 #ifndef _WIN32
5782 /* Win32 doesn't support line-buffering and requires size >= 2 */
5783 setvbuf(stdout, NULL, _IOLBF, 0);
5784 #endif
5786 if (init_timer_alarm() < 0) {
5787 fprintf(stderr, "could not initialize alarm timer\n");
5788 exit(1);
5790 if (use_icount && icount_time_shift < 0) {
5791 use_icount = 2;
5792 /* 125MIPS seems a reasonable initial guess at the guest speed.
5793 It will be corrected fairly quickly anyway. */
5794 icount_time_shift = 3;
5795 init_icount_adjust();
5798 #ifdef _WIN32
5799 socket_init();
5800 #endif
5802 if (net_init_clients() < 0) {
5803 exit(1);
5806 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5807 net_set_boot_mask(net_boot);
5809 /* init the bluetooth world */
5810 if (foreach_device_config(DEV_BT, bt_parse))
5811 exit(1);
5813 /* init the memory */
5814 if (ram_size == 0)
5815 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5817 /* init the dynamic translator */
5818 cpu_exec_init_all(tb_size * 1024 * 1024);
5820 bdrv_init_with_whitelist();
5822 blk_mig_init();
5824 if (default_cdrom) {
5825 /* we always create the cdrom drive, even if no disk is there */
5826 drive_add(NULL, CDROM_ALIAS);
5829 if (default_floppy) {
5830 /* we always create at least one floppy */
5831 drive_add(NULL, FD_ALIAS, 0);
5834 if (default_sdcard) {
5835 /* we always create one sd slot, even if no card is in it */
5836 drive_add(NULL, SD_ALIAS);
5839 /* open the virtual block devices */
5840 if (snapshot)
5841 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5842 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5843 exit(1);
5845 vmstate_register(0, &vmstate_timers ,&timers_state);
5846 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5847 ram_load, NULL);
5849 if (nb_numa_nodes > 0) {
5850 int i;
5852 if (nb_numa_nodes > smp_cpus) {
5853 nb_numa_nodes = smp_cpus;
5856 /* If no memory size if given for any node, assume the default case
5857 * and distribute the available memory equally across all nodes
5859 for (i = 0; i < nb_numa_nodes; i++) {
5860 if (node_mem[i] != 0)
5861 break;
5863 if (i == nb_numa_nodes) {
5864 uint64_t usedmem = 0;
5866 /* On Linux, the each node's border has to be 8MB aligned,
5867 * the final node gets the rest.
5869 for (i = 0; i < nb_numa_nodes - 1; i++) {
5870 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5871 usedmem += node_mem[i];
5873 node_mem[i] = ram_size - usedmem;
5876 for (i = 0; i < nb_numa_nodes; i++) {
5877 if (node_cpumask[i] != 0)
5878 break;
5880 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5881 * must cope with this anyway, because there are BIOSes out there in
5882 * real machines which also use this scheme.
5884 if (i == nb_numa_nodes) {
5885 for (i = 0; i < smp_cpus; i++) {
5886 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5891 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5892 exit(1);
5893 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5894 exit(1);
5895 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5896 exit(1);
5897 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5898 exit(1);
5900 module_call_init(MODULE_INIT_DEVICE);
5902 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
5903 exit(0);
5905 if (watchdog) {
5906 i = select_watchdog(watchdog);
5907 if (i > 0)
5908 exit (i == 1 ? 1 : 0);
5911 if (machine->compat_props) {
5912 qdev_prop_register_global_list(machine->compat_props);
5914 qemu_add_globals();
5916 machine->init(ram_size, boot_devices,
5917 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5920 #ifndef _WIN32
5921 /* must be after terminal init, SDL library changes signal handlers */
5922 sighandler_setup();
5923 #endif
5925 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5926 for (i = 0; i < nb_numa_nodes; i++) {
5927 if (node_cpumask[i] & (1 << env->cpu_index)) {
5928 env->numa_node = i;
5933 current_machine = machine;
5935 /* init USB devices */
5936 if (usb_enabled) {
5937 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5938 exit(1);
5941 /* init generic devices */
5942 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5943 exit(1);
5945 net_check_clients();
5947 /* just use the first displaystate for the moment */
5948 ds = get_displaystate();
5950 if (display_type == DT_DEFAULT) {
5951 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5952 display_type = DT_SDL;
5953 #else
5954 display_type = DT_VNC;
5955 vnc_display = "localhost:0,to=99";
5956 show_vnc_port = 1;
5957 #endif
5961 switch (display_type) {
5962 case DT_NOGRAPHIC:
5963 break;
5964 #if defined(CONFIG_CURSES)
5965 case DT_CURSES:
5966 curses_display_init(ds, full_screen);
5967 break;
5968 #endif
5969 #if defined(CONFIG_SDL)
5970 case DT_SDL:
5971 sdl_display_init(ds, full_screen, no_frame);
5972 break;
5973 #elif defined(CONFIG_COCOA)
5974 case DT_SDL:
5975 cocoa_display_init(ds, full_screen);
5976 break;
5977 #endif
5978 case DT_VNC:
5979 vnc_display_init(ds);
5980 if (vnc_display_open(ds, vnc_display) < 0)
5981 exit(1);
5983 if (show_vnc_port) {
5984 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5986 break;
5987 default:
5988 break;
5990 dpy_resize(ds);
5992 dcl = ds->listeners;
5993 while (dcl != NULL) {
5994 if (dcl->dpy_refresh != NULL) {
5995 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5996 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5998 dcl = dcl->next;
6001 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6002 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6003 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6006 text_consoles_set_display(ds);
6008 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6009 exit(1);
6011 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6012 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6013 gdbstub_dev);
6014 exit(1);
6017 qdev_machine_creation_done();
6019 if (rom_load_all() != 0) {
6020 fprintf(stderr, "rom loading failed\n");
6021 exit(1);
6024 qemu_system_reset();
6025 if (loadvm) {
6026 if (load_vmstate(cur_mon, loadvm) < 0) {
6027 autostart = 0;
6031 if (incoming) {
6032 qemu_start_incoming_migration(incoming);
6033 } else if (autostart) {
6034 vm_start();
6037 #ifndef _WIN32
6038 if (daemonize) {
6039 uint8_t status = 0;
6040 ssize_t len;
6042 again1:
6043 len = write(fds[1], &status, 1);
6044 if (len == -1 && (errno == EINTR))
6045 goto again1;
6047 if (len != 1)
6048 exit(1);
6050 if (chdir("/")) {
6051 perror("not able to chdir to /");
6052 exit(1);
6054 TFR(fd = qemu_open("/dev/null", O_RDWR));
6055 if (fd == -1)
6056 exit(1);
6059 if (run_as) {
6060 pwd = getpwnam(run_as);
6061 if (!pwd) {
6062 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6063 exit(1);
6067 if (chroot_dir) {
6068 if (chroot(chroot_dir) < 0) {
6069 fprintf(stderr, "chroot failed\n");
6070 exit(1);
6072 if (chdir("/")) {
6073 perror("not able to chdir to /");
6074 exit(1);
6078 if (run_as) {
6079 if (setgid(pwd->pw_gid) < 0) {
6080 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6081 exit(1);
6083 if (setuid(pwd->pw_uid) < 0) {
6084 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6085 exit(1);
6087 if (setuid(0) != -1) {
6088 fprintf(stderr, "Dropping privileges failed\n");
6089 exit(1);
6093 if (daemonize) {
6094 dup2(fd, 0);
6095 dup2(fd, 1);
6096 dup2(fd, 2);
6098 close(fd);
6100 #endif
6102 main_loop();
6103 quit_timers();
6104 net_cleanup();
6106 return 0;