Merge commit '731c54f86988d3f28268f184fabfe9b2a32fb5d3' into upstream-merge
[qemu-kvm/amd-iommu.git] / vl.c
blob6b620367e0793e06199557d590a8b45b310106f5
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 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef CONFIG_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
71 #include <sys/prctl.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
76 #include "hpet.h"
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
80 #endif
81 #ifdef __sun__
82 #include <sys/stat.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
92 #include <net/if.h>
93 #include <syslog.h>
94 #include <stropts.h>
95 #endif
96 #endif
97 #endif
99 #if defined(__OpenBSD__)
100 #include <util.h>
101 #endif
103 #if defined(CONFIG_VDE)
104 #include <libvdeplug.h>
105 #endif
107 #ifdef _WIN32
108 #include <windows.h>
109 #include <mmsystem.h>
110 #endif
112 #ifdef CONFIG_SDL
113 #if defined(__APPLE__) || defined(main)
114 #include <SDL.h>
115 int qemu_main(int argc, char **argv, char **envp);
116 int main(int argc, char **argv)
118 return qemu_main(argc, argv, NULL);
120 #undef main
121 #define main qemu_main
122 #endif
123 #endif /* CONFIG_SDL */
125 #ifdef CONFIG_COCOA
126 #undef main
127 #define main qemu_main
128 #endif /* CONFIG_COCOA */
130 #include "hw/hw.h"
131 #include "hw/boards.h"
132 #include "hw/usb.h"
133 #include "hw/pcmcia.h"
134 #include "hw/pc.h"
135 #include "hw/audiodev.h"
136 #include "hw/isa.h"
137 #include "hw/baum.h"
138 #include "hw/bt.h"
139 #include "hw/watchdog.h"
140 #include "hw/smbios.h"
141 #include "hw/xen.h"
142 #include "hw/qdev.h"
143 #include "bt-host.h"
144 #include "net.h"
145 #include "monitor.h"
146 #include "console.h"
147 #include "sysemu.h"
148 #include "gdbstub.h"
149 #include "qemu-timer.h"
150 #include "qemu-char.h"
151 #include "cache-utils.h"
152 #include "block.h"
153 #include "dma.h"
154 #include "audio/audio.h"
155 #include "migration.h"
156 #include "kvm.h"
157 #include "balloon.h"
158 #include "qemu-option.h"
159 #include "qemu-config.h"
160 #include "qemu-kvm.h"
161 #include "hw/device-assignment.h"
163 #include "disas.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
171 #include "qemu-queue.h"
173 //#define DEBUG_NET
174 //#define DEBUG_SLIRP
176 #define DEFAULT_RAM_SIZE 128
178 /* Maximum number of monitor devices */
179 #define MAX_MONITOR_DEVICES 10
181 static const char *data_dir;
182 const char *bios_name = NULL;
183 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
184 to store the VM snapshots */
185 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
186 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
187 DriveInfo *extboot_drive = NULL;
188 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
189 static DisplayState *display_state;
190 DisplayType display_type = DT_DEFAULT;
191 const char* keyboard_layout = NULL;
192 ram_addr_t ram_size;
193 int nb_nics;
194 NICInfo nd_table[MAX_NICS];
195 int vm_running;
196 int autostart;
197 static int rtc_utc = 1;
198 static int rtc_date_offset = -1; /* -1 means no change */
199 int vga_interface_type = VGA_CIRRUS;
200 #ifdef TARGET_SPARC
201 int graphic_width = 1024;
202 int graphic_height = 768;
203 int graphic_depth = 8;
204 #else
205 int graphic_width = 800;
206 int graphic_height = 600;
207 int graphic_depth = 15;
208 #endif
209 static int full_screen = 0;
210 #ifdef CONFIG_SDL
211 static int no_frame = 0;
212 #endif
213 int no_quit = 0;
214 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
215 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
216 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
217 #ifdef TARGET_I386
218 int win2k_install_hack = 0;
219 int rtc_td_hack = 0;
220 #endif
221 int usb_enabled = 0;
222 int singlestep = 0;
223 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
224 int assigned_devices_index;
225 int smp_cpus = 1;
226 int max_cpus = 0;
227 int smp_cores = 1;
228 int smp_threads = 1;
229 const char *vnc_display;
230 int acpi_enabled = 1;
231 #ifdef TARGET_I386
232 int no_hpet = 0;
233 #endif
234 int fd_bootchk = 1;
235 int no_reboot = 0;
236 int no_shutdown = 0;
237 int cursor_hide = 1;
238 int graphic_rotate = 0;
239 uint8_t irq0override = 1;
240 #ifndef _WIN32
241 int daemonize = 0;
242 #endif
243 const char *watchdog;
244 const char *option_rom[MAX_OPTION_ROMS];
245 int nb_option_roms;
246 int semihosting_enabled = 0;
247 int time_drift_fix = 0;
248 unsigned int kvm_shadow_memory = 0;
249 const char *mem_path = NULL;
250 #ifdef MAP_POPULATE
251 int mem_prealloc = 1; /* force preallocation of physical target memory */
252 #endif
253 #ifdef TARGET_ARM
254 int old_param = 0;
255 #endif
256 const char *qemu_name;
257 int alt_grab = 0;
258 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
259 unsigned int nb_prom_envs = 0;
260 const char *prom_envs[MAX_PROM_ENVS];
261 #endif
262 const char *nvram = NULL;
263 int boot_menu;
265 int nb_numa_nodes;
266 uint64_t node_mem[MAX_NODES];
267 uint64_t node_cpumask[MAX_NODES];
269 static CPUState *cur_cpu;
270 static CPUState *next_cpu;
271 static int timer_alarm_pending = 1;
272 /* Conversion factor from emulated instructions to virtual clock ticks. */
273 static int icount_time_shift;
274 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
275 #define MAX_ICOUNT_SHIFT 10
276 /* Compensate for varying guest execution speed. */
277 static int64_t qemu_icount_bias;
278 static QEMUTimer *icount_rt_timer;
279 static QEMUTimer *icount_vm_timer;
280 static QEMUTimer *nographic_timer;
282 uint8_t qemu_uuid[16];
284 static QEMUBootSetHandler *boot_set_handler;
285 static void *boot_set_opaque;
287 /***********************************************************/
288 /* x86 ISA bus support */
290 target_phys_addr_t isa_mem_base = 0;
291 PicState2 *isa_pic;
293 /***********************************************************/
294 void hw_error(const char *fmt, ...)
296 va_list ap;
297 CPUState *env;
299 va_start(ap, fmt);
300 fprintf(stderr, "qemu: hardware error: ");
301 vfprintf(stderr, fmt, ap);
302 fprintf(stderr, "\n");
303 for(env = first_cpu; env != NULL; env = env->next_cpu) {
304 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
305 #ifdef TARGET_I386
306 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
307 #else
308 cpu_dump_state(env, stderr, fprintf, 0);
309 #endif
311 va_end(ap);
312 abort();
315 static void set_proc_name(const char *s)
317 #if defined(__linux__) && defined(PR_SET_NAME)
318 char name[16];
319 if (!s)
320 return;
321 name[sizeof(name) - 1] = 0;
322 strncpy(name, s, sizeof(name));
323 /* Could rewrite argv[0] too, but that's a bit more complicated.
324 This simple way is enough for `top'. */
325 prctl(PR_SET_NAME, name);
326 #endif
329 /***************/
330 /* ballooning */
332 static QEMUBalloonEvent *qemu_balloon_event;
333 void *qemu_balloon_event_opaque;
335 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
337 qemu_balloon_event = func;
338 qemu_balloon_event_opaque = opaque;
341 void qemu_balloon(ram_addr_t target)
343 if (qemu_balloon_event)
344 qemu_balloon_event(qemu_balloon_event_opaque, target);
347 ram_addr_t qemu_balloon_status(void)
349 if (qemu_balloon_event)
350 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
351 return 0;
354 /***********************************************************/
355 /* keyboard/mouse */
357 static QEMUPutKBDEvent *qemu_put_kbd_event;
358 static void *qemu_put_kbd_event_opaque;
359 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
360 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
362 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
364 qemu_put_kbd_event_opaque = opaque;
365 qemu_put_kbd_event = func;
368 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
369 void *opaque, int absolute,
370 const char *name)
372 QEMUPutMouseEntry *s, *cursor;
374 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
376 s->qemu_put_mouse_event = func;
377 s->qemu_put_mouse_event_opaque = opaque;
378 s->qemu_put_mouse_event_absolute = absolute;
379 s->qemu_put_mouse_event_name = qemu_strdup(name);
380 s->next = NULL;
382 if (!qemu_put_mouse_event_head) {
383 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
384 return s;
387 cursor = qemu_put_mouse_event_head;
388 while (cursor->next != NULL)
389 cursor = cursor->next;
391 cursor->next = s;
392 qemu_put_mouse_event_current = s;
394 return s;
397 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
399 QEMUPutMouseEntry *prev = NULL, *cursor;
401 if (!qemu_put_mouse_event_head || entry == NULL)
402 return;
404 cursor = qemu_put_mouse_event_head;
405 while (cursor != NULL && cursor != entry) {
406 prev = cursor;
407 cursor = cursor->next;
410 if (cursor == NULL) // does not exist or list empty
411 return;
412 else if (prev == NULL) { // entry is head
413 qemu_put_mouse_event_head = cursor->next;
414 if (qemu_put_mouse_event_current == entry)
415 qemu_put_mouse_event_current = cursor->next;
416 qemu_free(entry->qemu_put_mouse_event_name);
417 qemu_free(entry);
418 return;
421 prev->next = entry->next;
423 if (qemu_put_mouse_event_current == entry)
424 qemu_put_mouse_event_current = prev;
426 qemu_free(entry->qemu_put_mouse_event_name);
427 qemu_free(entry);
430 void kbd_put_keycode(int keycode)
432 if (qemu_put_kbd_event) {
433 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
437 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
439 QEMUPutMouseEvent *mouse_event;
440 void *mouse_event_opaque;
441 int width;
443 if (!qemu_put_mouse_event_current) {
444 return;
447 mouse_event =
448 qemu_put_mouse_event_current->qemu_put_mouse_event;
449 mouse_event_opaque =
450 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
452 if (mouse_event) {
453 if (graphic_rotate) {
454 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
455 width = 0x7fff;
456 else
457 width = graphic_width - 1;
458 mouse_event(mouse_event_opaque,
459 width - dy, dx, dz, buttons_state);
460 } else
461 mouse_event(mouse_event_opaque,
462 dx, dy, dz, buttons_state);
466 int kbd_mouse_is_absolute(void)
468 if (!qemu_put_mouse_event_current)
469 return 0;
471 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
474 void do_info_mice(Monitor *mon)
476 QEMUPutMouseEntry *cursor;
477 int index = 0;
479 if (!qemu_put_mouse_event_head) {
480 monitor_printf(mon, "No mouse devices connected\n");
481 return;
484 monitor_printf(mon, "Mouse devices available:\n");
485 cursor = qemu_put_mouse_event_head;
486 while (cursor != NULL) {
487 monitor_printf(mon, "%c Mouse #%d: %s\n",
488 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
489 index, cursor->qemu_put_mouse_event_name);
490 index++;
491 cursor = cursor->next;
495 void do_mouse_set(Monitor *mon, const QDict *qdict)
497 QEMUPutMouseEntry *cursor;
498 int i = 0;
499 int index = qdict_get_int(qdict, "index");
501 if (!qemu_put_mouse_event_head) {
502 monitor_printf(mon, "No mouse devices connected\n");
503 return;
506 cursor = qemu_put_mouse_event_head;
507 while (cursor != NULL && index != i) {
508 i++;
509 cursor = cursor->next;
512 if (cursor != NULL)
513 qemu_put_mouse_event_current = cursor;
514 else
515 monitor_printf(mon, "Mouse at given index not found\n");
518 /* compute with 96 bit intermediate result: (a*b)/c */
519 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
521 union {
522 uint64_t ll;
523 struct {
524 #ifdef HOST_WORDS_BIGENDIAN
525 uint32_t high, low;
526 #else
527 uint32_t low, high;
528 #endif
529 } l;
530 } u, res;
531 uint64_t rl, rh;
533 u.ll = a;
534 rl = (uint64_t)u.l.low * (uint64_t)b;
535 rh = (uint64_t)u.l.high * (uint64_t)b;
536 rh += (rl >> 32);
537 res.l.high = rh / c;
538 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
539 return res.ll;
542 /***********************************************************/
543 /* real time host monotonic timer */
545 #ifdef WIN32
547 static int64_t clock_freq;
549 static void init_get_clock(void)
551 LARGE_INTEGER freq;
552 int ret;
553 ret = QueryPerformanceFrequency(&freq);
554 if (ret == 0) {
555 fprintf(stderr, "Could not calibrate ticks\n");
556 exit(1);
558 clock_freq = freq.QuadPart;
561 static int64_t get_clock(void)
563 LARGE_INTEGER ti;
564 QueryPerformanceCounter(&ti);
565 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
568 #else
570 static int use_rt_clock;
572 static void init_get_clock(void)
574 use_rt_clock = 0;
575 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
576 || defined(__DragonFly__)
578 struct timespec ts;
579 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
580 use_rt_clock = 1;
583 #endif
586 static int64_t get_clock(void)
588 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
589 || defined(__DragonFly__)
590 if (use_rt_clock) {
591 struct timespec ts;
592 clock_gettime(CLOCK_MONOTONIC, &ts);
593 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
594 } else
595 #endif
597 /* XXX: using gettimeofday leads to problems if the date
598 changes, so it should be avoided. */
599 struct timeval tv;
600 gettimeofday(&tv, NULL);
601 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
604 #endif
606 /* Return the virtual CPU time, based on the instruction counter. */
607 static int64_t cpu_get_icount(void)
609 int64_t icount;
610 CPUState *env = cpu_single_env;;
611 icount = qemu_icount;
612 if (env) {
613 if (!can_do_io(env))
614 fprintf(stderr, "Bad clock read\n");
615 icount -= (env->icount_decr.u16.low + env->icount_extra);
617 return qemu_icount_bias + (icount << icount_time_shift);
620 /***********************************************************/
621 /* guest cycle counter */
623 typedef struct TimersState {
624 int64_t cpu_ticks_prev;
625 int64_t cpu_ticks_offset;
626 int64_t cpu_clock_offset;
627 int32_t cpu_ticks_enabled;
628 int64_t dummy;
629 } TimersState;
631 TimersState timers_state;
633 /* return the host CPU cycle counter and handle stop/restart */
634 int64_t cpu_get_ticks(void)
636 if (use_icount) {
637 return cpu_get_icount();
639 if (!timers_state.cpu_ticks_enabled) {
640 return timers_state.cpu_ticks_offset;
641 } else {
642 int64_t ticks;
643 ticks = cpu_get_real_ticks();
644 if (timers_state.cpu_ticks_prev > ticks) {
645 /* Note: non increasing ticks may happen if the host uses
646 software suspend */
647 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
649 timers_state.cpu_ticks_prev = ticks;
650 return ticks + timers_state.cpu_ticks_offset;
654 /* return the host CPU monotonic timer and handle stop/restart */
655 static int64_t cpu_get_clock(void)
657 int64_t ti;
658 if (!timers_state.cpu_ticks_enabled) {
659 return timers_state.cpu_clock_offset;
660 } else {
661 ti = get_clock();
662 return ti + timers_state.cpu_clock_offset;
666 /* enable cpu_get_ticks() */
667 void cpu_enable_ticks(void)
669 if (!timers_state.cpu_ticks_enabled) {
670 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
671 timers_state.cpu_clock_offset -= get_clock();
672 timers_state.cpu_ticks_enabled = 1;
676 /* disable cpu_get_ticks() : the clock is stopped. You must not call
677 cpu_get_ticks() after that. */
678 void cpu_disable_ticks(void)
680 if (timers_state.cpu_ticks_enabled) {
681 timers_state.cpu_ticks_offset = cpu_get_ticks();
682 timers_state.cpu_clock_offset = cpu_get_clock();
683 timers_state.cpu_ticks_enabled = 0;
687 /***********************************************************/
688 /* timers */
690 #define QEMU_TIMER_REALTIME 0
691 #define QEMU_TIMER_VIRTUAL 1
693 struct QEMUClock {
694 int type;
695 /* XXX: add frequency */
698 struct QEMUTimer {
699 QEMUClock *clock;
700 int64_t expire_time;
701 QEMUTimerCB *cb;
702 void *opaque;
703 struct QEMUTimer *next;
706 struct qemu_alarm_timer {
707 char const *name;
708 unsigned int flags;
710 int (*start)(struct qemu_alarm_timer *t);
711 void (*stop)(struct qemu_alarm_timer *t);
712 void (*rearm)(struct qemu_alarm_timer *t);
713 void *priv;
716 #define ALARM_FLAG_DYNTICKS 0x1
717 #define ALARM_FLAG_EXPIRED 0x2
719 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
721 return t && (t->flags & ALARM_FLAG_DYNTICKS);
724 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
726 if (!alarm_has_dynticks(t))
727 return;
729 t->rearm(t);
732 /* TODO: MIN_TIMER_REARM_US should be optimized */
733 #define MIN_TIMER_REARM_US 250
735 static struct qemu_alarm_timer *alarm_timer;
737 #ifdef _WIN32
739 struct qemu_alarm_win32 {
740 MMRESULT timerId;
741 unsigned int period;
742 } alarm_win32_data = {0, -1};
744 static int win32_start_timer(struct qemu_alarm_timer *t);
745 static void win32_stop_timer(struct qemu_alarm_timer *t);
746 static void win32_rearm_timer(struct qemu_alarm_timer *t);
748 #else
750 static int unix_start_timer(struct qemu_alarm_timer *t);
751 static void unix_stop_timer(struct qemu_alarm_timer *t);
753 #ifdef __linux__
755 static int dynticks_start_timer(struct qemu_alarm_timer *t);
756 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
757 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
759 static int hpet_start_timer(struct qemu_alarm_timer *t);
760 static void hpet_stop_timer(struct qemu_alarm_timer *t);
762 static int rtc_start_timer(struct qemu_alarm_timer *t);
763 static void rtc_stop_timer(struct qemu_alarm_timer *t);
765 #endif /* __linux__ */
767 #endif /* _WIN32 */
769 /* Correlation between real and virtual time is always going to be
770 fairly approximate, so ignore small variation.
771 When the guest is idle real and virtual time will be aligned in
772 the IO wait loop. */
773 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
775 static void icount_adjust(void)
777 int64_t cur_time;
778 int64_t cur_icount;
779 int64_t delta;
780 static int64_t last_delta;
781 /* If the VM is not running, then do nothing. */
782 if (!vm_running)
783 return;
785 cur_time = cpu_get_clock();
786 cur_icount = qemu_get_clock(vm_clock);
787 delta = cur_icount - cur_time;
788 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
789 if (delta > 0
790 && last_delta + ICOUNT_WOBBLE < delta * 2
791 && icount_time_shift > 0) {
792 /* The guest is getting too far ahead. Slow time down. */
793 icount_time_shift--;
795 if (delta < 0
796 && last_delta - ICOUNT_WOBBLE > delta * 2
797 && icount_time_shift < MAX_ICOUNT_SHIFT) {
798 /* The guest is getting too far behind. Speed time up. */
799 icount_time_shift++;
801 last_delta = delta;
802 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
805 static void icount_adjust_rt(void * opaque)
807 qemu_mod_timer(icount_rt_timer,
808 qemu_get_clock(rt_clock) + 1000);
809 icount_adjust();
812 static void icount_adjust_vm(void * opaque)
814 qemu_mod_timer(icount_vm_timer,
815 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
816 icount_adjust();
819 static void init_icount_adjust(void)
821 /* Have both realtime and virtual time triggers for speed adjustment.
822 The realtime trigger catches emulated time passing too slowly,
823 the virtual time trigger catches emulated time passing too fast.
824 Realtime triggers occur even when idle, so use them less frequently
825 than VM triggers. */
826 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
827 qemu_mod_timer(icount_rt_timer,
828 qemu_get_clock(rt_clock) + 1000);
829 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
830 qemu_mod_timer(icount_vm_timer,
831 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
834 static struct qemu_alarm_timer alarm_timers[] = {
835 #ifndef _WIN32
836 #ifdef __linux__
837 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
838 dynticks_stop_timer, dynticks_rearm_timer, NULL},
839 /* HPET - if available - is preferred */
840 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
841 /* ...otherwise try RTC */
842 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
843 #endif
844 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
845 #else
846 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
847 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
848 {"win32", 0, win32_start_timer,
849 win32_stop_timer, NULL, &alarm_win32_data},
850 #endif
851 {NULL, }
854 static void show_available_alarms(void)
856 int i;
858 printf("Available alarm timers, in order of precedence:\n");
859 for (i = 0; alarm_timers[i].name; i++)
860 printf("%s\n", alarm_timers[i].name);
863 static void configure_alarms(char const *opt)
865 int i;
866 int cur = 0;
867 int count = ARRAY_SIZE(alarm_timers) - 1;
868 char *arg;
869 char *name;
870 struct qemu_alarm_timer tmp;
872 if (!strcmp(opt, "?")) {
873 show_available_alarms();
874 exit(0);
877 arg = qemu_strdup(opt);
879 /* Reorder the array */
880 name = strtok(arg, ",");
881 while (name) {
882 for (i = 0; i < count && alarm_timers[i].name; i++) {
883 if (!strcmp(alarm_timers[i].name, name))
884 break;
887 if (i == count) {
888 fprintf(stderr, "Unknown clock %s\n", name);
889 goto next;
892 if (i < cur)
893 /* Ignore */
894 goto next;
896 /* Swap */
897 tmp = alarm_timers[i];
898 alarm_timers[i] = alarm_timers[cur];
899 alarm_timers[cur] = tmp;
901 cur++;
902 next:
903 name = strtok(NULL, ",");
906 qemu_free(arg);
908 if (cur) {
909 /* Disable remaining timers */
910 for (i = cur; i < count; i++)
911 alarm_timers[i].name = NULL;
912 } else {
913 show_available_alarms();
914 exit(1);
918 QEMUClock *rt_clock;
919 QEMUClock *vm_clock;
921 static QEMUTimer *active_timers[2];
923 static QEMUClock *qemu_new_clock(int type)
925 QEMUClock *clock;
926 clock = qemu_mallocz(sizeof(QEMUClock));
927 clock->type = type;
928 return clock;
931 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
933 QEMUTimer *ts;
935 ts = qemu_mallocz(sizeof(QEMUTimer));
936 ts->clock = clock;
937 ts->cb = cb;
938 ts->opaque = opaque;
939 return ts;
942 void qemu_free_timer(QEMUTimer *ts)
944 qemu_free(ts);
947 /* stop a timer, but do not dealloc it */
948 void qemu_del_timer(QEMUTimer *ts)
950 QEMUTimer **pt, *t;
952 /* NOTE: this code must be signal safe because
953 qemu_timer_expired() can be called from a signal. */
954 pt = &active_timers[ts->clock->type];
955 for(;;) {
956 t = *pt;
957 if (!t)
958 break;
959 if (t == ts) {
960 *pt = t->next;
961 break;
963 pt = &t->next;
967 /* modify the current timer so that it will be fired when current_time
968 >= expire_time. The corresponding callback will be called. */
969 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
971 QEMUTimer **pt, *t;
973 qemu_del_timer(ts);
975 /* add the timer in the sorted list */
976 /* NOTE: this code must be signal safe because
977 qemu_timer_expired() can be called from a signal. */
978 pt = &active_timers[ts->clock->type];
979 for(;;) {
980 t = *pt;
981 if (!t)
982 break;
983 if (t->expire_time > expire_time)
984 break;
985 pt = &t->next;
987 ts->expire_time = expire_time;
988 ts->next = *pt;
989 *pt = ts;
991 /* Rearm if necessary */
992 if (pt == &active_timers[ts->clock->type]) {
993 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
994 qemu_rearm_alarm_timer(alarm_timer);
996 /* Interrupt execution to force deadline recalculation. */
997 if (use_icount)
998 qemu_notify_event();
1002 int qemu_timer_pending(QEMUTimer *ts)
1004 QEMUTimer *t;
1005 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1006 if (t == ts)
1007 return 1;
1009 return 0;
1012 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1014 if (!timer_head)
1015 return 0;
1016 return (timer_head->expire_time <= current_time);
1019 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1021 QEMUTimer *ts;
1023 for(;;) {
1024 ts = *ptimer_head;
1025 if (!ts || ts->expire_time > current_time)
1026 break;
1027 /* remove timer from the list before calling the callback */
1028 *ptimer_head = ts->next;
1029 ts->next = NULL;
1031 /* run the callback (the timer list can be modified) */
1032 ts->cb(ts->opaque);
1036 int64_t qemu_get_clock(QEMUClock *clock)
1038 switch(clock->type) {
1039 case QEMU_TIMER_REALTIME:
1040 return get_clock() / 1000000;
1041 default:
1042 case QEMU_TIMER_VIRTUAL:
1043 if (use_icount) {
1044 return cpu_get_icount();
1045 } else {
1046 return cpu_get_clock();
1051 static void init_timers(void)
1053 init_get_clock();
1054 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1055 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1058 /* save a timer */
1059 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1061 uint64_t expire_time;
1063 if (qemu_timer_pending(ts)) {
1064 expire_time = ts->expire_time;
1065 } else {
1066 expire_time = -1;
1068 qemu_put_be64(f, expire_time);
1071 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1073 uint64_t expire_time;
1075 expire_time = qemu_get_be64(f);
1076 if (expire_time != -1) {
1077 qemu_mod_timer(ts, expire_time);
1078 } else {
1079 qemu_del_timer(ts);
1083 static const VMStateDescription vmstate_timers = {
1084 .name = "timer",
1085 .version_id = 2,
1086 .minimum_version_id = 1,
1087 .minimum_version_id_old = 1,
1088 .fields = (VMStateField []) {
1089 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1090 VMSTATE_INT64(dummy, TimersState),
1091 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1092 VMSTATE_END_OF_LIST()
1096 static void qemu_event_increment(void);
1098 #ifdef _WIN32
1099 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1100 DWORD_PTR dwUser, DWORD_PTR dw1,
1101 DWORD_PTR dw2)
1102 #else
1103 static void host_alarm_handler(int host_signum)
1104 #endif
1106 #if 0
1107 #define DISP_FREQ 1000
1109 static int64_t delta_min = INT64_MAX;
1110 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1111 static int count;
1112 ti = qemu_get_clock(vm_clock);
1113 if (last_clock != 0) {
1114 delta = ti - last_clock;
1115 if (delta < delta_min)
1116 delta_min = delta;
1117 if (delta > delta_max)
1118 delta_max = delta;
1119 delta_cum += delta;
1120 if (++count == DISP_FREQ) {
1121 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1122 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1123 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1124 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1125 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1126 count = 0;
1127 delta_min = INT64_MAX;
1128 delta_max = 0;
1129 delta_cum = 0;
1132 last_clock = ti;
1134 #endif
1135 if (alarm_has_dynticks(alarm_timer) ||
1136 (!use_icount &&
1137 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1138 qemu_get_clock(vm_clock))) ||
1139 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1140 qemu_get_clock(rt_clock))) {
1141 qemu_event_increment();
1142 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1144 #ifndef CONFIG_IOTHREAD
1145 if (next_cpu) {
1146 /* stop the currently executing cpu because a timer occured */
1147 cpu_exit(next_cpu);
1149 #endif
1150 timer_alarm_pending = 1;
1151 qemu_notify_event();
1155 static int64_t qemu_next_deadline(void)
1157 int64_t delta;
1159 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1160 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1161 qemu_get_clock(vm_clock);
1162 } else {
1163 /* To avoid problems with overflow limit this to 2^32. */
1164 delta = INT32_MAX;
1167 if (delta < 0)
1168 delta = 0;
1170 return delta;
1173 #if defined(__linux__) || defined(_WIN32)
1174 static uint64_t qemu_next_deadline_dyntick(void)
1176 int64_t delta;
1177 int64_t rtdelta;
1179 if (use_icount)
1180 delta = INT32_MAX;
1181 else
1182 delta = (qemu_next_deadline() + 999) / 1000;
1184 if (active_timers[QEMU_TIMER_REALTIME]) {
1185 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1186 qemu_get_clock(rt_clock))*1000;
1187 if (rtdelta < delta)
1188 delta = rtdelta;
1191 if (delta < MIN_TIMER_REARM_US)
1192 delta = MIN_TIMER_REARM_US;
1194 return delta;
1196 #endif
1198 #ifndef _WIN32
1200 /* Sets a specific flag */
1201 static int fcntl_setfl(int fd, int flag)
1203 int flags;
1205 flags = fcntl(fd, F_GETFL);
1206 if (flags == -1)
1207 return -errno;
1209 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1210 return -errno;
1212 return 0;
1215 #if defined(__linux__)
1217 #define RTC_FREQ 1024
1219 static void enable_sigio_timer(int fd)
1221 struct sigaction act;
1223 /* timer signal */
1224 sigfillset(&act.sa_mask);
1225 act.sa_flags = 0;
1226 act.sa_handler = host_alarm_handler;
1228 sigaction(SIGIO, &act, NULL);
1229 fcntl_setfl(fd, O_ASYNC);
1230 fcntl(fd, F_SETOWN, getpid());
1233 static int hpet_start_timer(struct qemu_alarm_timer *t)
1235 struct hpet_info info;
1236 int r, fd;
1238 fd = open("/dev/hpet", O_RDONLY);
1239 if (fd < 0)
1240 return -1;
1242 /* Set frequency */
1243 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1244 if (r < 0) {
1245 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1246 "error, but for better emulation accuracy type:\n"
1247 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1248 goto fail;
1251 /* Check capabilities */
1252 r = ioctl(fd, HPET_INFO, &info);
1253 if (r < 0)
1254 goto fail;
1256 /* Enable periodic mode */
1257 r = ioctl(fd, HPET_EPI, 0);
1258 if (info.hi_flags && (r < 0))
1259 goto fail;
1261 /* Enable interrupt */
1262 r = ioctl(fd, HPET_IE_ON, 0);
1263 if (r < 0)
1264 goto fail;
1266 enable_sigio_timer(fd);
1267 t->priv = (void *)(long)fd;
1269 return 0;
1270 fail:
1271 close(fd);
1272 return -1;
1275 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1277 int fd = (long)t->priv;
1279 close(fd);
1282 static int rtc_start_timer(struct qemu_alarm_timer *t)
1284 int rtc_fd;
1285 unsigned long current_rtc_freq = 0;
1287 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1288 if (rtc_fd < 0)
1289 return -1;
1290 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1291 if (current_rtc_freq != RTC_FREQ &&
1292 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1293 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1294 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1295 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1296 goto fail;
1298 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1299 fail:
1300 close(rtc_fd);
1301 return -1;
1304 enable_sigio_timer(rtc_fd);
1306 t->priv = (void *)(long)rtc_fd;
1308 return 0;
1311 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1313 int rtc_fd = (long)t->priv;
1315 close(rtc_fd);
1318 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1320 struct sigevent ev;
1321 timer_t host_timer;
1322 struct sigaction act;
1324 sigfillset(&act.sa_mask);
1325 act.sa_flags = 0;
1326 act.sa_handler = host_alarm_handler;
1328 sigaction(SIGALRM, &act, NULL);
1331 * Initialize ev struct to 0 to avoid valgrind complaining
1332 * about uninitialized data in timer_create call
1334 memset(&ev, 0, sizeof(ev));
1335 ev.sigev_value.sival_int = 0;
1336 ev.sigev_notify = SIGEV_SIGNAL;
1337 ev.sigev_signo = SIGALRM;
1339 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1340 perror("timer_create");
1342 /* disable dynticks */
1343 fprintf(stderr, "Dynamic Ticks disabled\n");
1345 return -1;
1348 t->priv = (void *)(long)host_timer;
1350 return 0;
1353 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1355 timer_t host_timer = (timer_t)(long)t->priv;
1357 timer_delete(host_timer);
1360 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1362 timer_t host_timer = (timer_t)(long)t->priv;
1363 struct itimerspec timeout;
1364 int64_t nearest_delta_us = INT64_MAX;
1365 int64_t current_us;
1367 if (!active_timers[QEMU_TIMER_REALTIME] &&
1368 !active_timers[QEMU_TIMER_VIRTUAL])
1369 return;
1371 nearest_delta_us = qemu_next_deadline_dyntick();
1373 /* check whether a timer is already running */
1374 if (timer_gettime(host_timer, &timeout)) {
1375 perror("gettime");
1376 fprintf(stderr, "Internal timer error: aborting\n");
1377 exit(1);
1379 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1380 if (current_us && current_us <= nearest_delta_us)
1381 return;
1383 timeout.it_interval.tv_sec = 0;
1384 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1385 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1386 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1387 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1388 perror("settime");
1389 fprintf(stderr, "Internal timer error: aborting\n");
1390 exit(1);
1394 #endif /* defined(__linux__) */
1396 static int unix_start_timer(struct qemu_alarm_timer *t)
1398 struct sigaction act;
1399 struct itimerval itv;
1400 int err;
1402 /* timer signal */
1403 sigfillset(&act.sa_mask);
1404 act.sa_flags = 0;
1405 act.sa_handler = host_alarm_handler;
1407 sigaction(SIGALRM, &act, NULL);
1409 itv.it_interval.tv_sec = 0;
1410 /* for i386 kernel 2.6 to get 1 ms */
1411 itv.it_interval.tv_usec = 999;
1412 itv.it_value.tv_sec = 0;
1413 itv.it_value.tv_usec = 10 * 1000;
1415 err = setitimer(ITIMER_REAL, &itv, NULL);
1416 if (err)
1417 return -1;
1419 return 0;
1422 static void unix_stop_timer(struct qemu_alarm_timer *t)
1424 struct itimerval itv;
1426 memset(&itv, 0, sizeof(itv));
1427 setitimer(ITIMER_REAL, &itv, NULL);
1430 #endif /* !defined(_WIN32) */
1433 #ifdef _WIN32
1435 static int win32_start_timer(struct qemu_alarm_timer *t)
1437 TIMECAPS tc;
1438 struct qemu_alarm_win32 *data = t->priv;
1439 UINT flags;
1441 memset(&tc, 0, sizeof(tc));
1442 timeGetDevCaps(&tc, sizeof(tc));
1444 if (data->period < tc.wPeriodMin)
1445 data->period = tc.wPeriodMin;
1447 timeBeginPeriod(data->period);
1449 flags = TIME_CALLBACK_FUNCTION;
1450 if (alarm_has_dynticks(t))
1451 flags |= TIME_ONESHOT;
1452 else
1453 flags |= TIME_PERIODIC;
1455 data->timerId = timeSetEvent(1, // interval (ms)
1456 data->period, // resolution
1457 host_alarm_handler, // function
1458 (DWORD)t, // parameter
1459 flags);
1461 if (!data->timerId) {
1462 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1463 GetLastError());
1464 timeEndPeriod(data->period);
1465 return -1;
1468 return 0;
1471 static void win32_stop_timer(struct qemu_alarm_timer *t)
1473 struct qemu_alarm_win32 *data = t->priv;
1475 timeKillEvent(data->timerId);
1476 timeEndPeriod(data->period);
1479 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1481 struct qemu_alarm_win32 *data = t->priv;
1482 uint64_t nearest_delta_us;
1484 if (!active_timers[QEMU_TIMER_REALTIME] &&
1485 !active_timers[QEMU_TIMER_VIRTUAL])
1486 return;
1488 nearest_delta_us = qemu_next_deadline_dyntick();
1489 nearest_delta_us /= 1000;
1491 timeKillEvent(data->timerId);
1493 data->timerId = timeSetEvent(1,
1494 data->period,
1495 host_alarm_handler,
1496 (DWORD)t,
1497 TIME_ONESHOT | TIME_PERIODIC);
1499 if (!data->timerId) {
1500 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1501 GetLastError());
1503 timeEndPeriod(data->period);
1504 exit(1);
1508 #endif /* _WIN32 */
1510 static int init_timer_alarm(void)
1512 struct qemu_alarm_timer *t = NULL;
1513 int i, err = -1;
1515 for (i = 0; alarm_timers[i].name; i++) {
1516 t = &alarm_timers[i];
1518 err = t->start(t);
1519 if (!err)
1520 break;
1523 if (err) {
1524 err = -ENOENT;
1525 goto fail;
1528 alarm_timer = t;
1530 return 0;
1532 fail:
1533 return err;
1536 static void quit_timers(void)
1538 alarm_timer->stop(alarm_timer);
1539 alarm_timer = NULL;
1542 /***********************************************************/
1543 /* host time/date access */
1544 void qemu_get_timedate(struct tm *tm, int offset)
1546 time_t ti;
1547 struct tm *ret;
1549 time(&ti);
1550 ti += offset;
1551 if (rtc_date_offset == -1) {
1552 if (rtc_utc)
1553 ret = gmtime(&ti);
1554 else
1555 ret = localtime(&ti);
1556 } else {
1557 ti -= rtc_date_offset;
1558 ret = gmtime(&ti);
1561 memcpy(tm, ret, sizeof(struct tm));
1564 int qemu_timedate_diff(struct tm *tm)
1566 time_t seconds;
1568 if (rtc_date_offset == -1)
1569 if (rtc_utc)
1570 seconds = mktimegm(tm);
1571 else
1572 seconds = mktime(tm);
1573 else
1574 seconds = mktimegm(tm) + rtc_date_offset;
1576 return seconds - time(NULL);
1579 #ifdef _WIN32
1580 static void socket_cleanup(void)
1582 WSACleanup();
1585 static int socket_init(void)
1587 WSADATA Data;
1588 int ret, err;
1590 ret = WSAStartup(MAKEWORD(2,2), &Data);
1591 if (ret != 0) {
1592 err = WSAGetLastError();
1593 fprintf(stderr, "WSAStartup: %d\n", err);
1594 return -1;
1596 atexit(socket_cleanup);
1597 return 0;
1599 #endif
1601 /***********************************************************/
1602 /* Bluetooth support */
1603 static int nb_hcis;
1604 static int cur_hci;
1605 static struct HCIInfo *hci_table[MAX_NICS];
1607 static struct bt_vlan_s {
1608 struct bt_scatternet_s net;
1609 int id;
1610 struct bt_vlan_s *next;
1611 } *first_bt_vlan;
1613 /* find or alloc a new bluetooth "VLAN" */
1614 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1616 struct bt_vlan_s **pvlan, *vlan;
1617 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1618 if (vlan->id == id)
1619 return &vlan->net;
1621 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1622 vlan->id = id;
1623 pvlan = &first_bt_vlan;
1624 while (*pvlan != NULL)
1625 pvlan = &(*pvlan)->next;
1626 *pvlan = vlan;
1627 return &vlan->net;
1630 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1634 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1636 return -ENOTSUP;
1639 static struct HCIInfo null_hci = {
1640 .cmd_send = null_hci_send,
1641 .sco_send = null_hci_send,
1642 .acl_send = null_hci_send,
1643 .bdaddr_set = null_hci_addr_set,
1646 struct HCIInfo *qemu_next_hci(void)
1648 if (cur_hci == nb_hcis)
1649 return &null_hci;
1651 return hci_table[cur_hci++];
1654 static struct HCIInfo *hci_init(const char *str)
1656 char *endp;
1657 struct bt_scatternet_s *vlan = 0;
1659 if (!strcmp(str, "null"))
1660 /* null */
1661 return &null_hci;
1662 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1663 /* host[:hciN] */
1664 return bt_host_hci(str[4] ? str + 5 : "hci0");
1665 else if (!strncmp(str, "hci", 3)) {
1666 /* hci[,vlan=n] */
1667 if (str[3]) {
1668 if (!strncmp(str + 3, ",vlan=", 6)) {
1669 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1670 if (*endp)
1671 vlan = 0;
1673 } else
1674 vlan = qemu_find_bt_vlan(0);
1675 if (vlan)
1676 return bt_new_hci(vlan);
1679 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1681 return 0;
1684 static int bt_hci_parse(const char *str)
1686 struct HCIInfo *hci;
1687 bdaddr_t bdaddr;
1689 if (nb_hcis >= MAX_NICS) {
1690 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1691 return -1;
1694 hci = hci_init(str);
1695 if (!hci)
1696 return -1;
1698 bdaddr.b[0] = 0x52;
1699 bdaddr.b[1] = 0x54;
1700 bdaddr.b[2] = 0x00;
1701 bdaddr.b[3] = 0x12;
1702 bdaddr.b[4] = 0x34;
1703 bdaddr.b[5] = 0x56 + nb_hcis;
1704 hci->bdaddr_set(hci, bdaddr.b);
1706 hci_table[nb_hcis++] = hci;
1708 return 0;
1711 static void bt_vhci_add(int vlan_id)
1713 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1715 if (!vlan->slave)
1716 fprintf(stderr, "qemu: warning: adding a VHCI to "
1717 "an empty scatternet %i\n", vlan_id);
1719 bt_vhci_init(bt_new_hci(vlan));
1722 static struct bt_device_s *bt_device_add(const char *opt)
1724 struct bt_scatternet_s *vlan;
1725 int vlan_id = 0;
1726 char *endp = strstr(opt, ",vlan=");
1727 int len = (endp ? endp - opt : strlen(opt)) + 1;
1728 char devname[10];
1730 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1732 if (endp) {
1733 vlan_id = strtol(endp + 6, &endp, 0);
1734 if (*endp) {
1735 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1736 return 0;
1740 vlan = qemu_find_bt_vlan(vlan_id);
1742 if (!vlan->slave)
1743 fprintf(stderr, "qemu: warning: adding a slave device to "
1744 "an empty scatternet %i\n", vlan_id);
1746 if (!strcmp(devname, "keyboard"))
1747 return bt_keyboard_init(vlan);
1749 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1750 return 0;
1753 static int bt_parse(const char *opt)
1755 const char *endp, *p;
1756 int vlan;
1758 if (strstart(opt, "hci", &endp)) {
1759 if (!*endp || *endp == ',') {
1760 if (*endp)
1761 if (!strstart(endp, ",vlan=", 0))
1762 opt = endp + 1;
1764 return bt_hci_parse(opt);
1766 } else if (strstart(opt, "vhci", &endp)) {
1767 if (!*endp || *endp == ',') {
1768 if (*endp) {
1769 if (strstart(endp, ",vlan=", &p)) {
1770 vlan = strtol(p, (char **) &endp, 0);
1771 if (*endp) {
1772 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1773 return 1;
1775 } else {
1776 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1777 return 1;
1779 } else
1780 vlan = 0;
1782 bt_vhci_add(vlan);
1783 return 0;
1785 } else if (strstart(opt, "device:", &endp))
1786 return !bt_device_add(endp);
1788 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1789 return 1;
1792 /***********************************************************/
1793 /* QEMU Block devices */
1795 #define HD_ALIAS "index=%d,media=disk"
1796 #define CDROM_ALIAS "index=2,media=cdrom"
1797 #define FD_ALIAS "index=%d,if=floppy"
1798 #define PFLASH_ALIAS "if=pflash"
1799 #define MTD_ALIAS "if=mtd"
1800 #define SD_ALIAS "index=0,if=sd"
1802 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1804 va_list ap;
1805 char optstr[1024];
1806 QemuOpts *opts;
1808 va_start(ap, fmt);
1809 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1810 va_end(ap);
1812 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1813 if (!opts) {
1814 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1815 __FUNCTION__, optstr);
1816 return NULL;
1818 if (file)
1819 qemu_opt_set(opts, "file", file);
1820 return opts;
1823 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1825 DriveInfo *dinfo;
1827 /* seek interface, bus and unit */
1829 QTAILQ_FOREACH(dinfo, &drives, next) {
1830 if (dinfo->type == type &&
1831 dinfo->bus == bus &&
1832 dinfo->unit == unit)
1833 return dinfo;
1836 return NULL;
1839 DriveInfo *drive_get_by_id(const char *id)
1841 DriveInfo *dinfo;
1843 QTAILQ_FOREACH(dinfo, &drives, next) {
1844 if (strcmp(id, dinfo->id))
1845 continue;
1846 return dinfo;
1848 return NULL;
1851 int drive_get_max_bus(BlockInterfaceType type)
1853 int max_bus;
1854 DriveInfo *dinfo;
1856 max_bus = -1;
1857 QTAILQ_FOREACH(dinfo, &drives, next) {
1858 if(dinfo->type == type &&
1859 dinfo->bus > max_bus)
1860 max_bus = dinfo->bus;
1862 return max_bus;
1865 const char *drive_get_serial(BlockDriverState *bdrv)
1867 DriveInfo *dinfo;
1869 QTAILQ_FOREACH(dinfo, &drives, next) {
1870 if (dinfo->bdrv == bdrv)
1871 return dinfo->serial;
1874 return "\0";
1877 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1879 DriveInfo *dinfo;
1881 QTAILQ_FOREACH(dinfo, &drives, next) {
1882 if (dinfo->bdrv == bdrv)
1883 return dinfo->onerror;
1886 return BLOCK_ERR_STOP_ENOSPC;
1889 static void bdrv_format_print(void *opaque, const char *name)
1891 fprintf(stderr, " %s", name);
1894 void drive_uninit(BlockDriverState *bdrv)
1896 DriveInfo *dinfo;
1898 QTAILQ_FOREACH(dinfo, &drives, next) {
1899 if (dinfo->bdrv != bdrv)
1900 continue;
1901 qemu_opts_del(dinfo->opts);
1902 QTAILQ_REMOVE(&drives, dinfo, next);
1903 qemu_free(dinfo);
1904 break;
1908 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1909 int *fatal_error)
1911 const char *buf;
1912 const char *file = NULL;
1913 char devname[128];
1914 const char *serial;
1915 const char *mediastr = "";
1916 BlockInterfaceType type;
1917 enum { MEDIA_DISK, MEDIA_CDROM } media;
1918 int bus_id, unit_id;
1919 int cyls, heads, secs, translation;
1920 BlockDriver *drv = NULL;
1921 QEMUMachine *machine = opaque;
1922 int max_devs;
1923 int index;
1924 int cache;
1925 int aio = 0;
1926 int bdrv_flags, onerror;
1927 const char *devaddr;
1928 DriveInfo *dinfo;
1929 int is_extboot = 0;
1930 int snapshot = 0;
1932 *fatal_error = 1;
1934 translation = BIOS_ATA_TRANSLATION_AUTO;
1935 cache = 1;
1937 if (machine && machine->use_scsi) {
1938 type = IF_SCSI;
1939 max_devs = MAX_SCSI_DEVS;
1940 pstrcpy(devname, sizeof(devname), "scsi");
1941 } else {
1942 type = IF_IDE;
1943 max_devs = MAX_IDE_DEVS;
1944 pstrcpy(devname, sizeof(devname), "ide");
1946 media = MEDIA_DISK;
1948 /* extract parameters */
1949 bus_id = qemu_opt_get_number(opts, "bus", 0);
1950 unit_id = qemu_opt_get_number(opts, "unit", -1);
1951 index = qemu_opt_get_number(opts, "index", -1);
1953 cyls = qemu_opt_get_number(opts, "cyls", 0);
1954 heads = qemu_opt_get_number(opts, "heads", 0);
1955 secs = qemu_opt_get_number(opts, "secs", 0);
1957 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1959 file = qemu_opt_get(opts, "file");
1960 serial = qemu_opt_get(opts, "serial");
1962 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1963 pstrcpy(devname, sizeof(devname), buf);
1964 if (!strcmp(buf, "ide")) {
1965 type = IF_IDE;
1966 max_devs = MAX_IDE_DEVS;
1967 } else if (!strcmp(buf, "scsi")) {
1968 type = IF_SCSI;
1969 max_devs = MAX_SCSI_DEVS;
1970 } else if (!strcmp(buf, "floppy")) {
1971 type = IF_FLOPPY;
1972 max_devs = 0;
1973 } else if (!strcmp(buf, "pflash")) {
1974 type = IF_PFLASH;
1975 max_devs = 0;
1976 } else if (!strcmp(buf, "mtd")) {
1977 type = IF_MTD;
1978 max_devs = 0;
1979 } else if (!strcmp(buf, "sd")) {
1980 type = IF_SD;
1981 max_devs = 0;
1982 } else if (!strcmp(buf, "virtio")) {
1983 type = IF_VIRTIO;
1984 max_devs = 0;
1985 } else if (!strcmp(buf, "xen")) {
1986 type = IF_XEN;
1987 max_devs = 0;
1988 } else if (!strcmp(buf, "none")) {
1989 type = IF_NONE;
1990 max_devs = 0;
1991 } else {
1992 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1993 return NULL;
1997 if (cyls || heads || secs) {
1998 if (cyls < 1 || cyls > 16383) {
1999 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2000 return NULL;
2002 if (heads < 1 || heads > 16) {
2003 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2004 return NULL;
2006 if (secs < 1 || secs > 63) {
2007 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2008 return NULL;
2012 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2013 if (!cyls) {
2014 fprintf(stderr,
2015 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2016 buf);
2017 return NULL;
2019 if (!strcmp(buf, "none"))
2020 translation = BIOS_ATA_TRANSLATION_NONE;
2021 else if (!strcmp(buf, "lba"))
2022 translation = BIOS_ATA_TRANSLATION_LBA;
2023 else if (!strcmp(buf, "auto"))
2024 translation = BIOS_ATA_TRANSLATION_AUTO;
2025 else {
2026 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2027 return NULL;
2031 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2032 if (!strcmp(buf, "disk")) {
2033 media = MEDIA_DISK;
2034 } else if (!strcmp(buf, "cdrom")) {
2035 if (cyls || secs || heads) {
2036 fprintf(stderr,
2037 "qemu: '%s' invalid physical CHS format\n", buf);
2038 return NULL;
2040 media = MEDIA_CDROM;
2041 } else {
2042 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2043 return NULL;
2047 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2048 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2049 cache = 0;
2050 else if (!strcmp(buf, "writethrough"))
2051 cache = 1;
2052 else if (!strcmp(buf, "writeback"))
2053 cache = 2;
2054 else {
2055 fprintf(stderr, "qemu: invalid cache option\n");
2056 return NULL;
2060 #ifdef CONFIG_LINUX_AIO
2061 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2062 if (!strcmp(buf, "threads"))
2063 aio = 0;
2064 else if (!strcmp(buf, "native"))
2065 aio = 1;
2066 else {
2067 fprintf(stderr, "qemu: invalid aio option\n");
2068 return NULL;
2071 #endif
2073 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2074 if (strcmp(buf, "?") == 0) {
2075 fprintf(stderr, "qemu: Supported formats:");
2076 bdrv_iterate_format(bdrv_format_print, NULL);
2077 fprintf(stderr, "\n");
2078 return NULL;
2080 drv = bdrv_find_format(buf);
2081 if (!drv) {
2082 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2083 return NULL;
2087 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
2088 if (is_extboot && extboot_drive) {
2089 fprintf(stderr, "qemu: two bootable drives specified\n");
2090 return NULL;
2093 onerror = BLOCK_ERR_STOP_ENOSPC;
2094 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2095 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2096 fprintf(stderr, "werror is no supported by this format\n");
2097 return NULL;
2099 if (!strcmp(buf, "ignore"))
2100 onerror = BLOCK_ERR_IGNORE;
2101 else if (!strcmp(buf, "enospc"))
2102 onerror = BLOCK_ERR_STOP_ENOSPC;
2103 else if (!strcmp(buf, "stop"))
2104 onerror = BLOCK_ERR_STOP_ANY;
2105 else if (!strcmp(buf, "report"))
2106 onerror = BLOCK_ERR_REPORT;
2107 else {
2108 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2109 return NULL;
2113 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2114 if (type != IF_VIRTIO) {
2115 fprintf(stderr, "addr is not supported\n");
2116 return NULL;
2120 /* compute bus and unit according index */
2122 if (index != -1) {
2123 if (bus_id != 0 || unit_id != -1) {
2124 fprintf(stderr,
2125 "qemu: index cannot be used with bus and unit\n");
2126 return NULL;
2128 if (max_devs == 0)
2130 unit_id = index;
2131 bus_id = 0;
2132 } else {
2133 unit_id = index % max_devs;
2134 bus_id = index / max_devs;
2138 /* if user doesn't specify a unit_id,
2139 * try to find the first free
2142 if (unit_id == -1) {
2143 unit_id = 0;
2144 while (drive_get(type, bus_id, unit_id) != NULL) {
2145 unit_id++;
2146 if (max_devs && unit_id >= max_devs) {
2147 unit_id -= max_devs;
2148 bus_id++;
2153 /* check unit id */
2155 if (max_devs && unit_id >= max_devs) {
2156 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2157 unit_id, max_devs - 1);
2158 return NULL;
2162 * ignore multiple definitions
2165 if (drive_get(type, bus_id, unit_id) != NULL) {
2166 *fatal_error = 0;
2167 return NULL;
2170 /* init */
2172 dinfo = qemu_mallocz(sizeof(*dinfo));
2173 if ((buf = qemu_opts_id(opts)) != NULL) {
2174 dinfo->id = qemu_strdup(buf);
2175 } else {
2176 /* no id supplied -> create one */
2177 dinfo->id = qemu_mallocz(32);
2178 if (type == IF_IDE || type == IF_SCSI)
2179 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2180 if (max_devs)
2181 snprintf(dinfo->id, 32, "%s%i%s%i",
2182 devname, bus_id, mediastr, unit_id);
2183 else
2184 snprintf(dinfo->id, 32, "%s%s%i",
2185 devname, mediastr, unit_id);
2187 dinfo->bdrv = bdrv_new(dinfo->id);
2188 dinfo->devaddr = devaddr;
2189 dinfo->type = type;
2190 dinfo->bus = bus_id;
2191 dinfo->unit = unit_id;
2192 dinfo->onerror = onerror;
2193 dinfo->opts = opts;
2194 if (serial)
2195 strncpy(dinfo->serial, serial, sizeof(serial));
2196 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2197 if (is_extboot) {
2198 extboot_drive = dinfo;
2201 switch(type) {
2202 case IF_IDE:
2203 case IF_SCSI:
2204 case IF_XEN:
2205 case IF_NONE:
2206 switch(media) {
2207 case MEDIA_DISK:
2208 if (cyls != 0) {
2209 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2210 bdrv_set_translation_hint(dinfo->bdrv, translation);
2212 break;
2213 case MEDIA_CDROM:
2214 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2215 break;
2217 break;
2218 case IF_SD:
2219 /* FIXME: This isn't really a floppy, but it's a reasonable
2220 approximation. */
2221 case IF_FLOPPY:
2222 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2223 break;
2224 case IF_PFLASH:
2225 case IF_MTD:
2226 break;
2227 case IF_VIRTIO:
2228 /* add virtio block device */
2229 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2230 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2231 qemu_opt_set(opts, "drive", dinfo->id);
2232 if (devaddr)
2233 qemu_opt_set(opts, "addr", devaddr);
2234 break;
2235 case IF_COUNT:
2236 abort();
2238 if (!file) {
2239 *fatal_error = 0;
2240 return NULL;
2242 bdrv_flags = 0;
2243 if (snapshot) {
2244 bdrv_flags |= BDRV_O_SNAPSHOT;
2245 cache = 2; /* always use write-back with snapshot */
2247 if (cache == 0) /* no caching */
2248 bdrv_flags |= BDRV_O_NOCACHE;
2249 else if (cache == 2) /* write-back */
2250 bdrv_flags |= BDRV_O_CACHE_WB;
2252 if (aio == 1) {
2253 bdrv_flags |= BDRV_O_NATIVE_AIO;
2254 } else {
2255 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2258 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2259 fprintf(stderr, "qemu: could not open disk image %s\n",
2260 file);
2261 return NULL;
2264 if (bdrv_key_required(dinfo->bdrv))
2265 autostart = 0;
2266 *fatal_error = 0;
2267 return dinfo;
2270 static int drive_init_func(QemuOpts *opts, void *opaque)
2272 QEMUMachine *machine = opaque;
2273 int fatal_error = 0;
2275 if (drive_init(opts, machine, &fatal_error) == NULL) {
2276 if (fatal_error)
2277 return 1;
2279 return 0;
2282 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2284 if (NULL == qemu_opt_get(opts, "snapshot")) {
2285 qemu_opt_set(opts, "snapshot", "on");
2287 return 0;
2290 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2292 boot_set_handler = func;
2293 boot_set_opaque = opaque;
2296 int qemu_boot_set(const char *boot_devices)
2298 if (!boot_set_handler) {
2299 return -EINVAL;
2301 return boot_set_handler(boot_set_opaque, boot_devices);
2304 static int parse_bootdevices(char *devices)
2306 /* We just do some generic consistency checks */
2307 const char *p;
2308 int bitmap = 0;
2310 for (p = devices; *p != '\0'; p++) {
2311 /* Allowed boot devices are:
2312 * a-b: floppy disk drives
2313 * c-f: IDE disk drives
2314 * g-m: machine implementation dependant drives
2315 * n-p: network devices
2316 * It's up to each machine implementation to check if the given boot
2317 * devices match the actual hardware implementation and firmware
2318 * features.
2320 if (*p < 'a' || *p > 'p') {
2321 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2322 exit(1);
2324 if (bitmap & (1 << (*p - 'a'))) {
2325 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2326 exit(1);
2328 bitmap |= 1 << (*p - 'a');
2330 return bitmap;
2333 static void restore_boot_devices(void *opaque)
2335 char *standard_boot_devices = opaque;
2337 qemu_boot_set(standard_boot_devices);
2339 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2340 qemu_free(standard_boot_devices);
2343 static void numa_add(const char *optarg)
2345 char option[128];
2346 char *endptr;
2347 unsigned long long value, endvalue;
2348 int nodenr;
2350 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2351 if (!strcmp(option, "node")) {
2352 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2353 nodenr = nb_numa_nodes;
2354 } else {
2355 nodenr = strtoull(option, NULL, 10);
2358 if (get_param_value(option, 128, "mem", optarg) == 0) {
2359 node_mem[nodenr] = 0;
2360 } else {
2361 value = strtoull(option, &endptr, 0);
2362 switch (*endptr) {
2363 case 0: case 'M': case 'm':
2364 value <<= 20;
2365 break;
2366 case 'G': case 'g':
2367 value <<= 30;
2368 break;
2370 node_mem[nodenr] = value;
2372 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2373 node_cpumask[nodenr] = 0;
2374 } else {
2375 value = strtoull(option, &endptr, 10);
2376 if (value >= 64) {
2377 value = 63;
2378 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2379 } else {
2380 if (*endptr == '-') {
2381 endvalue = strtoull(endptr+1, &endptr, 10);
2382 if (endvalue >= 63) {
2383 endvalue = 62;
2384 fprintf(stderr,
2385 "only 63 CPUs in NUMA mode supported.\n");
2387 value = (1 << (endvalue + 1)) - (1 << value);
2388 } else {
2389 value = 1 << value;
2392 node_cpumask[nodenr] = value;
2394 nb_numa_nodes++;
2396 return;
2399 static void smp_parse(const char *optarg)
2401 int smp, sockets = 0, threads = 0, cores = 0;
2402 char *endptr;
2403 char option[128];
2405 smp = strtoul(optarg, &endptr, 10);
2406 if (endptr != optarg) {
2407 if (*endptr == ',') {
2408 endptr++;
2411 if (get_param_value(option, 128, "sockets", endptr) != 0)
2412 sockets = strtoull(option, NULL, 10);
2413 if (get_param_value(option, 128, "cores", endptr) != 0)
2414 cores = strtoull(option, NULL, 10);
2415 if (get_param_value(option, 128, "threads", endptr) != 0)
2416 threads = strtoull(option, NULL, 10);
2417 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2418 max_cpus = strtoull(option, NULL, 10);
2420 /* compute missing values, prefer sockets over cores over threads */
2421 if (smp == 0 || sockets == 0) {
2422 sockets = sockets > 0 ? sockets : 1;
2423 cores = cores > 0 ? cores : 1;
2424 threads = threads > 0 ? threads : 1;
2425 if (smp == 0) {
2426 smp = cores * threads * sockets;
2427 } else {
2428 sockets = smp / (cores * threads);
2430 } else {
2431 if (cores == 0) {
2432 threads = threads > 0 ? threads : 1;
2433 cores = smp / (sockets * threads);
2434 } else {
2435 if (sockets == 0) {
2436 sockets = smp / (cores * threads);
2437 } else {
2438 threads = smp / (cores * sockets);
2442 smp_cpus = smp;
2443 smp_cores = cores > 0 ? cores : 1;
2444 smp_threads = threads > 0 ? threads : 1;
2445 if (max_cpus == 0)
2446 max_cpus = smp_cpus;
2449 /***********************************************************/
2450 /* USB devices */
2452 static void usb_msd_password_cb(void *opaque, int err)
2454 USBDevice *dev = opaque;
2456 if (!err)
2457 usb_device_attach(dev);
2458 else
2459 dev->info->handle_destroy(dev);
2462 static struct {
2463 const char *name;
2464 const char *qdev;
2465 } usbdevs[] = {
2467 .name = "mouse",
2468 .qdev = "QEMU USB Mouse",
2470 .name = "tablet",
2471 .qdev = "QEMU USB Tablet",
2473 .name = "keyboard",
2474 .qdev = "QEMU USB Keyboard",
2476 .name = "wacom-tablet",
2477 .qdev = "QEMU PenPartner Tablet",
2481 static int usb_device_add(const char *devname, int is_hotplug)
2483 const char *p;
2484 USBBus *bus = usb_bus_find(-1 /* any */);
2485 USBDevice *dev = NULL;
2486 int i;
2488 if (!usb_enabled)
2489 return -1;
2491 /* simple devices which don't need extra care */
2492 for (i = 0; i < ARRAY_SIZE(usbdevs); i++) {
2493 if (strcmp(devname, usbdevs[i].name) != 0)
2494 continue;
2495 dev = usb_create_simple(bus, usbdevs[i].qdev);
2496 goto done;
2499 /* the other ones */
2500 if (strstart(devname, "host:", &p)) {
2501 dev = usb_host_device_open(p);
2502 } else if (strstart(devname, "disk:", &p)) {
2503 BlockDriverState *bs;
2505 dev = usb_msd_init(p);
2506 if (!dev)
2507 return -1;
2508 bs = usb_msd_get_bdrv(dev);
2509 if (bdrv_key_required(bs)) {
2510 autostart = 0;
2511 if (is_hotplug) {
2512 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2513 dev);
2514 return 0;
2517 } else if (strstart(devname, "serial:", &p)) {
2518 dev = usb_serial_init(p);
2519 #ifdef CONFIG_BRLAPI
2520 } else if (!strcmp(devname, "braille")) {
2521 dev = usb_baum_init();
2522 #endif
2523 } else if (strstart(devname, "net:", &p)) {
2524 int nic = nb_nics;
2526 if (net_client_init(NULL, "nic", p) < 0)
2527 return -1;
2528 nd_table[nic].model = "usb";
2529 dev = usb_net_init(&nd_table[nic]);
2530 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2531 dev = usb_bt_init(devname[2] ? hci_init(p) :
2532 bt_new_hci(qemu_find_bt_vlan(0)));
2533 } else {
2534 return -1;
2536 if (!dev)
2537 return -1;
2539 done:
2540 return 0;
2543 static int usb_device_del(const char *devname)
2545 int bus_num, addr;
2546 const char *p;
2548 if (strstart(devname, "host:", &p))
2549 return usb_host_device_close(p);
2551 if (!usb_enabled)
2552 return -1;
2554 p = strchr(devname, '.');
2555 if (!p)
2556 return -1;
2557 bus_num = strtoul(devname, NULL, 0);
2558 addr = strtoul(p + 1, NULL, 0);
2560 return usb_device_delete_addr(bus_num, addr);
2563 static int usb_parse(const char *cmdline)
2565 return usb_device_add(cmdline, 0);
2568 void do_usb_add(Monitor *mon, const QDict *qdict)
2570 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2573 void do_usb_del(Monitor *mon, const QDict *qdict)
2575 usb_device_del(qdict_get_str(qdict, "devname"));
2578 /***********************************************************/
2579 /* PCMCIA/Cardbus */
2581 static struct pcmcia_socket_entry_s {
2582 PCMCIASocket *socket;
2583 struct pcmcia_socket_entry_s *next;
2584 } *pcmcia_sockets = 0;
2586 void pcmcia_socket_register(PCMCIASocket *socket)
2588 struct pcmcia_socket_entry_s *entry;
2590 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2591 entry->socket = socket;
2592 entry->next = pcmcia_sockets;
2593 pcmcia_sockets = entry;
2596 void pcmcia_socket_unregister(PCMCIASocket *socket)
2598 struct pcmcia_socket_entry_s *entry, **ptr;
2600 ptr = &pcmcia_sockets;
2601 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2602 if (entry->socket == socket) {
2603 *ptr = entry->next;
2604 qemu_free(entry);
2608 void pcmcia_info(Monitor *mon)
2610 struct pcmcia_socket_entry_s *iter;
2612 if (!pcmcia_sockets)
2613 monitor_printf(mon, "No PCMCIA sockets\n");
2615 for (iter = pcmcia_sockets; iter; iter = iter->next)
2616 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2617 iter->socket->attached ? iter->socket->card_string :
2618 "Empty");
2621 /***********************************************************/
2622 /* register display */
2624 struct DisplayAllocator default_allocator = {
2625 defaultallocator_create_displaysurface,
2626 defaultallocator_resize_displaysurface,
2627 defaultallocator_free_displaysurface
2630 void register_displaystate(DisplayState *ds)
2632 DisplayState **s;
2633 s = &display_state;
2634 while (*s != NULL)
2635 s = &(*s)->next;
2636 ds->next = NULL;
2637 *s = ds;
2640 DisplayState *get_displaystate(void)
2642 return display_state;
2645 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2647 if(ds->allocator == &default_allocator) ds->allocator = da;
2648 return ds->allocator;
2651 /* dumb display */
2653 static void dumb_display_init(void)
2655 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2656 ds->allocator = &default_allocator;
2657 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2658 register_displaystate(ds);
2661 /***********************************************************/
2662 /* I/O handling */
2664 typedef struct IOHandlerRecord {
2665 int fd;
2666 IOCanRWHandler *fd_read_poll;
2667 IOHandler *fd_read;
2668 IOHandler *fd_write;
2669 int deleted;
2670 void *opaque;
2671 /* temporary data */
2672 struct pollfd *ufd;
2673 struct IOHandlerRecord *next;
2674 } IOHandlerRecord;
2676 static IOHandlerRecord *first_io_handler;
2678 /* XXX: fd_read_poll should be suppressed, but an API change is
2679 necessary in the character devices to suppress fd_can_read(). */
2680 int qemu_set_fd_handler2(int fd,
2681 IOCanRWHandler *fd_read_poll,
2682 IOHandler *fd_read,
2683 IOHandler *fd_write,
2684 void *opaque)
2686 IOHandlerRecord **pioh, *ioh;
2688 if (!fd_read && !fd_write) {
2689 pioh = &first_io_handler;
2690 for(;;) {
2691 ioh = *pioh;
2692 if (ioh == NULL)
2693 break;
2694 if (ioh->fd == fd) {
2695 ioh->deleted = 1;
2696 break;
2698 pioh = &ioh->next;
2700 } else {
2701 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2702 if (ioh->fd == fd)
2703 goto found;
2705 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2706 ioh->next = first_io_handler;
2707 first_io_handler = ioh;
2708 found:
2709 ioh->fd = fd;
2710 ioh->fd_read_poll = fd_read_poll;
2711 ioh->fd_read = fd_read;
2712 ioh->fd_write = fd_write;
2713 ioh->opaque = opaque;
2714 ioh->deleted = 0;
2716 qemu_notify_event();
2717 return 0;
2720 int qemu_set_fd_handler(int fd,
2721 IOHandler *fd_read,
2722 IOHandler *fd_write,
2723 void *opaque)
2725 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2728 #ifdef _WIN32
2729 /***********************************************************/
2730 /* Polling handling */
2732 typedef struct PollingEntry {
2733 PollingFunc *func;
2734 void *opaque;
2735 struct PollingEntry *next;
2736 } PollingEntry;
2738 static PollingEntry *first_polling_entry;
2740 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2742 PollingEntry **ppe, *pe;
2743 pe = qemu_mallocz(sizeof(PollingEntry));
2744 pe->func = func;
2745 pe->opaque = opaque;
2746 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2747 *ppe = pe;
2748 return 0;
2751 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2753 PollingEntry **ppe, *pe;
2754 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2755 pe = *ppe;
2756 if (pe->func == func && pe->opaque == opaque) {
2757 *ppe = pe->next;
2758 qemu_free(pe);
2759 break;
2764 /***********************************************************/
2765 /* Wait objects support */
2766 typedef struct WaitObjects {
2767 int num;
2768 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2769 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2770 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2771 } WaitObjects;
2773 static WaitObjects wait_objects = {0};
2775 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2777 WaitObjects *w = &wait_objects;
2779 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2780 return -1;
2781 w->events[w->num] = handle;
2782 w->func[w->num] = func;
2783 w->opaque[w->num] = opaque;
2784 w->num++;
2785 return 0;
2788 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2790 int i, found;
2791 WaitObjects *w = &wait_objects;
2793 found = 0;
2794 for (i = 0; i < w->num; i++) {
2795 if (w->events[i] == handle)
2796 found = 1;
2797 if (found) {
2798 w->events[i] = w->events[i + 1];
2799 w->func[i] = w->func[i + 1];
2800 w->opaque[i] = w->opaque[i + 1];
2803 if (found)
2804 w->num--;
2806 #endif
2808 /***********************************************************/
2809 /* ram save/restore */
2811 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2812 #define RAM_SAVE_FLAG_COMPRESS 0x02
2813 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2814 #define RAM_SAVE_FLAG_PAGE 0x08
2815 #define RAM_SAVE_FLAG_EOS 0x10
2817 static int is_dup_page(uint8_t *page, uint8_t ch)
2819 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2820 uint32_t *array = (uint32_t *)page;
2821 int i;
2823 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2824 if (array[i] != val)
2825 return 0;
2828 return 1;
2831 static int ram_save_block(QEMUFile *f)
2833 static ram_addr_t current_addr = 0;
2834 ram_addr_t saved_addr = current_addr;
2835 ram_addr_t addr = 0;
2836 int found = 0;
2838 while (addr < last_ram_offset) {
2839 if (kvm_enabled() && current_addr == 0) {
2840 int r;
2841 r = kvm_update_dirty_pages_log();
2842 if (r) {
2843 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
2844 qemu_file_set_error(f);
2845 return 0;
2848 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2849 uint8_t *p;
2851 cpu_physical_memory_reset_dirty(current_addr,
2852 current_addr + TARGET_PAGE_SIZE,
2853 MIGRATION_DIRTY_FLAG);
2855 p = qemu_get_ram_ptr(current_addr);
2857 if (is_dup_page(p, *p)) {
2858 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2859 qemu_put_byte(f, *p);
2860 } else {
2861 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2862 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2865 found = 1;
2866 break;
2868 addr += TARGET_PAGE_SIZE;
2869 current_addr = (saved_addr + addr) % last_ram_offset;
2872 return found;
2875 static uint64_t bytes_transferred = 0;
2877 static ram_addr_t ram_save_remaining(void)
2879 ram_addr_t addr;
2880 ram_addr_t count = 0;
2882 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2883 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2884 count++;
2887 return count;
2890 uint64_t ram_bytes_remaining(void)
2892 return ram_save_remaining() * TARGET_PAGE_SIZE;
2895 uint64_t ram_bytes_transferred(void)
2897 return bytes_transferred;
2900 uint64_t ram_bytes_total(void)
2902 return last_ram_offset;
2905 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
2907 ram_addr_t addr;
2908 uint64_t bytes_transferred_last;
2909 double bwidth = 0;
2910 uint64_t expected_time = 0;
2912 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2913 qemu_file_set_error(f);
2914 return 0;
2917 if (stage == 1) {
2918 /* Make sure all dirty bits are set */
2919 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2920 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2921 cpu_physical_memory_set_dirty(addr);
2924 /* Enable dirty memory tracking */
2925 cpu_physical_memory_set_dirty_tracking(1);
2927 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2930 bytes_transferred_last = bytes_transferred;
2931 bwidth = get_clock();
2933 while (!qemu_file_rate_limit(f)) {
2934 int ret;
2936 ret = ram_save_block(f);
2937 bytes_transferred += ret * TARGET_PAGE_SIZE;
2938 if (ret == 0) /* no more blocks */
2939 break;
2942 bwidth = get_clock() - bwidth;
2943 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2945 /* if we haven't transferred anything this round, force expected_time to a
2946 * a very high value, but without crashing */
2947 if (bwidth == 0)
2948 bwidth = 0.000001;
2950 /* try transferring iterative blocks of memory */
2952 if (stage == 3) {
2954 /* flush all remaining blocks regardless of rate limiting */
2955 while (ram_save_block(f) != 0) {
2956 bytes_transferred += TARGET_PAGE_SIZE;
2958 cpu_physical_memory_set_dirty_tracking(0);
2961 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2963 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2965 return (stage == 2) && (expected_time <= migrate_max_downtime());
2968 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2970 ram_addr_t addr;
2971 int flags;
2973 if (version_id != 3)
2974 return -EINVAL;
2976 do {
2977 addr = qemu_get_be64(f);
2979 flags = addr & ~TARGET_PAGE_MASK;
2980 addr &= TARGET_PAGE_MASK;
2982 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2983 if (addr != last_ram_offset)
2984 return -EINVAL;
2987 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2988 uint8_t ch = qemu_get_byte(f);
2989 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2990 #ifndef _WIN32
2991 if (ch == 0 &&
2992 (!kvm_enabled() || kvm_has_sync_mmu())) {
2993 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2995 #endif
2996 } else if (flags & RAM_SAVE_FLAG_PAGE)
2997 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2998 } while (!(flags & RAM_SAVE_FLAG_EOS));
3000 return 0;
3003 void qemu_service_io(void)
3005 qemu_notify_event();
3008 /***********************************************************/
3009 /* bottom halves (can be seen as timers which expire ASAP) */
3011 struct QEMUBH {
3012 QEMUBHFunc *cb;
3013 void *opaque;
3014 int scheduled;
3015 int idle;
3016 int deleted;
3017 QEMUBH *next;
3020 static QEMUBH *first_bh = NULL;
3022 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3024 QEMUBH *bh;
3025 bh = qemu_mallocz(sizeof(QEMUBH));
3026 bh->cb = cb;
3027 bh->opaque = opaque;
3028 bh->next = first_bh;
3029 first_bh = bh;
3030 return bh;
3033 int qemu_bh_poll(void)
3035 QEMUBH *bh, **bhp;
3036 int ret;
3038 ret = 0;
3039 for (bh = first_bh; bh; bh = bh->next) {
3040 if (!bh->deleted && bh->scheduled) {
3041 bh->scheduled = 0;
3042 if (!bh->idle)
3043 ret = 1;
3044 bh->idle = 0;
3045 bh->cb(bh->opaque);
3049 /* remove deleted bhs */
3050 bhp = &first_bh;
3051 while (*bhp) {
3052 bh = *bhp;
3053 if (bh->deleted) {
3054 *bhp = bh->next;
3055 qemu_free(bh);
3056 } else
3057 bhp = &bh->next;
3060 return ret;
3063 void qemu_bh_schedule_idle(QEMUBH *bh)
3065 if (bh->scheduled)
3066 return;
3067 bh->scheduled = 1;
3068 bh->idle = 1;
3071 void qemu_bh_schedule(QEMUBH *bh)
3073 if (bh->scheduled)
3074 return;
3075 bh->scheduled = 1;
3076 bh->idle = 0;
3077 /* stop the currently executing CPU to execute the BH ASAP */
3078 qemu_notify_event();
3081 void qemu_bh_cancel(QEMUBH *bh)
3083 bh->scheduled = 0;
3086 void qemu_bh_delete(QEMUBH *bh)
3088 bh->scheduled = 0;
3089 bh->deleted = 1;
3092 static void qemu_bh_update_timeout(int *timeout)
3094 QEMUBH *bh;
3096 for (bh = first_bh; bh; bh = bh->next) {
3097 if (!bh->deleted && bh->scheduled) {
3098 if (bh->idle) {
3099 /* idle bottom halves will be polled at least
3100 * every 10ms */
3101 *timeout = MIN(10, *timeout);
3102 } else {
3103 /* non-idle bottom halves will be executed
3104 * immediately */
3105 *timeout = 0;
3106 break;
3112 /***********************************************************/
3113 /* machine registration */
3115 static QEMUMachine *first_machine = NULL;
3116 QEMUMachine *current_machine = NULL;
3118 int qemu_register_machine(QEMUMachine *m)
3120 QEMUMachine **pm;
3121 pm = &first_machine;
3122 while (*pm != NULL)
3123 pm = &(*pm)->next;
3124 m->next = NULL;
3125 *pm = m;
3126 return 0;
3129 static QEMUMachine *find_machine(const char *name)
3131 QEMUMachine *m;
3133 for(m = first_machine; m != NULL; m = m->next) {
3134 if (!strcmp(m->name, name))
3135 return m;
3136 if (m->alias && !strcmp(m->alias, name))
3137 return m;
3139 return NULL;
3142 static QEMUMachine *find_default_machine(void)
3144 QEMUMachine *m;
3146 for(m = first_machine; m != NULL; m = m->next) {
3147 if (m->is_default) {
3148 return m;
3151 return NULL;
3154 /***********************************************************/
3155 /* main execution loop */
3157 static void gui_update(void *opaque)
3159 uint64_t interval = GUI_REFRESH_INTERVAL;
3160 DisplayState *ds = opaque;
3161 DisplayChangeListener *dcl = ds->listeners;
3163 dpy_refresh(ds);
3165 while (dcl != NULL) {
3166 if (dcl->gui_timer_interval &&
3167 dcl->gui_timer_interval < interval)
3168 interval = dcl->gui_timer_interval;
3169 dcl = dcl->next;
3171 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3174 static void nographic_update(void *opaque)
3176 uint64_t interval = GUI_REFRESH_INTERVAL;
3178 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3181 struct vm_change_state_entry {
3182 VMChangeStateHandler *cb;
3183 void *opaque;
3184 QLIST_ENTRY (vm_change_state_entry) entries;
3187 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3189 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3190 void *opaque)
3192 VMChangeStateEntry *e;
3194 e = qemu_mallocz(sizeof (*e));
3196 e->cb = cb;
3197 e->opaque = opaque;
3198 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3199 return e;
3202 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3204 QLIST_REMOVE (e, entries);
3205 qemu_free (e);
3208 static void vm_state_notify(int running, int reason)
3210 VMChangeStateEntry *e;
3212 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3213 e->cb(e->opaque, running, reason);
3217 static void resume_all_vcpus(void);
3218 static void pause_all_vcpus(void);
3220 void vm_start(void)
3222 if (!vm_running) {
3223 cpu_enable_ticks();
3224 vm_running = 1;
3225 vm_state_notify(1, 0);
3226 qemu_rearm_alarm_timer(alarm_timer);
3227 resume_all_vcpus();
3231 /* reset/shutdown handler */
3233 typedef struct QEMUResetEntry {
3234 QTAILQ_ENTRY(QEMUResetEntry) entry;
3235 QEMUResetHandler *func;
3236 void *opaque;
3237 } QEMUResetEntry;
3239 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3240 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3241 static int reset_requested;
3242 static int shutdown_requested;
3243 static int powerdown_requested;
3244 static int debug_requested;
3245 static int vmstop_requested;
3247 int qemu_no_shutdown(void)
3249 int r = no_shutdown;
3250 no_shutdown = 0;
3251 return r;
3254 int qemu_shutdown_requested(void)
3256 int r = shutdown_requested;
3257 shutdown_requested = 0;
3258 return r;
3261 int qemu_reset_requested(void)
3263 int r = reset_requested;
3264 reset_requested = 0;
3265 return r;
3268 int qemu_powerdown_requested(void)
3270 int r = powerdown_requested;
3271 powerdown_requested = 0;
3272 return r;
3275 static int qemu_debug_requested(void)
3277 int r = debug_requested;
3278 debug_requested = 0;
3279 return r;
3282 static int qemu_vmstop_requested(void)
3284 int r = vmstop_requested;
3285 vmstop_requested = 0;
3286 return r;
3289 static void do_vm_stop(int reason)
3291 if (vm_running) {
3292 cpu_disable_ticks();
3293 vm_running = 0;
3294 pause_all_vcpus();
3295 vm_state_notify(0, reason);
3299 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3301 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3303 re->func = func;
3304 re->opaque = opaque;
3305 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3308 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3310 QEMUResetEntry *re;
3312 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3313 if (re->func == func && re->opaque == opaque) {
3314 QTAILQ_REMOVE(&reset_handlers, re, entry);
3315 qemu_free(re);
3316 return;
3321 void qemu_system_reset(void)
3323 QEMUResetEntry *re, *nre;
3325 /* reset all devices */
3326 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3327 re->func(re->opaque);
3331 void qemu_system_reset_request(void)
3333 if (no_reboot) {
3334 shutdown_requested = 1;
3335 } else {
3336 reset_requested = 1;
3338 if (cpu_single_env) {
3339 cpu_single_env->stopped = 1;
3341 qemu_notify_event();
3344 void qemu_system_shutdown_request(void)
3346 shutdown_requested = 1;
3347 qemu_notify_event();
3350 void qemu_system_powerdown_request(void)
3352 powerdown_requested = 1;
3353 qemu_notify_event();
3356 #ifdef CONFIG_IOTHREAD
3357 static void qemu_system_vmstop_request(int reason)
3359 vmstop_requested = reason;
3360 qemu_notify_event();
3362 #endif
3364 #ifndef _WIN32
3365 static int io_thread_fd = -1;
3367 static void qemu_event_increment(void)
3369 static const char byte = 0;
3371 if (io_thread_fd == -1)
3372 return;
3374 write(io_thread_fd, &byte, sizeof(byte));
3377 static void qemu_event_read(void *opaque)
3379 int fd = (unsigned long)opaque;
3380 ssize_t len;
3382 /* Drain the notify pipe */
3383 do {
3384 char buffer[512];
3385 len = read(fd, buffer, sizeof(buffer));
3386 } while ((len == -1 && errno == EINTR) || len > 0);
3389 static int qemu_event_init(void)
3391 int err;
3392 int fds[2];
3394 err = pipe(fds);
3395 if (err == -1)
3396 return -errno;
3398 err = fcntl_setfl(fds[0], O_NONBLOCK);
3399 if (err < 0)
3400 goto fail;
3402 err = fcntl_setfl(fds[1], O_NONBLOCK);
3403 if (err < 0)
3404 goto fail;
3406 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3407 (void *)(unsigned long)fds[0]);
3409 io_thread_fd = fds[1];
3410 return 0;
3412 fail:
3413 close(fds[0]);
3414 close(fds[1]);
3415 return err;
3417 #else
3418 HANDLE qemu_event_handle;
3420 static void dummy_event_handler(void *opaque)
3424 static int qemu_event_init(void)
3426 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3427 if (!qemu_event_handle) {
3428 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3429 return -1;
3431 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3432 return 0;
3435 static void qemu_event_increment(void)
3437 if (!SetEvent(qemu_event_handle)) {
3438 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3439 GetLastError());
3440 exit (1);
3443 #endif
3445 static int cpu_can_run(CPUState *env)
3447 if (env->stop)
3448 return 0;
3449 if (env->stopped)
3450 return 0;
3451 return 1;
3454 #ifndef CONFIG_IOTHREAD
3455 static int qemu_init_main_loop(void)
3457 return qemu_event_init();
3460 void qemu_init_vcpu(void *_env)
3462 CPUState *env = _env;
3464 if (kvm_enabled())
3465 kvm_init_vcpu(env);
3466 env->nr_cores = smp_cores;
3467 env->nr_threads = smp_threads;
3468 return;
3471 int qemu_cpu_self(void *env)
3473 return 1;
3476 static void resume_all_vcpus(void)
3480 static void pause_all_vcpus(void)
3484 void qemu_cpu_kick(void *env)
3486 return;
3489 void qemu_notify_event(void)
3491 CPUState *env = cpu_single_env;
3493 if (kvm_enabled()) {
3494 qemu_kvm_notify_work();
3495 return;
3497 if (env) {
3498 cpu_exit(env);
3502 #ifdef KVM_UPSTREAM
3503 #define qemu_mutex_lock_iothread() do { } while (0)
3504 #define qemu_mutex_unlock_iothread() do { } while (0)
3505 #endif
3507 void vm_stop(int reason)
3509 do_vm_stop(reason);
3512 #else /* CONFIG_IOTHREAD */
3514 #include "qemu-thread.h"
3516 QemuMutex qemu_global_mutex;
3517 static QemuMutex qemu_fair_mutex;
3519 static QemuThread io_thread;
3521 static QemuThread *tcg_cpu_thread;
3522 static QemuCond *tcg_halt_cond;
3524 static int qemu_system_ready;
3525 /* cpu creation */
3526 static QemuCond qemu_cpu_cond;
3527 /* system init */
3528 static QemuCond qemu_system_cond;
3529 static QemuCond qemu_pause_cond;
3531 static void block_io_signals(void);
3532 static void unblock_io_signals(void);
3533 static int tcg_has_work(void);
3535 static int qemu_init_main_loop(void)
3537 int ret;
3539 ret = qemu_event_init();
3540 if (ret)
3541 return ret;
3543 qemu_cond_init(&qemu_pause_cond);
3544 qemu_mutex_init(&qemu_fair_mutex);
3545 qemu_mutex_init(&qemu_global_mutex);
3546 qemu_mutex_lock(&qemu_global_mutex);
3548 unblock_io_signals();
3549 qemu_thread_self(&io_thread);
3551 return 0;
3554 static void qemu_wait_io_event(CPUState *env)
3556 while (!tcg_has_work())
3557 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3559 qemu_mutex_unlock(&qemu_global_mutex);
3562 * Users of qemu_global_mutex can be starved, having no chance
3563 * to acquire it since this path will get to it first.
3564 * So use another lock to provide fairness.
3566 qemu_mutex_lock(&qemu_fair_mutex);
3567 qemu_mutex_unlock(&qemu_fair_mutex);
3569 qemu_mutex_lock(&qemu_global_mutex);
3570 if (env->stop) {
3571 env->stop = 0;
3572 env->stopped = 1;
3573 qemu_cond_signal(&qemu_pause_cond);
3577 static int qemu_cpu_exec(CPUState *env);
3579 static void *kvm_cpu_thread_fn(void *arg)
3581 CPUState *env = arg;
3583 block_io_signals();
3584 qemu_thread_self(env->thread);
3585 if (kvm_enabled())
3586 kvm_init_vcpu(env);
3588 /* signal CPU creation */
3589 qemu_mutex_lock(&qemu_global_mutex);
3590 env->created = 1;
3591 qemu_cond_signal(&qemu_cpu_cond);
3593 /* and wait for machine initialization */
3594 while (!qemu_system_ready)
3595 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3597 while (1) {
3598 if (cpu_can_run(env))
3599 qemu_cpu_exec(env);
3600 qemu_wait_io_event(env);
3603 return NULL;
3606 static void tcg_cpu_exec(void);
3608 static void *tcg_cpu_thread_fn(void *arg)
3610 CPUState *env = arg;
3612 block_io_signals();
3613 qemu_thread_self(env->thread);
3615 /* signal CPU creation */
3616 qemu_mutex_lock(&qemu_global_mutex);
3617 for (env = first_cpu; env != NULL; env = env->next_cpu)
3618 env->created = 1;
3619 qemu_cond_signal(&qemu_cpu_cond);
3621 /* and wait for machine initialization */
3622 while (!qemu_system_ready)
3623 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3625 while (1) {
3626 tcg_cpu_exec();
3627 qemu_wait_io_event(cur_cpu);
3630 return NULL;
3633 void qemu_cpu_kick(void *_env)
3635 CPUState *env = _env;
3636 qemu_cond_broadcast(env->halt_cond);
3637 if (kvm_enabled())
3638 qemu_thread_signal(env->thread, SIGUSR1);
3641 int qemu_cpu_self(void *env)
3643 return (cpu_single_env != NULL);
3646 static void cpu_signal(int sig)
3648 if (cpu_single_env)
3649 cpu_exit(cpu_single_env);
3652 static void block_io_signals(void)
3654 sigset_t set;
3655 struct sigaction sigact;
3657 sigemptyset(&set);
3658 sigaddset(&set, SIGUSR2);
3659 sigaddset(&set, SIGIO);
3660 sigaddset(&set, SIGALRM);
3661 pthread_sigmask(SIG_BLOCK, &set, NULL);
3663 sigemptyset(&set);
3664 sigaddset(&set, SIGUSR1);
3665 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3667 memset(&sigact, 0, sizeof(sigact));
3668 sigact.sa_handler = cpu_signal;
3669 sigaction(SIGUSR1, &sigact, NULL);
3672 static void unblock_io_signals(void)
3674 sigset_t set;
3676 sigemptyset(&set);
3677 sigaddset(&set, SIGUSR2);
3678 sigaddset(&set, SIGIO);
3679 sigaddset(&set, SIGALRM);
3680 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3682 sigemptyset(&set);
3683 sigaddset(&set, SIGUSR1);
3684 pthread_sigmask(SIG_BLOCK, &set, NULL);
3687 static void qemu_signal_lock(unsigned int msecs)
3689 qemu_mutex_lock(&qemu_fair_mutex);
3691 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3692 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3693 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3694 break;
3696 qemu_mutex_unlock(&qemu_fair_mutex);
3699 static void qemu_mutex_lock_iothread(void)
3701 if (kvm_enabled()) {
3702 qemu_mutex_lock(&qemu_fair_mutex);
3703 qemu_mutex_lock(&qemu_global_mutex);
3704 qemu_mutex_unlock(&qemu_fair_mutex);
3705 } else
3706 qemu_signal_lock(100);
3709 static void qemu_mutex_unlock_iothread(void)
3711 qemu_mutex_unlock(&qemu_global_mutex);
3714 static int all_vcpus_paused(void)
3716 CPUState *penv = first_cpu;
3718 while (penv) {
3719 if (!penv->stopped)
3720 return 0;
3721 penv = (CPUState *)penv->next_cpu;
3724 return 1;
3727 static void pause_all_vcpus(void)
3729 CPUState *penv = first_cpu;
3731 while (penv) {
3732 penv->stop = 1;
3733 qemu_thread_signal(penv->thread, SIGUSR1);
3734 qemu_cpu_kick(penv);
3735 penv = (CPUState *)penv->next_cpu;
3738 while (!all_vcpus_paused()) {
3739 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3740 penv = first_cpu;
3741 while (penv) {
3742 qemu_thread_signal(penv->thread, SIGUSR1);
3743 penv = (CPUState *)penv->next_cpu;
3748 static void resume_all_vcpus(void)
3750 CPUState *penv = first_cpu;
3752 while (penv) {
3753 penv->stop = 0;
3754 penv->stopped = 0;
3755 qemu_thread_signal(penv->thread, SIGUSR1);
3756 qemu_cpu_kick(penv);
3757 penv = (CPUState *)penv->next_cpu;
3761 static void tcg_init_vcpu(void *_env)
3763 CPUState *env = _env;
3764 /* share a single thread for all cpus with TCG */
3765 if (!tcg_cpu_thread) {
3766 env->thread = qemu_mallocz(sizeof(QemuThread));
3767 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3768 qemu_cond_init(env->halt_cond);
3769 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3770 while (env->created == 0)
3771 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3772 tcg_cpu_thread = env->thread;
3773 tcg_halt_cond = env->halt_cond;
3774 } else {
3775 env->thread = tcg_cpu_thread;
3776 env->halt_cond = tcg_halt_cond;
3780 static void kvm_start_vcpu(CPUState *env)
3782 env->thread = qemu_mallocz(sizeof(QemuThread));
3783 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3784 qemu_cond_init(env->halt_cond);
3785 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3786 while (env->created == 0)
3787 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3790 void qemu_init_vcpu(void *_env)
3792 CPUState *env = _env;
3794 if (kvm_enabled())
3795 kvm_start_vcpu(env);
3796 else
3797 tcg_init_vcpu(env);
3798 env->nr_cores = smp_cores;
3799 env->nr_threads = smp_threads;
3802 void qemu_notify_event(void)
3804 qemu_event_increment();
3807 void vm_stop(int reason)
3809 QemuThread me;
3810 qemu_thread_self(&me);
3812 if (!qemu_thread_equal(&me, &io_thread)) {
3813 qemu_system_vmstop_request(reason);
3815 * FIXME: should not return to device code in case
3816 * vm_stop() has been requested.
3818 if (cpu_single_env) {
3819 cpu_exit(cpu_single_env);
3820 cpu_single_env->stop = 1;
3822 return;
3824 do_vm_stop(reason);
3827 #endif
3830 #ifdef _WIN32
3831 static void host_main_loop_wait(int *timeout)
3833 int ret, ret2, i;
3834 PollingEntry *pe;
3837 /* XXX: need to suppress polling by better using win32 events */
3838 ret = 0;
3839 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3840 ret |= pe->func(pe->opaque);
3842 if (ret == 0) {
3843 int err;
3844 WaitObjects *w = &wait_objects;
3846 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3847 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3848 if (w->func[ret - WAIT_OBJECT_0])
3849 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3851 /* Check for additional signaled events */
3852 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3854 /* Check if event is signaled */
3855 ret2 = WaitForSingleObject(w->events[i], 0);
3856 if(ret2 == WAIT_OBJECT_0) {
3857 if (w->func[i])
3858 w->func[i](w->opaque[i]);
3859 } else if (ret2 == WAIT_TIMEOUT) {
3860 } else {
3861 err = GetLastError();
3862 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3865 } else if (ret == WAIT_TIMEOUT) {
3866 } else {
3867 err = GetLastError();
3868 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3872 *timeout = 0;
3874 #else
3875 static void host_main_loop_wait(int *timeout)
3878 #endif
3880 void main_loop_wait(int timeout)
3882 IOHandlerRecord *ioh;
3883 fd_set rfds, wfds, xfds;
3884 int ret, nfds;
3885 struct timeval tv;
3887 qemu_bh_update_timeout(&timeout);
3889 host_main_loop_wait(&timeout);
3891 /* poll any events */
3892 /* XXX: separate device handlers from system ones */
3893 nfds = -1;
3894 FD_ZERO(&rfds);
3895 FD_ZERO(&wfds);
3896 FD_ZERO(&xfds);
3897 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3898 if (ioh->deleted)
3899 continue;
3900 if (ioh->fd_read &&
3901 (!ioh->fd_read_poll ||
3902 ioh->fd_read_poll(ioh->opaque) != 0)) {
3903 FD_SET(ioh->fd, &rfds);
3904 if (ioh->fd > nfds)
3905 nfds = ioh->fd;
3907 if (ioh->fd_write) {
3908 FD_SET(ioh->fd, &wfds);
3909 if (ioh->fd > nfds)
3910 nfds = ioh->fd;
3914 tv.tv_sec = timeout / 1000;
3915 tv.tv_usec = (timeout % 1000) * 1000;
3917 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3919 qemu_mutex_unlock_iothread();
3920 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3921 qemu_mutex_lock_iothread();
3922 if (ret > 0) {
3923 IOHandlerRecord **pioh;
3925 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3926 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3927 ioh->fd_read(ioh->opaque);
3928 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3929 FD_CLR(ioh->fd, &rfds);
3931 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3932 ioh->fd_write(ioh->opaque);
3936 /* remove deleted IO handlers */
3937 pioh = &first_io_handler;
3938 while (*pioh) {
3939 ioh = *pioh;
3940 if (ioh->deleted) {
3941 *pioh = ioh->next;
3942 qemu_free(ioh);
3943 } else
3944 pioh = &ioh->next;
3948 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3950 /* rearm timer, if not periodic */
3951 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3952 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3953 qemu_rearm_alarm_timer(alarm_timer);
3956 /* vm time timers */
3957 if (vm_running) {
3958 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3959 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3960 qemu_get_clock(vm_clock));
3963 /* real time timers */
3964 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3965 qemu_get_clock(rt_clock));
3967 /* Check bottom-halves last in case any of the earlier events triggered
3968 them. */
3969 qemu_bh_poll();
3973 static int qemu_cpu_exec(CPUState *env)
3975 int ret;
3976 #ifdef CONFIG_PROFILER
3977 int64_t ti;
3978 #endif
3980 #ifdef CONFIG_PROFILER
3981 ti = profile_getclock();
3982 #endif
3983 if (use_icount) {
3984 int64_t count;
3985 int decr;
3986 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3987 env->icount_decr.u16.low = 0;
3988 env->icount_extra = 0;
3989 count = qemu_next_deadline();
3990 count = (count + (1 << icount_time_shift) - 1)
3991 >> icount_time_shift;
3992 qemu_icount += count;
3993 decr = (count > 0xffff) ? 0xffff : count;
3994 count -= decr;
3995 env->icount_decr.u16.low = decr;
3996 env->icount_extra = count;
3998 ret = cpu_exec(env);
3999 #ifdef CONFIG_PROFILER
4000 qemu_time += profile_getclock() - ti;
4001 #endif
4002 if (use_icount) {
4003 /* Fold pending instructions back into the
4004 instruction counter, and clear the interrupt flag. */
4005 qemu_icount -= (env->icount_decr.u16.low
4006 + env->icount_extra);
4007 env->icount_decr.u32 = 0;
4008 env->icount_extra = 0;
4010 return ret;
4013 static void tcg_cpu_exec(void)
4015 int ret = 0;
4017 if (next_cpu == NULL)
4018 next_cpu = first_cpu;
4019 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4020 CPUState *env = cur_cpu = next_cpu;
4022 if (!vm_running)
4023 break;
4024 if (timer_alarm_pending) {
4025 timer_alarm_pending = 0;
4026 break;
4028 if (cpu_can_run(env))
4029 ret = qemu_cpu_exec(env);
4030 if (ret == EXCP_DEBUG) {
4031 gdb_set_stop_cpu(env);
4032 debug_requested = 1;
4033 break;
4038 static int cpu_has_work(CPUState *env)
4040 if (env->stop)
4041 return 1;
4042 if (env->stopped)
4043 return 0;
4044 if (!env->halted)
4045 return 1;
4046 if (qemu_cpu_has_work(env))
4047 return 1;
4048 return 0;
4051 static int tcg_has_work(void)
4053 CPUState *env;
4055 for (env = first_cpu; env != NULL; env = env->next_cpu)
4056 if (cpu_has_work(env))
4057 return 1;
4058 return 0;
4061 static int qemu_calculate_timeout(void)
4063 #ifndef CONFIG_IOTHREAD
4064 int timeout;
4066 if (!vm_running)
4067 timeout = 5000;
4068 else if (tcg_has_work())
4069 timeout = 0;
4070 else if (!use_icount)
4071 timeout = 5000;
4072 else {
4073 /* XXX: use timeout computed from timers */
4074 int64_t add;
4075 int64_t delta;
4076 /* Advance virtual time to the next event. */
4077 if (use_icount == 1) {
4078 /* When not using an adaptive execution frequency
4079 we tend to get badly out of sync with real time,
4080 so just delay for a reasonable amount of time. */
4081 delta = 0;
4082 } else {
4083 delta = cpu_get_icount() - cpu_get_clock();
4085 if (delta > 0) {
4086 /* If virtual time is ahead of real time then just
4087 wait for IO. */
4088 timeout = (delta / 1000000) + 1;
4089 } else {
4090 /* Wait for either IO to occur or the next
4091 timer event. */
4092 add = qemu_next_deadline();
4093 /* We advance the timer before checking for IO.
4094 Limit the amount we advance so that early IO
4095 activity won't get the guest too far ahead. */
4096 if (add > 10000000)
4097 add = 10000000;
4098 delta += add;
4099 add = (add + (1 << icount_time_shift) - 1)
4100 >> icount_time_shift;
4101 qemu_icount += add;
4102 timeout = delta / 1000000;
4103 if (timeout < 0)
4104 timeout = 0;
4108 return timeout;
4109 #else /* CONFIG_IOTHREAD */
4110 return 1000;
4111 #endif
4114 static int vm_can_run(void)
4116 if (powerdown_requested)
4117 return 0;
4118 if (reset_requested)
4119 return 0;
4120 if (shutdown_requested)
4121 return 0;
4122 if (debug_requested)
4123 return 0;
4124 return 1;
4127 qemu_irq qemu_system_powerdown;
4129 static void main_loop(void)
4131 int r;
4133 if (kvm_enabled()) {
4134 kvm_main_loop();
4135 cpu_disable_ticks();
4136 return;
4139 #ifdef CONFIG_IOTHREAD
4140 qemu_system_ready = 1;
4141 qemu_cond_broadcast(&qemu_system_cond);
4142 #endif
4144 for (;;) {
4145 do {
4146 #ifdef CONFIG_PROFILER
4147 int64_t ti;
4148 #endif
4149 #ifndef CONFIG_IOTHREAD
4150 tcg_cpu_exec();
4151 #endif
4152 #ifdef CONFIG_PROFILER
4153 ti = profile_getclock();
4154 #endif
4155 main_loop_wait(qemu_calculate_timeout());
4156 #ifdef CONFIG_PROFILER
4157 dev_time += profile_getclock() - ti;
4158 #endif
4159 } while (vm_can_run());
4161 if (qemu_debug_requested())
4162 vm_stop(EXCP_DEBUG);
4163 if (qemu_shutdown_requested()) {
4164 if (no_shutdown) {
4165 vm_stop(0);
4166 no_shutdown = 0;
4167 } else
4168 break;
4170 if (qemu_reset_requested()) {
4171 pause_all_vcpus();
4172 qemu_system_reset();
4173 resume_all_vcpus();
4175 if (qemu_powerdown_requested()) {
4176 qemu_irq_raise(qemu_system_powerdown);
4178 if ((r = qemu_vmstop_requested()))
4179 vm_stop(r);
4181 pause_all_vcpus();
4184 static void version(void)
4186 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4189 static void help(int exitcode)
4191 version();
4192 printf("usage: %s [options] [disk_image]\n"
4193 "\n"
4194 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4195 "\n"
4196 #define DEF(option, opt_arg, opt_enum, opt_help) \
4197 opt_help
4198 #define DEFHEADING(text) stringify(text) "\n"
4199 #include "qemu-options.h"
4200 #undef DEF
4201 #undef DEFHEADING
4202 #undef GEN_DOCS
4203 "\n"
4204 "During emulation, the following keys are useful:\n"
4205 "ctrl-alt-f toggle full screen\n"
4206 "ctrl-alt-n switch to virtual console 'n'\n"
4207 "ctrl-alt toggle mouse and keyboard grab\n"
4208 "\n"
4209 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4211 "qemu",
4212 DEFAULT_RAM_SIZE,
4213 #ifndef _WIN32
4214 DEFAULT_NETWORK_SCRIPT,
4215 DEFAULT_NETWORK_DOWN_SCRIPT,
4216 #endif
4217 DEFAULT_GDBSTUB_PORT,
4218 "/tmp/qemu.log");
4219 exit(exitcode);
4222 #define HAS_ARG 0x0001
4224 enum {
4225 #define DEF(option, opt_arg, opt_enum, opt_help) \
4226 opt_enum,
4227 #define DEFHEADING(text)
4228 #include "qemu-options.h"
4229 #undef DEF
4230 #undef DEFHEADING
4231 #undef GEN_DOCS
4234 typedef struct QEMUOption {
4235 const char *name;
4236 int flags;
4237 int index;
4238 } QEMUOption;
4240 static const QEMUOption qemu_options[] = {
4241 { "h", 0, QEMU_OPTION_h },
4242 #define DEF(option, opt_arg, opt_enum, opt_help) \
4243 { option, opt_arg, opt_enum },
4244 #define DEFHEADING(text)
4245 #include "qemu-options.h"
4246 #undef DEF
4247 #undef DEFHEADING
4248 #undef GEN_DOCS
4249 { NULL },
4252 #ifdef HAS_AUDIO
4253 struct soundhw soundhw[] = {
4254 #ifdef HAS_AUDIO_CHOICE
4255 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4257 "pcspk",
4258 "PC speaker",
4261 { .init_isa = pcspk_audio_init }
4263 #endif
4265 #ifdef CONFIG_SB16
4267 "sb16",
4268 "Creative Sound Blaster 16",
4271 { .init_isa = SB16_init }
4273 #endif
4275 #ifdef CONFIG_CS4231A
4277 "cs4231a",
4278 "CS4231A",
4281 { .init_isa = cs4231a_init }
4283 #endif
4285 #ifdef CONFIG_ADLIB
4287 "adlib",
4288 #ifdef HAS_YMF262
4289 "Yamaha YMF262 (OPL3)",
4290 #else
4291 "Yamaha YM3812 (OPL2)",
4292 #endif
4295 { .init_isa = Adlib_init }
4297 #endif
4299 #ifdef CONFIG_GUS
4301 "gus",
4302 "Gravis Ultrasound GF1",
4305 { .init_isa = GUS_init }
4307 #endif
4309 #ifdef CONFIG_AC97
4311 "ac97",
4312 "Intel 82801AA AC97 Audio",
4315 { .init_pci = ac97_init }
4317 #endif
4319 #ifdef CONFIG_ES1370
4321 "es1370",
4322 "ENSONIQ AudioPCI ES1370",
4325 { .init_pci = es1370_init }
4327 #endif
4329 #endif /* HAS_AUDIO_CHOICE */
4331 { NULL, NULL, 0, 0, { NULL } }
4334 static void select_soundhw (const char *optarg)
4336 struct soundhw *c;
4338 if (*optarg == '?') {
4339 show_valid_cards:
4341 printf ("Valid sound card names (comma separated):\n");
4342 for (c = soundhw; c->name; ++c) {
4343 printf ("%-11s %s\n", c->name, c->descr);
4345 printf ("\n-soundhw all will enable all of the above\n");
4346 exit (*optarg != '?');
4348 else {
4349 size_t l;
4350 const char *p;
4351 char *e;
4352 int bad_card = 0;
4354 if (!strcmp (optarg, "all")) {
4355 for (c = soundhw; c->name; ++c) {
4356 c->enabled = 1;
4358 return;
4361 p = optarg;
4362 while (*p) {
4363 e = strchr (p, ',');
4364 l = !e ? strlen (p) : (size_t) (e - p);
4366 for (c = soundhw; c->name; ++c) {
4367 if (!strncmp (c->name, p, l) && !c->name[l]) {
4368 c->enabled = 1;
4369 break;
4373 if (!c->name) {
4374 if (l > 80) {
4375 fprintf (stderr,
4376 "Unknown sound card name (too big to show)\n");
4378 else {
4379 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4380 (int) l, p);
4382 bad_card = 1;
4384 p += l + (e != NULL);
4387 if (bad_card)
4388 goto show_valid_cards;
4391 #endif
4393 static void select_vgahw (const char *p)
4395 const char *opts;
4397 vga_interface_type = VGA_NONE;
4398 if (strstart(p, "std", &opts)) {
4399 vga_interface_type = VGA_STD;
4400 } else if (strstart(p, "cirrus", &opts)) {
4401 vga_interface_type = VGA_CIRRUS;
4402 } else if (strstart(p, "vmware", &opts)) {
4403 vga_interface_type = VGA_VMWARE;
4404 } else if (strstart(p, "xenfb", &opts)) {
4405 vga_interface_type = VGA_XENFB;
4406 } else if (!strstart(p, "none", &opts)) {
4407 invalid_vga:
4408 fprintf(stderr, "Unknown vga type: %s\n", p);
4409 exit(1);
4411 while (*opts) {
4412 const char *nextopt;
4414 if (strstart(opts, ",retrace=", &nextopt)) {
4415 opts = nextopt;
4416 if (strstart(opts, "dumb", &nextopt))
4417 vga_retrace_method = VGA_RETRACE_DUMB;
4418 else if (strstart(opts, "precise", &nextopt))
4419 vga_retrace_method = VGA_RETRACE_PRECISE;
4420 else goto invalid_vga;
4421 } else goto invalid_vga;
4422 opts = nextopt;
4426 #ifdef TARGET_I386
4427 static int balloon_parse(const char *arg)
4429 QemuOpts *opts;
4431 if (strcmp(arg, "none") == 0) {
4432 return 0;
4435 if (!strncmp(arg, "virtio", 6)) {
4436 if (arg[6] == ',') {
4437 /* have params -> parse them */
4438 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4439 if (!opts)
4440 return -1;
4441 } else {
4442 /* create empty opts */
4443 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4445 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4446 return 0;
4449 return -1;
4451 #endif
4453 #ifdef _WIN32
4454 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4456 exit(STATUS_CONTROL_C_EXIT);
4457 return TRUE;
4459 #endif
4461 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4463 int ret;
4465 if(strlen(str) != 36)
4466 return -1;
4468 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4469 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4470 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4472 if(ret != 16)
4473 return -1;
4475 #ifdef TARGET_I386
4476 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4477 #endif
4479 return 0;
4482 #define MAX_NET_CLIENTS 32
4484 #ifndef _WIN32
4486 static void termsig_handler(int signal)
4488 qemu_system_shutdown_request();
4491 static void sigchld_handler(int signal)
4493 waitpid(-1, NULL, WNOHANG);
4496 static void sighandler_setup(void)
4498 struct sigaction act;
4500 memset(&act, 0, sizeof(act));
4501 act.sa_handler = termsig_handler;
4502 sigaction(SIGINT, &act, NULL);
4503 sigaction(SIGHUP, &act, NULL);
4504 sigaction(SIGTERM, &act, NULL);
4506 act.sa_handler = sigchld_handler;
4507 act.sa_flags = SA_NOCLDSTOP;
4508 sigaction(SIGCHLD, &act, NULL);
4511 #endif
4513 #ifdef _WIN32
4514 /* Look for support files in the same directory as the executable. */
4515 static char *find_datadir(const char *argv0)
4517 char *p;
4518 char buf[MAX_PATH];
4519 DWORD len;
4521 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4522 if (len == 0) {
4523 return NULL;
4526 buf[len] = 0;
4527 p = buf + len - 1;
4528 while (p != buf && *p != '\\')
4529 p--;
4530 *p = 0;
4531 if (access(buf, R_OK) == 0) {
4532 return qemu_strdup(buf);
4534 return NULL;
4536 #else /* !_WIN32 */
4538 /* Find a likely location for support files using the location of the binary.
4539 For installed binaries this will be "$bindir/../share/qemu". When
4540 running from the build tree this will be "$bindir/../pc-bios". */
4541 #define SHARE_SUFFIX "/share/qemu"
4542 #define BUILD_SUFFIX "/pc-bios"
4543 static char *find_datadir(const char *argv0)
4545 char *dir;
4546 char *p = NULL;
4547 char *res;
4548 char buf[PATH_MAX];
4549 size_t max_len;
4551 #if defined(__linux__)
4553 int len;
4554 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4555 if (len > 0) {
4556 buf[len] = 0;
4557 p = buf;
4560 #elif defined(__FreeBSD__)
4562 int len;
4563 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4564 if (len > 0) {
4565 buf[len] = 0;
4566 p = buf;
4569 #endif
4570 /* If we don't have any way of figuring out the actual executable
4571 location then try argv[0]. */
4572 if (!p) {
4573 p = realpath(argv0, buf);
4574 if (!p) {
4575 return NULL;
4578 dir = dirname(p);
4579 dir = dirname(dir);
4581 max_len = strlen(dir) +
4582 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4583 res = qemu_mallocz(max_len);
4584 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4585 if (access(res, R_OK)) {
4586 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4587 if (access(res, R_OK)) {
4588 qemu_free(res);
4589 res = NULL;
4593 return res;
4595 #undef SHARE_SUFFIX
4596 #undef BUILD_SUFFIX
4597 #endif
4599 char *qemu_find_file(int type, const char *name)
4601 int len;
4602 const char *subdir;
4603 char *buf;
4605 /* If name contains path separators then try it as a straight path. */
4606 if ((strchr(name, '/') || strchr(name, '\\'))
4607 && access(name, R_OK) == 0) {
4608 return qemu_strdup(name);
4610 switch (type) {
4611 case QEMU_FILE_TYPE_BIOS:
4612 subdir = "";
4613 break;
4614 case QEMU_FILE_TYPE_KEYMAP:
4615 subdir = "keymaps/";
4616 break;
4617 default:
4618 abort();
4620 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4621 buf = qemu_mallocz(len);
4622 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4623 if (access(buf, R_OK)) {
4624 qemu_free(buf);
4625 return NULL;
4627 return buf;
4630 static int device_init_func(QemuOpts *opts, void *opaque)
4632 DeviceState *dev;
4634 dev = qdev_device_add(opts);
4635 if (!dev)
4636 return -1;
4637 return 0;
4640 struct device_config {
4641 enum {
4642 DEV_USB, /* -usbdevice */
4643 DEV_BT, /* -bt */
4644 } type;
4645 const char *cmdline;
4646 QTAILQ_ENTRY(device_config) next;
4648 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4650 static void add_device_config(int type, const char *cmdline)
4652 struct device_config *conf;
4654 conf = qemu_mallocz(sizeof(*conf));
4655 conf->type = type;
4656 conf->cmdline = cmdline;
4657 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4660 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4662 struct device_config *conf;
4663 int rc;
4665 QTAILQ_FOREACH(conf, &device_configs, next) {
4666 if (conf->type != type)
4667 continue;
4668 rc = func(conf->cmdline);
4669 if (0 != rc)
4670 return rc;
4672 return 0;
4675 int main(int argc, char **argv, char **envp)
4677 const char *gdbstub_dev = NULL;
4678 uint32_t boot_devices_bitmap = 0;
4679 int i;
4680 int snapshot, linux_boot, net_boot;
4681 const char *initrd_filename;
4682 const char *kernel_filename, *kernel_cmdline;
4683 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4684 DisplayState *ds;
4685 DisplayChangeListener *dcl;
4686 int cyls, heads, secs, translation;
4687 const char *net_clients[MAX_NET_CLIENTS];
4688 int nb_net_clients;
4689 QemuOpts *hda_opts = NULL, *opts;
4690 int optind;
4691 const char *r, *optarg;
4692 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4693 const char *monitor_devices[MAX_MONITOR_DEVICES];
4694 int monitor_device_index;
4695 const char *serial_devices[MAX_SERIAL_PORTS];
4696 int serial_device_index;
4697 const char *parallel_devices[MAX_PARALLEL_PORTS];
4698 int parallel_device_index;
4699 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4700 int virtio_console_index;
4701 const char *loadvm = NULL;
4702 QEMUMachine *machine;
4703 const char *cpu_model;
4704 #ifndef _WIN32
4705 int fds[2];
4706 #endif
4707 int tb_size;
4708 const char *pid_file = NULL;
4709 const char *incoming = NULL;
4710 #ifndef _WIN32
4711 int fd = 0;
4712 struct passwd *pwd = NULL;
4713 const char *chroot_dir = NULL;
4714 const char *run_as = NULL;
4715 #endif
4716 CPUState *env;
4717 int show_vnc_port = 0;
4719 qemu_errors_to_file(stderr);
4720 qemu_cache_utils_init(envp);
4722 QLIST_INIT (&vm_change_state_head);
4723 #ifndef _WIN32
4725 struct sigaction act;
4726 sigfillset(&act.sa_mask);
4727 act.sa_flags = 0;
4728 act.sa_handler = SIG_IGN;
4729 sigaction(SIGPIPE, &act, NULL);
4731 #else
4732 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4733 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4734 QEMU to run on a single CPU */
4736 HANDLE h;
4737 DWORD mask, smask;
4738 int i;
4739 h = GetCurrentProcess();
4740 if (GetProcessAffinityMask(h, &mask, &smask)) {
4741 for(i = 0; i < 32; i++) {
4742 if (mask & (1 << i))
4743 break;
4745 if (i != 32) {
4746 mask = 1 << i;
4747 SetProcessAffinityMask(h, mask);
4751 #endif
4753 module_call_init(MODULE_INIT_MACHINE);
4754 machine = find_default_machine();
4755 cpu_model = NULL;
4756 initrd_filename = NULL;
4757 ram_size = 0;
4758 snapshot = 0;
4759 kernel_filename = NULL;
4760 kernel_cmdline = "";
4761 cyls = heads = secs = 0;
4762 translation = BIOS_ATA_TRANSLATION_AUTO;
4764 serial_devices[0] = "vc:80Cx24C";
4765 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4766 serial_devices[i] = NULL;
4767 serial_device_index = 0;
4769 parallel_devices[0] = "vc:80Cx24C";
4770 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4771 parallel_devices[i] = NULL;
4772 parallel_device_index = 0;
4774 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4775 virtio_consoles[i] = NULL;
4776 virtio_console_index = 0;
4778 monitor_devices[0] = "vc:80Cx24C";
4779 for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4780 monitor_devices[i] = NULL;
4782 monitor_device_index = 0;
4784 for (i = 0; i < MAX_NODES; i++) {
4785 node_mem[i] = 0;
4786 node_cpumask[i] = 0;
4789 assigned_devices_index = 0;
4791 nb_net_clients = 0;
4792 nb_numa_nodes = 0;
4793 nb_nics = 0;
4795 tb_size = 0;
4796 autostart= 1;
4798 optind = 1;
4799 for(;;) {
4800 if (optind >= argc)
4801 break;
4802 r = argv[optind];
4803 if (r[0] != '-') {
4804 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4805 } else {
4806 const QEMUOption *popt;
4808 optind++;
4809 /* Treat --foo the same as -foo. */
4810 if (r[1] == '-')
4811 r++;
4812 popt = qemu_options;
4813 for(;;) {
4814 if (!popt->name) {
4815 fprintf(stderr, "%s: invalid option -- '%s'\n",
4816 argv[0], r);
4817 exit(1);
4819 if (!strcmp(popt->name, r + 1))
4820 break;
4821 popt++;
4823 if (popt->flags & HAS_ARG) {
4824 if (optind >= argc) {
4825 fprintf(stderr, "%s: option '%s' requires an argument\n",
4826 argv[0], r);
4827 exit(1);
4829 optarg = argv[optind++];
4830 } else {
4831 optarg = NULL;
4834 switch(popt->index) {
4835 case QEMU_OPTION_M:
4836 machine = find_machine(optarg);
4837 if (!machine) {
4838 QEMUMachine *m;
4839 printf("Supported machines are:\n");
4840 for(m = first_machine; m != NULL; m = m->next) {
4841 if (m->alias)
4842 printf("%-10s %s (alias of %s)\n",
4843 m->alias, m->desc, m->name);
4844 printf("%-10s %s%s\n",
4845 m->name, m->desc,
4846 m->is_default ? " (default)" : "");
4848 exit(*optarg != '?');
4850 break;
4851 case QEMU_OPTION_cpu:
4852 /* hw initialization will check this */
4853 if (*optarg == '?') {
4854 /* XXX: implement xxx_cpu_list for targets that still miss it */
4855 #if defined(cpu_list)
4856 cpu_list(stdout, &fprintf);
4857 #endif
4858 exit(0);
4859 } else {
4860 cpu_model = optarg;
4862 break;
4863 case QEMU_OPTION_initrd:
4864 initrd_filename = optarg;
4865 break;
4866 case QEMU_OPTION_hda:
4867 if (cyls == 0)
4868 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4869 else
4870 hda_opts = drive_add(optarg, HD_ALIAS
4871 ",cyls=%d,heads=%d,secs=%d%s",
4872 0, cyls, heads, secs,
4873 translation == BIOS_ATA_TRANSLATION_LBA ?
4874 ",trans=lba" :
4875 translation == BIOS_ATA_TRANSLATION_NONE ?
4876 ",trans=none" : "");
4877 break;
4878 case QEMU_OPTION_hdb:
4879 case QEMU_OPTION_hdc:
4880 case QEMU_OPTION_hdd:
4881 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4882 break;
4883 case QEMU_OPTION_drive:
4884 drive_add(NULL, "%s", optarg);
4885 break;
4886 case QEMU_OPTION_set:
4887 if (qemu_set_option(optarg) != 0)
4888 exit(1);
4889 break;
4890 case QEMU_OPTION_mtdblock:
4891 drive_add(optarg, MTD_ALIAS);
4892 break;
4893 case QEMU_OPTION_sd:
4894 drive_add(optarg, SD_ALIAS);
4895 break;
4896 case QEMU_OPTION_pflash:
4897 drive_add(optarg, PFLASH_ALIAS);
4898 break;
4899 case QEMU_OPTION_snapshot:
4900 snapshot = 1;
4901 break;
4902 case QEMU_OPTION_hdachs:
4904 const char *p;
4905 p = optarg;
4906 cyls = strtol(p, (char **)&p, 0);
4907 if (cyls < 1 || cyls > 16383)
4908 goto chs_fail;
4909 if (*p != ',')
4910 goto chs_fail;
4911 p++;
4912 heads = strtol(p, (char **)&p, 0);
4913 if (heads < 1 || heads > 16)
4914 goto chs_fail;
4915 if (*p != ',')
4916 goto chs_fail;
4917 p++;
4918 secs = strtol(p, (char **)&p, 0);
4919 if (secs < 1 || secs > 63)
4920 goto chs_fail;
4921 if (*p == ',') {
4922 p++;
4923 if (!strcmp(p, "none"))
4924 translation = BIOS_ATA_TRANSLATION_NONE;
4925 else if (!strcmp(p, "lba"))
4926 translation = BIOS_ATA_TRANSLATION_LBA;
4927 else if (!strcmp(p, "auto"))
4928 translation = BIOS_ATA_TRANSLATION_AUTO;
4929 else
4930 goto chs_fail;
4931 } else if (*p != '\0') {
4932 chs_fail:
4933 fprintf(stderr, "qemu: invalid physical CHS format\n");
4934 exit(1);
4936 if (hda_opts != NULL) {
4937 char num[16];
4938 snprintf(num, sizeof(num), "%d", cyls);
4939 qemu_opt_set(hda_opts, "cyls", num);
4940 snprintf(num, sizeof(num), "%d", heads);
4941 qemu_opt_set(hda_opts, "heads", num);
4942 snprintf(num, sizeof(num), "%d", secs);
4943 qemu_opt_set(hda_opts, "secs", num);
4944 if (translation == BIOS_ATA_TRANSLATION_LBA)
4945 qemu_opt_set(hda_opts, "trans", "lba");
4946 if (translation == BIOS_ATA_TRANSLATION_NONE)
4947 qemu_opt_set(hda_opts, "trans", "none");
4950 break;
4951 case QEMU_OPTION_numa:
4952 if (nb_numa_nodes >= MAX_NODES) {
4953 fprintf(stderr, "qemu: too many NUMA nodes\n");
4954 exit(1);
4956 numa_add(optarg);
4957 break;
4958 case QEMU_OPTION_nographic:
4959 display_type = DT_NOGRAPHIC;
4960 break;
4961 #ifdef CONFIG_CURSES
4962 case QEMU_OPTION_curses:
4963 display_type = DT_CURSES;
4964 break;
4965 #endif
4966 case QEMU_OPTION_portrait:
4967 graphic_rotate = 1;
4968 break;
4969 case QEMU_OPTION_kernel:
4970 kernel_filename = optarg;
4971 break;
4972 case QEMU_OPTION_append:
4973 kernel_cmdline = optarg;
4974 break;
4975 case QEMU_OPTION_cdrom:
4976 drive_add(optarg, CDROM_ALIAS);
4977 break;
4978 case QEMU_OPTION_boot:
4980 static const char * const params[] = {
4981 "order", "once", "menu", NULL
4983 char buf[sizeof(boot_devices)];
4984 char *standard_boot_devices;
4985 int legacy = 0;
4987 if (!strchr(optarg, '=')) {
4988 legacy = 1;
4989 pstrcpy(buf, sizeof(buf), optarg);
4990 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4991 fprintf(stderr,
4992 "qemu: unknown boot parameter '%s' in '%s'\n",
4993 buf, optarg);
4994 exit(1);
4997 if (legacy ||
4998 get_param_value(buf, sizeof(buf), "order", optarg)) {
4999 boot_devices_bitmap = parse_bootdevices(buf);
5000 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5002 if (!legacy) {
5003 if (get_param_value(buf, sizeof(buf),
5004 "once", optarg)) {
5005 boot_devices_bitmap |= parse_bootdevices(buf);
5006 standard_boot_devices = qemu_strdup(boot_devices);
5007 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5008 qemu_register_reset(restore_boot_devices,
5009 standard_boot_devices);
5011 if (get_param_value(buf, sizeof(buf),
5012 "menu", optarg)) {
5013 if (!strcmp(buf, "on")) {
5014 boot_menu = 1;
5015 } else if (!strcmp(buf, "off")) {
5016 boot_menu = 0;
5017 } else {
5018 fprintf(stderr,
5019 "qemu: invalid option value '%s'\n",
5020 buf);
5021 exit(1);
5026 break;
5027 case QEMU_OPTION_fda:
5028 case QEMU_OPTION_fdb:
5029 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5030 break;
5031 #ifdef TARGET_I386
5032 case QEMU_OPTION_no_fd_bootchk:
5033 fd_bootchk = 0;
5034 break;
5035 #endif
5036 case QEMU_OPTION_net:
5037 if (nb_net_clients >= MAX_NET_CLIENTS) {
5038 fprintf(stderr, "qemu: too many network clients\n");
5039 exit(1);
5041 net_clients[nb_net_clients] = optarg;
5042 nb_net_clients++;
5043 break;
5044 #ifdef CONFIG_SLIRP
5045 case QEMU_OPTION_tftp:
5046 legacy_tftp_prefix = optarg;
5047 break;
5048 case QEMU_OPTION_bootp:
5049 legacy_bootp_filename = optarg;
5050 break;
5051 #ifndef _WIN32
5052 case QEMU_OPTION_smb:
5053 net_slirp_smb(optarg);
5054 break;
5055 #endif
5056 case QEMU_OPTION_redir:
5057 net_slirp_redir(optarg);
5058 break;
5059 #endif
5060 case QEMU_OPTION_bt:
5061 add_device_config(DEV_BT, optarg);
5062 break;
5063 #ifdef HAS_AUDIO
5064 case QEMU_OPTION_audio_help:
5065 AUD_help ();
5066 exit (0);
5067 break;
5068 case QEMU_OPTION_soundhw:
5069 select_soundhw (optarg);
5070 break;
5071 #endif
5072 case QEMU_OPTION_h:
5073 help(0);
5074 break;
5075 case QEMU_OPTION_version:
5076 version();
5077 exit(0);
5078 break;
5079 case QEMU_OPTION_m: {
5080 uint64_t value;
5081 char *ptr;
5083 value = strtoul(optarg, &ptr, 10);
5084 switch (*ptr) {
5085 case 0: case 'M': case 'm':
5086 value <<= 20;
5087 break;
5088 case 'G': case 'g':
5089 value <<= 30;
5090 break;
5091 default:
5092 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5093 exit(1);
5096 /* On 32-bit hosts, QEMU is limited by virtual address space */
5097 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5098 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5099 exit(1);
5101 if (value != (uint64_t)(ram_addr_t)value) {
5102 fprintf(stderr, "qemu: ram size too large\n");
5103 exit(1);
5105 ram_size = value;
5106 break;
5108 case QEMU_OPTION_d:
5110 int mask;
5111 const CPULogItem *item;
5113 mask = cpu_str_to_log_mask(optarg);
5114 if (!mask) {
5115 printf("Log items (comma separated):\n");
5116 for(item = cpu_log_items; item->mask != 0; item++) {
5117 printf("%-10s %s\n", item->name, item->help);
5119 exit(1);
5121 cpu_set_log(mask);
5123 break;
5124 case QEMU_OPTION_s:
5125 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5126 break;
5127 case QEMU_OPTION_gdb:
5128 gdbstub_dev = optarg;
5129 break;
5130 case QEMU_OPTION_L:
5131 data_dir = optarg;
5132 break;
5133 case QEMU_OPTION_bios:
5134 bios_name = optarg;
5135 break;
5136 case QEMU_OPTION_singlestep:
5137 singlestep = 1;
5138 break;
5139 case QEMU_OPTION_S:
5140 autostart = 0;
5141 break;
5142 #ifndef _WIN32
5143 case QEMU_OPTION_k:
5144 keyboard_layout = optarg;
5145 break;
5146 #endif
5147 case QEMU_OPTION_localtime:
5148 rtc_utc = 0;
5149 break;
5150 case QEMU_OPTION_vga:
5151 select_vgahw (optarg);
5152 break;
5153 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5154 case QEMU_OPTION_g:
5156 const char *p;
5157 int w, h, depth;
5158 p = optarg;
5159 w = strtol(p, (char **)&p, 10);
5160 if (w <= 0) {
5161 graphic_error:
5162 fprintf(stderr, "qemu: invalid resolution or depth\n");
5163 exit(1);
5165 if (*p != 'x')
5166 goto graphic_error;
5167 p++;
5168 h = strtol(p, (char **)&p, 10);
5169 if (h <= 0)
5170 goto graphic_error;
5171 if (*p == 'x') {
5172 p++;
5173 depth = strtol(p, (char **)&p, 10);
5174 if (depth != 8 && depth != 15 && depth != 16 &&
5175 depth != 24 && depth != 32)
5176 goto graphic_error;
5177 } else if (*p == '\0') {
5178 depth = graphic_depth;
5179 } else {
5180 goto graphic_error;
5183 graphic_width = w;
5184 graphic_height = h;
5185 graphic_depth = depth;
5187 break;
5188 #endif
5189 case QEMU_OPTION_echr:
5191 char *r;
5192 term_escape_char = strtol(optarg, &r, 0);
5193 if (r == optarg)
5194 printf("Bad argument to echr\n");
5195 break;
5197 case QEMU_OPTION_monitor:
5198 if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5199 fprintf(stderr, "qemu: too many monitor devices\n");
5200 exit(1);
5202 monitor_devices[monitor_device_index] = optarg;
5203 monitor_device_index++;
5204 break;
5205 case QEMU_OPTION_chardev:
5206 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5207 if (!opts) {
5208 fprintf(stderr, "parse error: %s\n", optarg);
5209 exit(1);
5211 if (qemu_chr_open_opts(opts, NULL) == NULL) {
5212 exit(1);
5214 break;
5215 case QEMU_OPTION_serial:
5216 if (serial_device_index >= MAX_SERIAL_PORTS) {
5217 fprintf(stderr, "qemu: too many serial ports\n");
5218 exit(1);
5220 serial_devices[serial_device_index] = optarg;
5221 serial_device_index++;
5222 break;
5223 case QEMU_OPTION_watchdog:
5224 if (watchdog) {
5225 fprintf(stderr,
5226 "qemu: only one watchdog option may be given\n");
5227 return 1;
5229 watchdog = optarg;
5230 break;
5231 case QEMU_OPTION_watchdog_action:
5232 if (select_watchdog_action(optarg) == -1) {
5233 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5234 exit(1);
5236 break;
5237 case QEMU_OPTION_virtiocon:
5238 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5239 fprintf(stderr, "qemu: too many virtio consoles\n");
5240 exit(1);
5242 virtio_consoles[virtio_console_index] = optarg;
5243 virtio_console_index++;
5244 break;
5245 case QEMU_OPTION_parallel:
5246 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5247 fprintf(stderr, "qemu: too many parallel ports\n");
5248 exit(1);
5250 parallel_devices[parallel_device_index] = optarg;
5251 parallel_device_index++;
5252 break;
5253 case QEMU_OPTION_loadvm:
5254 loadvm = optarg;
5255 break;
5256 case QEMU_OPTION_full_screen:
5257 full_screen = 1;
5258 break;
5259 #ifdef CONFIG_SDL
5260 case QEMU_OPTION_no_frame:
5261 no_frame = 1;
5262 break;
5263 case QEMU_OPTION_alt_grab:
5264 alt_grab = 1;
5265 break;
5266 case QEMU_OPTION_no_quit:
5267 no_quit = 1;
5268 break;
5269 case QEMU_OPTION_sdl:
5270 display_type = DT_SDL;
5271 break;
5272 #endif
5273 case QEMU_OPTION_pidfile:
5274 pid_file = optarg;
5275 break;
5276 #ifdef TARGET_I386
5277 case QEMU_OPTION_win2k_hack:
5278 win2k_install_hack = 1;
5279 break;
5280 case QEMU_OPTION_rtc_td_hack:
5281 rtc_td_hack = 1;
5282 break;
5283 case QEMU_OPTION_acpitable:
5284 if(acpi_table_add(optarg) < 0) {
5285 fprintf(stderr, "Wrong acpi table provided\n");
5286 exit(1);
5288 break;
5289 case QEMU_OPTION_smbios:
5290 if(smbios_entry_add(optarg) < 0) {
5291 fprintf(stderr, "Wrong smbios provided\n");
5292 exit(1);
5294 break;
5295 #endif
5296 #ifdef CONFIG_KVM
5297 #ifdef KVM_UPSTREAM
5298 case QEMU_OPTION_enable_kvm:
5299 kvm_allowed = 1;
5300 #endif
5301 break;
5302 case QEMU_OPTION_no_kvm:
5303 kvm_allowed = 0;
5304 break;
5305 case QEMU_OPTION_no_kvm_irqchip: {
5306 kvm_irqchip = 0;
5307 kvm_pit = 0;
5308 break;
5310 case QEMU_OPTION_no_kvm_pit: {
5311 kvm_pit = 0;
5312 break;
5314 case QEMU_OPTION_no_kvm_pit_reinjection: {
5315 kvm_pit_reinject = 0;
5316 break;
5318 case QEMU_OPTION_enable_nesting: {
5319 kvm_nested = 1;
5320 break;
5322 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5323 case QEMU_OPTION_pcidevice:
5324 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5325 fprintf(stderr, "Too many assigned devices\n");
5326 exit(1);
5328 assigned_devices[assigned_devices_index] = optarg;
5329 assigned_devices_index++;
5330 break;
5331 #endif
5332 #endif
5333 case QEMU_OPTION_usb:
5334 usb_enabled = 1;
5335 break;
5336 case QEMU_OPTION_usbdevice:
5337 usb_enabled = 1;
5338 add_device_config(DEV_USB, optarg);
5339 break;
5340 case QEMU_OPTION_device:
5341 opts = qemu_opts_parse(&qemu_device_opts, optarg, "driver");
5342 if (!opts) {
5343 fprintf(stderr, "parse error: %s\n", optarg);
5344 exit(1);
5346 break;
5347 case QEMU_OPTION_smp:
5348 smp_parse(optarg);
5349 if (smp_cpus < 1) {
5350 fprintf(stderr, "Invalid number of CPUs\n");
5351 exit(1);
5353 if (max_cpus < smp_cpus) {
5354 fprintf(stderr, "maxcpus must be equal to or greater than "
5355 "smp\n");
5356 exit(1);
5358 if (max_cpus > 255) {
5359 fprintf(stderr, "Unsupported number of maxcpus\n");
5360 exit(1);
5362 break;
5363 case QEMU_OPTION_vnc:
5364 display_type = DT_VNC;
5365 vnc_display = optarg;
5366 break;
5367 #ifdef TARGET_I386
5368 case QEMU_OPTION_no_acpi:
5369 acpi_enabled = 0;
5370 break;
5371 case QEMU_OPTION_no_hpet:
5372 no_hpet = 1;
5373 break;
5374 case QEMU_OPTION_balloon:
5375 if (balloon_parse(optarg) < 0) {
5376 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5377 exit(1);
5379 break;
5380 #endif
5381 case QEMU_OPTION_no_reboot:
5382 no_reboot = 1;
5383 break;
5384 case QEMU_OPTION_no_shutdown:
5385 no_shutdown = 1;
5386 break;
5387 case QEMU_OPTION_show_cursor:
5388 cursor_hide = 0;
5389 break;
5390 case QEMU_OPTION_uuid:
5391 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5392 fprintf(stderr, "Fail to parse UUID string."
5393 " Wrong format.\n");
5394 exit(1);
5396 break;
5397 #ifndef _WIN32
5398 case QEMU_OPTION_daemonize:
5399 daemonize = 1;
5400 break;
5401 #endif
5402 case QEMU_OPTION_option_rom:
5403 if (nb_option_roms >= MAX_OPTION_ROMS) {
5404 fprintf(stderr, "Too many option ROMs\n");
5405 exit(1);
5407 option_rom[nb_option_roms] = optarg;
5408 nb_option_roms++;
5409 break;
5410 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5411 case QEMU_OPTION_semihosting:
5412 semihosting_enabled = 1;
5413 break;
5414 #endif
5415 case QEMU_OPTION_tdf:
5416 time_drift_fix = 1;
5417 break;
5418 case QEMU_OPTION_kvm_shadow_memory:
5419 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5420 break;
5421 case QEMU_OPTION_mempath:
5422 mem_path = optarg;
5423 break;
5424 #ifdef MAP_POPULATE
5425 case QEMU_OPTION_mem_prealloc:
5426 mem_prealloc = !mem_prealloc;
5427 break;
5428 #endif
5429 case QEMU_OPTION_name:
5430 qemu_name = qemu_strdup(optarg);
5432 char *p = strchr(qemu_name, ',');
5433 if (p != NULL) {
5434 *p++ = 0;
5435 if (strncmp(p, "process=", 8)) {
5436 fprintf(stderr, "Unknown subargument %s to -name", p);
5437 exit(1);
5439 p += 8;
5440 set_proc_name(p);
5443 break;
5444 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5445 case QEMU_OPTION_prom_env:
5446 if (nb_prom_envs >= MAX_PROM_ENVS) {
5447 fprintf(stderr, "Too many prom variables\n");
5448 exit(1);
5450 prom_envs[nb_prom_envs] = optarg;
5451 nb_prom_envs++;
5452 break;
5453 #endif
5454 #ifdef TARGET_ARM
5455 case QEMU_OPTION_old_param:
5456 old_param = 1;
5457 break;
5458 #endif
5459 case QEMU_OPTION_clock:
5460 configure_alarms(optarg);
5461 break;
5462 case QEMU_OPTION_startdate:
5464 struct tm tm;
5465 time_t rtc_start_date;
5466 if (!strcmp(optarg, "now")) {
5467 rtc_date_offset = -1;
5468 } else {
5469 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5470 &tm.tm_year,
5471 &tm.tm_mon,
5472 &tm.tm_mday,
5473 &tm.tm_hour,
5474 &tm.tm_min,
5475 &tm.tm_sec) == 6) {
5476 /* OK */
5477 } else if (sscanf(optarg, "%d-%d-%d",
5478 &tm.tm_year,
5479 &tm.tm_mon,
5480 &tm.tm_mday) == 3) {
5481 tm.tm_hour = 0;
5482 tm.tm_min = 0;
5483 tm.tm_sec = 0;
5484 } else {
5485 goto date_fail;
5487 tm.tm_year -= 1900;
5488 tm.tm_mon--;
5489 rtc_start_date = mktimegm(&tm);
5490 if (rtc_start_date == -1) {
5491 date_fail:
5492 fprintf(stderr, "Invalid date format. Valid format are:\n"
5493 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5494 exit(1);
5496 rtc_date_offset = time(NULL) - rtc_start_date;
5499 break;
5500 case QEMU_OPTION_tb_size:
5501 tb_size = strtol(optarg, NULL, 0);
5502 if (tb_size < 0)
5503 tb_size = 0;
5504 break;
5505 case QEMU_OPTION_icount:
5506 use_icount = 1;
5507 if (strcmp(optarg, "auto") == 0) {
5508 icount_time_shift = -1;
5509 } else {
5510 icount_time_shift = strtol(optarg, NULL, 0);
5512 break;
5513 case QEMU_OPTION_incoming:
5514 incoming = optarg;
5515 break;
5516 #ifndef _WIN32
5517 case QEMU_OPTION_chroot:
5518 chroot_dir = optarg;
5519 break;
5520 case QEMU_OPTION_runas:
5521 run_as = optarg;
5522 break;
5523 case QEMU_OPTION_nvram:
5524 nvram = optarg;
5525 break;
5526 #endif
5527 #ifdef CONFIG_XEN
5528 case QEMU_OPTION_xen_domid:
5529 xen_domid = atoi(optarg);
5530 break;
5531 case QEMU_OPTION_xen_create:
5532 xen_mode = XEN_CREATE;
5533 break;
5534 case QEMU_OPTION_xen_attach:
5535 xen_mode = XEN_ATTACH;
5536 break;
5537 #endif
5542 /* If no data_dir is specified then try to find it relative to the
5543 executable path. */
5544 if (!data_dir) {
5545 data_dir = find_datadir(argv[0]);
5547 /* If all else fails use the install patch specified when building. */
5548 if (!data_dir) {
5549 data_dir = CONFIG_QEMU_SHAREDIR;
5553 * Default to max_cpus = smp_cpus, in case the user doesn't
5554 * specify a max_cpus value.
5556 if (!max_cpus)
5557 max_cpus = smp_cpus;
5559 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5560 if (smp_cpus > machine->max_cpus) {
5561 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5562 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5563 machine->max_cpus);
5564 exit(1);
5567 if (display_type == DT_NOGRAPHIC) {
5568 if (serial_device_index == 0)
5569 serial_devices[0] = "stdio";
5570 if (parallel_device_index == 0)
5571 parallel_devices[0] = "null";
5572 if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5573 monitor_devices[0] = "stdio";
5577 #ifndef _WIN32
5578 if (daemonize) {
5579 pid_t pid;
5581 if (pipe(fds) == -1)
5582 exit(1);
5584 pid = fork();
5585 if (pid > 0) {
5586 uint8_t status;
5587 ssize_t len;
5589 close(fds[1]);
5591 again:
5592 len = read(fds[0], &status, 1);
5593 if (len == -1 && (errno == EINTR))
5594 goto again;
5596 if (len != 1)
5597 exit(1);
5598 else if (status == 1) {
5599 fprintf(stderr, "Could not acquire pidfile\n");
5600 exit(1);
5601 } else
5602 exit(0);
5603 } else if (pid < 0)
5604 exit(1);
5606 setsid();
5608 pid = fork();
5609 if (pid > 0)
5610 exit(0);
5611 else if (pid < 0)
5612 exit(1);
5614 umask(027);
5616 signal(SIGTSTP, SIG_IGN);
5617 signal(SIGTTOU, SIG_IGN);
5618 signal(SIGTTIN, SIG_IGN);
5621 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5622 if (daemonize) {
5623 uint8_t status = 1;
5624 write(fds[1], &status, 1);
5625 } else
5626 fprintf(stderr, "Could not acquire pid file\n");
5627 exit(1);
5629 #endif
5631 if (kvm_enabled()) {
5632 int ret;
5634 ret = kvm_init(smp_cpus);
5635 if (ret < 0) {
5636 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5637 fprintf(stderr, "failed to initialize KVM\n");
5638 exit(1);
5639 #endif
5640 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5641 kvm_allowed = 0;
5645 if (qemu_init_main_loop()) {
5646 fprintf(stderr, "qemu_init_main_loop failed\n");
5647 exit(1);
5649 linux_boot = (kernel_filename != NULL);
5651 if (!linux_boot && *kernel_cmdline != '\0') {
5652 fprintf(stderr, "-append only allowed with -kernel option\n");
5653 exit(1);
5656 if (!linux_boot && initrd_filename != NULL) {
5657 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5658 exit(1);
5661 #ifndef _WIN32
5662 /* Win32 doesn't support line-buffering and requires size >= 2 */
5663 setvbuf(stdout, NULL, _IOLBF, 0);
5664 #endif
5666 init_timers();
5667 if (init_timer_alarm() < 0) {
5668 fprintf(stderr, "could not initialize alarm timer\n");
5669 exit(1);
5671 if (use_icount && icount_time_shift < 0) {
5672 use_icount = 2;
5673 /* 125MIPS seems a reasonable initial guess at the guest speed.
5674 It will be corrected fairly quickly anyway. */
5675 icount_time_shift = 3;
5676 init_icount_adjust();
5679 #ifdef _WIN32
5680 socket_init();
5681 #endif
5683 /* init network clients */
5684 if (nb_net_clients == 0) {
5685 /* if no clients, we use a default config */
5686 net_clients[nb_net_clients++] = "nic";
5687 #ifdef CONFIG_SLIRP
5688 net_clients[nb_net_clients++] = "user";
5689 #endif
5692 for(i = 0;i < nb_net_clients; i++) {
5693 if (net_client_parse(net_clients[i]) < 0)
5694 exit(1);
5697 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5698 net_set_boot_mask(net_boot);
5700 net_client_check();
5702 /* init the bluetooth world */
5703 if (foreach_device_config(DEV_BT, bt_parse))
5704 exit(1);
5706 /* init the memory */
5707 if (ram_size == 0)
5708 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5710 /* init the dynamic translator */
5711 cpu_exec_init_all(tb_size * 1024 * 1024);
5713 bdrv_init();
5715 /* we always create the cdrom drive, even if no disk is there */
5716 drive_add(NULL, CDROM_ALIAS);
5718 /* we always create at least one floppy */
5719 drive_add(NULL, FD_ALIAS, 0);
5721 /* we always create one sd slot, even if no card is in it */
5722 drive_add(NULL, SD_ALIAS);
5724 /* open the virtual block devices */
5725 if (snapshot)
5726 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5727 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5728 exit(1);
5730 vmstate_register(0, &vmstate_timers ,&timers_state);
5731 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5733 /* Maintain compatibility with multiple stdio monitors */
5734 if (!strcmp(monitor_devices[0],"stdio")) {
5735 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5736 const char *devname = serial_devices[i];
5737 if (devname && !strcmp(devname,"mon:stdio")) {
5738 monitor_devices[0] = NULL;
5739 break;
5740 } else if (devname && !strcmp(devname,"stdio")) {
5741 monitor_devices[0] = NULL;
5742 serial_devices[i] = "mon:stdio";
5743 break;
5748 if (nb_numa_nodes > 0) {
5749 int i;
5751 if (nb_numa_nodes > smp_cpus) {
5752 nb_numa_nodes = smp_cpus;
5755 /* If no memory size if given for any node, assume the default case
5756 * and distribute the available memory equally across all nodes
5758 for (i = 0; i < nb_numa_nodes; i++) {
5759 if (node_mem[i] != 0)
5760 break;
5762 if (i == nb_numa_nodes) {
5763 uint64_t usedmem = 0;
5765 /* On Linux, the each node's border has to be 8MB aligned,
5766 * the final node gets the rest.
5768 for (i = 0; i < nb_numa_nodes - 1; i++) {
5769 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5770 usedmem += node_mem[i];
5772 node_mem[i] = ram_size - usedmem;
5775 for (i = 0; i < nb_numa_nodes; i++) {
5776 if (node_cpumask[i] != 0)
5777 break;
5779 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5780 * must cope with this anyway, because there are BIOSes out there in
5781 * real machines which also use this scheme.
5783 if (i == nb_numa_nodes) {
5784 for (i = 0; i < smp_cpus; i++) {
5785 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5790 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5791 const char *devname = monitor_devices[i];
5792 if (devname && strcmp(devname, "none")) {
5793 char label[32];
5794 if (i == 0) {
5795 snprintf(label, sizeof(label), "monitor");
5796 } else {
5797 snprintf(label, sizeof(label), "monitor%d", i);
5799 monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5800 if (!monitor_hds[i]) {
5801 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5802 devname);
5803 exit(1);
5808 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5809 const char *devname = serial_devices[i];
5810 if (devname && strcmp(devname, "none")) {
5811 char label[32];
5812 snprintf(label, sizeof(label), "serial%d", i);
5813 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5814 if (!serial_hds[i]) {
5815 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5816 devname);
5817 exit(1);
5822 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5823 const char *devname = parallel_devices[i];
5824 if (devname && strcmp(devname, "none")) {
5825 char label[32];
5826 snprintf(label, sizeof(label), "parallel%d", i);
5827 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5828 if (!parallel_hds[i]) {
5829 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5830 devname);
5831 exit(1);
5836 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5837 const char *devname = virtio_consoles[i];
5838 if (devname && strcmp(devname, "none")) {
5839 char label[32];
5840 snprintf(label, sizeof(label), "virtcon%d", i);
5841 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5842 if (!virtcon_hds[i]) {
5843 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5844 devname);
5845 exit(1);
5850 module_call_init(MODULE_INIT_DEVICE);
5852 if (watchdog) {
5853 i = select_watchdog(watchdog);
5854 if (i > 0)
5855 exit (i == 1 ? 1 : 0);
5858 if (machine->compat_props) {
5859 qdev_prop_register_compat(machine->compat_props);
5861 machine->init(ram_size, boot_devices,
5862 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5865 #ifndef _WIN32
5866 /* must be after terminal init, SDL library changes signal handlers */
5867 sighandler_setup();
5868 #endif
5870 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5871 for (i = 0; i < nb_numa_nodes; i++) {
5872 if (node_cpumask[i] & (1 << env->cpu_index)) {
5873 env->numa_node = i;
5878 current_machine = machine;
5880 /* init USB devices */
5881 if (usb_enabled) {
5882 foreach_device_config(DEV_USB, usb_parse);
5885 /* init generic devices */
5886 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5887 exit(1);
5889 if (!display_state)
5890 dumb_display_init();
5891 /* just use the first displaystate for the moment */
5892 ds = display_state;
5894 if (display_type == DT_DEFAULT) {
5895 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5896 display_type = DT_SDL;
5897 #else
5898 display_type = DT_VNC;
5899 vnc_display = "localhost:0,to=99";
5900 show_vnc_port = 1;
5901 #endif
5905 switch (display_type) {
5906 case DT_NOGRAPHIC:
5907 break;
5908 #if defined(CONFIG_CURSES)
5909 case DT_CURSES:
5910 curses_display_init(ds, full_screen);
5911 break;
5912 #endif
5913 #if defined(CONFIG_SDL)
5914 case DT_SDL:
5915 sdl_display_init(ds, full_screen, no_frame);
5916 break;
5917 #elif defined(CONFIG_COCOA)
5918 case DT_SDL:
5919 cocoa_display_init(ds, full_screen);
5920 break;
5921 #endif
5922 case DT_VNC:
5923 vnc_display_init(ds);
5924 if (vnc_display_open(ds, vnc_display) < 0)
5925 exit(1);
5927 if (show_vnc_port) {
5928 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5930 break;
5931 default:
5932 break;
5934 dpy_resize(ds);
5936 dcl = ds->listeners;
5937 while (dcl != NULL) {
5938 if (dcl->dpy_refresh != NULL) {
5939 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5940 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5942 dcl = dcl->next;
5945 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5946 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5947 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5950 text_consoles_set_display(display_state);
5951 qemu_chr_initial_reset();
5953 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5954 if (monitor_devices[i] && monitor_hds[i]) {
5955 monitor_init(monitor_hds[i],
5956 MONITOR_USE_READLINE |
5957 ((i == 0) ? MONITOR_IS_DEFAULT : 0));
5961 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5962 const char *devname = serial_devices[i];
5963 if (devname && strcmp(devname, "none")) {
5964 if (strstart(devname, "vc", 0))
5965 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5969 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5970 const char *devname = parallel_devices[i];
5971 if (devname && strcmp(devname, "none")) {
5972 if (strstart(devname, "vc", 0))
5973 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5977 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5978 const char *devname = virtio_consoles[i];
5979 if (virtcon_hds[i] && devname) {
5980 if (strstart(devname, "vc", 0))
5981 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5985 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5986 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5987 gdbstub_dev);
5988 exit(1);
5991 if (loadvm) {
5992 if (load_vmstate(cur_mon, loadvm) < 0) {
5993 autostart = 0;
5997 if (incoming) {
5998 qemu_start_incoming_migration(incoming);
5999 } else if (autostart) {
6000 vm_start();
6003 #ifndef _WIN32
6004 if (daemonize) {
6005 uint8_t status = 0;
6006 ssize_t len;
6008 again1:
6009 len = write(fds[1], &status, 1);
6010 if (len == -1 && (errno == EINTR))
6011 goto again1;
6013 if (len != 1)
6014 exit(1);
6016 chdir("/");
6017 TFR(fd = open("/dev/null", O_RDWR));
6018 if (fd == -1)
6019 exit(1);
6022 if (run_as) {
6023 pwd = getpwnam(run_as);
6024 if (!pwd) {
6025 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6026 exit(1);
6030 if (chroot_dir) {
6031 if (chroot(chroot_dir) < 0) {
6032 fprintf(stderr, "chroot failed\n");
6033 exit(1);
6035 chdir("/");
6038 if (run_as) {
6039 if (setgid(pwd->pw_gid) < 0) {
6040 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6041 exit(1);
6043 if (setuid(pwd->pw_uid) < 0) {
6044 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6045 exit(1);
6047 if (setuid(0) != -1) {
6048 fprintf(stderr, "Dropping privileges failed\n");
6049 exit(1);
6053 if (daemonize) {
6054 dup2(fd, 0);
6055 dup2(fd, 1);
6056 dup2(fd, 2);
6058 close(fd);
6060 #endif
6062 main_loop();
6063 quit_timers();
6064 net_cleanup();
6066 return 0;