test: Fix compilation rule for assembly files wrt autodependencies
[qemu-kvm/amd-iommu.git] / vl.c
blob888d481fee19105725d8a00a806e66774c45608a
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 perror("Failed to initialize win32 alarm timer");
1463 timeEndPeriod(data->period);
1464 return -1;
1467 return 0;
1470 static void win32_stop_timer(struct qemu_alarm_timer *t)
1472 struct qemu_alarm_win32 *data = t->priv;
1474 timeKillEvent(data->timerId);
1475 timeEndPeriod(data->period);
1478 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1480 struct qemu_alarm_win32 *data = t->priv;
1481 uint64_t nearest_delta_us;
1483 if (!active_timers[QEMU_TIMER_REALTIME] &&
1484 !active_timers[QEMU_TIMER_VIRTUAL])
1485 return;
1487 nearest_delta_us = qemu_next_deadline_dyntick();
1488 nearest_delta_us /= 1000;
1490 timeKillEvent(data->timerId);
1492 data->timerId = timeSetEvent(1,
1493 data->period,
1494 host_alarm_handler,
1495 (DWORD)t,
1496 TIME_ONESHOT | TIME_PERIODIC);
1498 if (!data->timerId) {
1499 perror("Failed to re-arm win32 alarm timer");
1501 timeEndPeriod(data->period);
1502 exit(1);
1506 #endif /* _WIN32 */
1508 static int init_timer_alarm(void)
1510 struct qemu_alarm_timer *t = NULL;
1511 int i, err = -1;
1513 for (i = 0; alarm_timers[i].name; i++) {
1514 t = &alarm_timers[i];
1516 err = t->start(t);
1517 if (!err)
1518 break;
1521 if (err) {
1522 err = -ENOENT;
1523 goto fail;
1526 alarm_timer = t;
1528 return 0;
1530 fail:
1531 return err;
1534 static void quit_timers(void)
1536 alarm_timer->stop(alarm_timer);
1537 alarm_timer = NULL;
1540 /***********************************************************/
1541 /* host time/date access */
1542 void qemu_get_timedate(struct tm *tm, int offset)
1544 time_t ti;
1545 struct tm *ret;
1547 time(&ti);
1548 ti += offset;
1549 if (rtc_date_offset == -1) {
1550 if (rtc_utc)
1551 ret = gmtime(&ti);
1552 else
1553 ret = localtime(&ti);
1554 } else {
1555 ti -= rtc_date_offset;
1556 ret = gmtime(&ti);
1559 memcpy(tm, ret, sizeof(struct tm));
1562 int qemu_timedate_diff(struct tm *tm)
1564 time_t seconds;
1566 if (rtc_date_offset == -1)
1567 if (rtc_utc)
1568 seconds = mktimegm(tm);
1569 else
1570 seconds = mktime(tm);
1571 else
1572 seconds = mktimegm(tm) + rtc_date_offset;
1574 return seconds - time(NULL);
1577 #ifdef _WIN32
1578 static void socket_cleanup(void)
1580 WSACleanup();
1583 static int socket_init(void)
1585 WSADATA Data;
1586 int ret, err;
1588 ret = WSAStartup(MAKEWORD(2,2), &Data);
1589 if (ret != 0) {
1590 err = WSAGetLastError();
1591 fprintf(stderr, "WSAStartup: %d\n", err);
1592 return -1;
1594 atexit(socket_cleanup);
1595 return 0;
1597 #endif
1599 /***********************************************************/
1600 /* Bluetooth support */
1601 static int nb_hcis;
1602 static int cur_hci;
1603 static struct HCIInfo *hci_table[MAX_NICS];
1605 static struct bt_vlan_s {
1606 struct bt_scatternet_s net;
1607 int id;
1608 struct bt_vlan_s *next;
1609 } *first_bt_vlan;
1611 /* find or alloc a new bluetooth "VLAN" */
1612 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1614 struct bt_vlan_s **pvlan, *vlan;
1615 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1616 if (vlan->id == id)
1617 return &vlan->net;
1619 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1620 vlan->id = id;
1621 pvlan = &first_bt_vlan;
1622 while (*pvlan != NULL)
1623 pvlan = &(*pvlan)->next;
1624 *pvlan = vlan;
1625 return &vlan->net;
1628 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1632 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1634 return -ENOTSUP;
1637 static struct HCIInfo null_hci = {
1638 .cmd_send = null_hci_send,
1639 .sco_send = null_hci_send,
1640 .acl_send = null_hci_send,
1641 .bdaddr_set = null_hci_addr_set,
1644 struct HCIInfo *qemu_next_hci(void)
1646 if (cur_hci == nb_hcis)
1647 return &null_hci;
1649 return hci_table[cur_hci++];
1652 static struct HCIInfo *hci_init(const char *str)
1654 char *endp;
1655 struct bt_scatternet_s *vlan = 0;
1657 if (!strcmp(str, "null"))
1658 /* null */
1659 return &null_hci;
1660 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1661 /* host[:hciN] */
1662 return bt_host_hci(str[4] ? str + 5 : "hci0");
1663 else if (!strncmp(str, "hci", 3)) {
1664 /* hci[,vlan=n] */
1665 if (str[3]) {
1666 if (!strncmp(str + 3, ",vlan=", 6)) {
1667 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1668 if (*endp)
1669 vlan = 0;
1671 } else
1672 vlan = qemu_find_bt_vlan(0);
1673 if (vlan)
1674 return bt_new_hci(vlan);
1677 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1679 return 0;
1682 static int bt_hci_parse(const char *str)
1684 struct HCIInfo *hci;
1685 bdaddr_t bdaddr;
1687 if (nb_hcis >= MAX_NICS) {
1688 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1689 return -1;
1692 hci = hci_init(str);
1693 if (!hci)
1694 return -1;
1696 bdaddr.b[0] = 0x52;
1697 bdaddr.b[1] = 0x54;
1698 bdaddr.b[2] = 0x00;
1699 bdaddr.b[3] = 0x12;
1700 bdaddr.b[4] = 0x34;
1701 bdaddr.b[5] = 0x56 + nb_hcis;
1702 hci->bdaddr_set(hci, bdaddr.b);
1704 hci_table[nb_hcis++] = hci;
1706 return 0;
1709 static void bt_vhci_add(int vlan_id)
1711 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1713 if (!vlan->slave)
1714 fprintf(stderr, "qemu: warning: adding a VHCI to "
1715 "an empty scatternet %i\n", vlan_id);
1717 bt_vhci_init(bt_new_hci(vlan));
1720 static struct bt_device_s *bt_device_add(const char *opt)
1722 struct bt_scatternet_s *vlan;
1723 int vlan_id = 0;
1724 char *endp = strstr(opt, ",vlan=");
1725 int len = (endp ? endp - opt : strlen(opt)) + 1;
1726 char devname[10];
1728 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1730 if (endp) {
1731 vlan_id = strtol(endp + 6, &endp, 0);
1732 if (*endp) {
1733 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1734 return 0;
1738 vlan = qemu_find_bt_vlan(vlan_id);
1740 if (!vlan->slave)
1741 fprintf(stderr, "qemu: warning: adding a slave device to "
1742 "an empty scatternet %i\n", vlan_id);
1744 if (!strcmp(devname, "keyboard"))
1745 return bt_keyboard_init(vlan);
1747 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1748 return 0;
1751 static int bt_parse(const char *opt)
1753 const char *endp, *p;
1754 int vlan;
1756 if (strstart(opt, "hci", &endp)) {
1757 if (!*endp || *endp == ',') {
1758 if (*endp)
1759 if (!strstart(endp, ",vlan=", 0))
1760 opt = endp + 1;
1762 return bt_hci_parse(opt);
1764 } else if (strstart(opt, "vhci", &endp)) {
1765 if (!*endp || *endp == ',') {
1766 if (*endp) {
1767 if (strstart(endp, ",vlan=", &p)) {
1768 vlan = strtol(p, (char **) &endp, 0);
1769 if (*endp) {
1770 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1771 return 1;
1773 } else {
1774 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1775 return 1;
1777 } else
1778 vlan = 0;
1780 bt_vhci_add(vlan);
1781 return 0;
1783 } else if (strstart(opt, "device:", &endp))
1784 return !bt_device_add(endp);
1786 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1787 return 1;
1790 /***********************************************************/
1791 /* QEMU Block devices */
1793 #define HD_ALIAS "index=%d,media=disk"
1794 #define CDROM_ALIAS "index=2,media=cdrom"
1795 #define FD_ALIAS "index=%d,if=floppy"
1796 #define PFLASH_ALIAS "if=pflash"
1797 #define MTD_ALIAS "if=mtd"
1798 #define SD_ALIAS "index=0,if=sd"
1800 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1802 va_list ap;
1803 char optstr[1024];
1804 QemuOpts *opts;
1806 va_start(ap, fmt);
1807 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1808 va_end(ap);
1810 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1811 if (!opts) {
1812 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1813 __FUNCTION__, optstr);
1814 return NULL;
1816 if (file)
1817 qemu_opt_set(opts, "file", file);
1818 return opts;
1821 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1823 DriveInfo *dinfo;
1825 /* seek interface, bus and unit */
1827 QTAILQ_FOREACH(dinfo, &drives, next) {
1828 if (dinfo->type == type &&
1829 dinfo->bus == bus &&
1830 dinfo->unit == unit)
1831 return dinfo;
1834 return NULL;
1837 DriveInfo *drive_get_by_id(const char *id)
1839 DriveInfo *dinfo;
1841 QTAILQ_FOREACH(dinfo, &drives, next) {
1842 if (strcmp(id, dinfo->id))
1843 continue;
1844 return dinfo;
1846 return NULL;
1849 int drive_get_max_bus(BlockInterfaceType type)
1851 int max_bus;
1852 DriveInfo *dinfo;
1854 max_bus = -1;
1855 QTAILQ_FOREACH(dinfo, &drives, next) {
1856 if(dinfo->type == type &&
1857 dinfo->bus > max_bus)
1858 max_bus = dinfo->bus;
1860 return max_bus;
1863 const char *drive_get_serial(BlockDriverState *bdrv)
1865 DriveInfo *dinfo;
1867 QTAILQ_FOREACH(dinfo, &drives, next) {
1868 if (dinfo->bdrv == bdrv)
1869 return dinfo->serial;
1872 return "\0";
1875 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1877 DriveInfo *dinfo;
1879 QTAILQ_FOREACH(dinfo, &drives, next) {
1880 if (dinfo->bdrv == bdrv)
1881 return dinfo->onerror;
1884 return BLOCK_ERR_STOP_ENOSPC;
1887 static void bdrv_format_print(void *opaque, const char *name)
1889 fprintf(stderr, " %s", name);
1892 void drive_uninit(BlockDriverState *bdrv)
1894 DriveInfo *dinfo;
1896 QTAILQ_FOREACH(dinfo, &drives, next) {
1897 if (dinfo->bdrv != bdrv)
1898 continue;
1899 qemu_opts_del(dinfo->opts);
1900 QTAILQ_REMOVE(&drives, dinfo, next);
1901 qemu_free(dinfo);
1902 break;
1906 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1907 int *fatal_error)
1909 const char *buf;
1910 const char *file = NULL;
1911 char devname[128];
1912 const char *serial;
1913 const char *mediastr = "";
1914 BlockInterfaceType type;
1915 enum { MEDIA_DISK, MEDIA_CDROM } media;
1916 int bus_id, unit_id;
1917 int cyls, heads, secs, translation;
1918 BlockDriver *drv = NULL;
1919 QEMUMachine *machine = opaque;
1920 int max_devs;
1921 int index;
1922 int cache;
1923 int aio = 0;
1924 int bdrv_flags, onerror;
1925 const char *devaddr;
1926 DriveInfo *dinfo;
1927 int is_extboot = 0;
1928 int snapshot = 0;
1930 *fatal_error = 1;
1932 translation = BIOS_ATA_TRANSLATION_AUTO;
1933 cache = 1;
1935 if (machine && machine->use_scsi) {
1936 type = IF_SCSI;
1937 max_devs = MAX_SCSI_DEVS;
1938 pstrcpy(devname, sizeof(devname), "scsi");
1939 } else {
1940 type = IF_IDE;
1941 max_devs = MAX_IDE_DEVS;
1942 pstrcpy(devname, sizeof(devname), "ide");
1944 media = MEDIA_DISK;
1946 /* extract parameters */
1947 bus_id = qemu_opt_get_number(opts, "bus", 0);
1948 unit_id = qemu_opt_get_number(opts, "unit", -1);
1949 index = qemu_opt_get_number(opts, "index", -1);
1951 cyls = qemu_opt_get_number(opts, "cyls", 0);
1952 heads = qemu_opt_get_number(opts, "heads", 0);
1953 secs = qemu_opt_get_number(opts, "secs", 0);
1955 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1957 file = qemu_opt_get(opts, "file");
1958 serial = qemu_opt_get(opts, "serial");
1960 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1961 pstrcpy(devname, sizeof(devname), buf);
1962 if (!strcmp(buf, "ide")) {
1963 type = IF_IDE;
1964 max_devs = MAX_IDE_DEVS;
1965 } else if (!strcmp(buf, "scsi")) {
1966 type = IF_SCSI;
1967 max_devs = MAX_SCSI_DEVS;
1968 } else if (!strcmp(buf, "floppy")) {
1969 type = IF_FLOPPY;
1970 max_devs = 0;
1971 } else if (!strcmp(buf, "pflash")) {
1972 type = IF_PFLASH;
1973 max_devs = 0;
1974 } else if (!strcmp(buf, "mtd")) {
1975 type = IF_MTD;
1976 max_devs = 0;
1977 } else if (!strcmp(buf, "sd")) {
1978 type = IF_SD;
1979 max_devs = 0;
1980 } else if (!strcmp(buf, "virtio")) {
1981 type = IF_VIRTIO;
1982 max_devs = 0;
1983 } else if (!strcmp(buf, "xen")) {
1984 type = IF_XEN;
1985 max_devs = 0;
1986 } else if (!strcmp(buf, "none")) {
1987 type = IF_NONE;
1988 max_devs = 0;
1989 } else {
1990 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1991 return NULL;
1995 if (cyls || heads || secs) {
1996 if (cyls < 1 || cyls > 16383) {
1997 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1998 return NULL;
2000 if (heads < 1 || heads > 16) {
2001 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2002 return NULL;
2004 if (secs < 1 || secs > 63) {
2005 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2006 return NULL;
2010 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2011 if (!cyls) {
2012 fprintf(stderr,
2013 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2014 buf);
2015 return NULL;
2017 if (!strcmp(buf, "none"))
2018 translation = BIOS_ATA_TRANSLATION_NONE;
2019 else if (!strcmp(buf, "lba"))
2020 translation = BIOS_ATA_TRANSLATION_LBA;
2021 else if (!strcmp(buf, "auto"))
2022 translation = BIOS_ATA_TRANSLATION_AUTO;
2023 else {
2024 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2025 return NULL;
2029 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2030 if (!strcmp(buf, "disk")) {
2031 media = MEDIA_DISK;
2032 } else if (!strcmp(buf, "cdrom")) {
2033 if (cyls || secs || heads) {
2034 fprintf(stderr,
2035 "qemu: '%s' invalid physical CHS format\n", buf);
2036 return NULL;
2038 media = MEDIA_CDROM;
2039 } else {
2040 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2041 return NULL;
2045 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2046 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2047 cache = 0;
2048 else if (!strcmp(buf, "writethrough"))
2049 cache = 1;
2050 else if (!strcmp(buf, "writeback"))
2051 cache = 2;
2052 else {
2053 fprintf(stderr, "qemu: invalid cache option\n");
2054 return NULL;
2058 #ifdef CONFIG_LINUX_AIO
2059 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2060 if (!strcmp(buf, "threads"))
2061 aio = 0;
2062 else if (!strcmp(buf, "native"))
2063 aio = 1;
2064 else {
2065 fprintf(stderr, "qemu: invalid aio option\n");
2066 return NULL;
2069 #endif
2071 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2072 if (strcmp(buf, "?") == 0) {
2073 fprintf(stderr, "qemu: Supported formats:");
2074 bdrv_iterate_format(bdrv_format_print, NULL);
2075 fprintf(stderr, "\n");
2076 return NULL;
2078 drv = bdrv_find_format(buf);
2079 if (!drv) {
2080 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2081 return NULL;
2085 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
2086 if (is_extboot && extboot_drive) {
2087 fprintf(stderr, "qemu: two bootable drives specified\n");
2088 return NULL;
2091 onerror = BLOCK_ERR_STOP_ENOSPC;
2092 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2093 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2094 fprintf(stderr, "werror is no supported by this format\n");
2095 return NULL;
2097 if (!strcmp(buf, "ignore"))
2098 onerror = BLOCK_ERR_IGNORE;
2099 else if (!strcmp(buf, "enospc"))
2100 onerror = BLOCK_ERR_STOP_ENOSPC;
2101 else if (!strcmp(buf, "stop"))
2102 onerror = BLOCK_ERR_STOP_ANY;
2103 else if (!strcmp(buf, "report"))
2104 onerror = BLOCK_ERR_REPORT;
2105 else {
2106 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2107 return NULL;
2111 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2112 if (type != IF_VIRTIO) {
2113 fprintf(stderr, "addr is not supported\n");
2114 return NULL;
2118 /* compute bus and unit according index */
2120 if (index != -1) {
2121 if (bus_id != 0 || unit_id != -1) {
2122 fprintf(stderr,
2123 "qemu: index cannot be used with bus and unit\n");
2124 return NULL;
2126 if (max_devs == 0)
2128 unit_id = index;
2129 bus_id = 0;
2130 } else {
2131 unit_id = index % max_devs;
2132 bus_id = index / max_devs;
2136 /* if user doesn't specify a unit_id,
2137 * try to find the first free
2140 if (unit_id == -1) {
2141 unit_id = 0;
2142 while (drive_get(type, bus_id, unit_id) != NULL) {
2143 unit_id++;
2144 if (max_devs && unit_id >= max_devs) {
2145 unit_id -= max_devs;
2146 bus_id++;
2151 /* check unit id */
2153 if (max_devs && unit_id >= max_devs) {
2154 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2155 unit_id, max_devs - 1);
2156 return NULL;
2160 * ignore multiple definitions
2163 if (drive_get(type, bus_id, unit_id) != NULL) {
2164 *fatal_error = 0;
2165 return NULL;
2168 /* init */
2170 dinfo = qemu_mallocz(sizeof(*dinfo));
2171 if ((buf = qemu_opts_id(opts)) != NULL) {
2172 dinfo->id = qemu_strdup(buf);
2173 } else {
2174 /* no id supplied -> create one */
2175 dinfo->id = qemu_mallocz(32);
2176 if (type == IF_IDE || type == IF_SCSI)
2177 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2178 if (max_devs)
2179 snprintf(dinfo->id, 32, "%s%i%s%i",
2180 devname, bus_id, mediastr, unit_id);
2181 else
2182 snprintf(dinfo->id, 32, "%s%s%i",
2183 devname, mediastr, unit_id);
2185 dinfo->bdrv = bdrv_new(dinfo->id);
2186 dinfo->devaddr = devaddr;
2187 dinfo->type = type;
2188 dinfo->bus = bus_id;
2189 dinfo->unit = unit_id;
2190 dinfo->onerror = onerror;
2191 dinfo->opts = opts;
2192 if (serial)
2193 strncpy(dinfo->serial, serial, sizeof(serial));
2194 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2195 if (is_extboot) {
2196 extboot_drive = dinfo;
2199 switch(type) {
2200 case IF_IDE:
2201 case IF_SCSI:
2202 case IF_XEN:
2203 switch(media) {
2204 case MEDIA_DISK:
2205 if (cyls != 0) {
2206 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2207 bdrv_set_translation_hint(dinfo->bdrv, translation);
2209 break;
2210 case MEDIA_CDROM:
2211 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2212 break;
2214 break;
2215 case IF_SD:
2216 /* FIXME: This isn't really a floppy, but it's a reasonable
2217 approximation. */
2218 case IF_FLOPPY:
2219 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2220 break;
2221 case IF_PFLASH:
2222 case IF_MTD:
2223 case IF_NONE:
2224 break;
2225 case IF_VIRTIO:
2226 /* add virtio block device */
2227 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2228 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2229 qemu_opt_set(opts, "drive", dinfo->id);
2230 if (devaddr)
2231 qemu_opt_set(opts, "addr", devaddr);
2232 break;
2233 case IF_COUNT:
2234 abort();
2236 if (!file) {
2237 *fatal_error = 0;
2238 return NULL;
2240 bdrv_flags = 0;
2241 if (snapshot) {
2242 bdrv_flags |= BDRV_O_SNAPSHOT;
2243 cache = 2; /* always use write-back with snapshot */
2245 if (cache == 0) /* no caching */
2246 bdrv_flags |= BDRV_O_NOCACHE;
2247 else if (cache == 2) /* write-back */
2248 bdrv_flags |= BDRV_O_CACHE_WB;
2250 if (aio == 1) {
2251 bdrv_flags |= BDRV_O_NATIVE_AIO;
2252 } else {
2253 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2256 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2257 fprintf(stderr, "qemu: could not open disk image %s\n",
2258 file);
2259 return NULL;
2262 if (bdrv_key_required(dinfo->bdrv))
2263 autostart = 0;
2264 *fatal_error = 0;
2265 return dinfo;
2268 static int drive_init_func(QemuOpts *opts, void *opaque)
2270 QEMUMachine *machine = opaque;
2271 int fatal_error = 0;
2273 if (drive_init(opts, machine, &fatal_error) == NULL) {
2274 if (fatal_error)
2275 return 1;
2277 return 0;
2280 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2282 if (NULL == qemu_opt_get(opts, "snapshot")) {
2283 qemu_opt_set(opts, "snapshot", "on");
2285 return 0;
2288 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2290 boot_set_handler = func;
2291 boot_set_opaque = opaque;
2294 int qemu_boot_set(const char *boot_devices)
2296 if (!boot_set_handler) {
2297 return -EINVAL;
2299 return boot_set_handler(boot_set_opaque, boot_devices);
2302 static int parse_bootdevices(char *devices)
2304 /* We just do some generic consistency checks */
2305 const char *p;
2306 int bitmap = 0;
2308 for (p = devices; *p != '\0'; p++) {
2309 /* Allowed boot devices are:
2310 * a-b: floppy disk drives
2311 * c-f: IDE disk drives
2312 * g-m: machine implementation dependant drives
2313 * n-p: network devices
2314 * It's up to each machine implementation to check if the given boot
2315 * devices match the actual hardware implementation and firmware
2316 * features.
2318 if (*p < 'a' || *p > 'p') {
2319 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2320 exit(1);
2322 if (bitmap & (1 << (*p - 'a'))) {
2323 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2324 exit(1);
2326 bitmap |= 1 << (*p - 'a');
2328 return bitmap;
2331 static void restore_boot_devices(void *opaque)
2333 char *standard_boot_devices = opaque;
2335 qemu_boot_set(standard_boot_devices);
2337 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2338 qemu_free(standard_boot_devices);
2341 static void numa_add(const char *optarg)
2343 char option[128];
2344 char *endptr;
2345 unsigned long long value, endvalue;
2346 int nodenr;
2348 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2349 if (!strcmp(option, "node")) {
2350 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2351 nodenr = nb_numa_nodes;
2352 } else {
2353 nodenr = strtoull(option, NULL, 10);
2356 if (get_param_value(option, 128, "mem", optarg) == 0) {
2357 node_mem[nodenr] = 0;
2358 } else {
2359 value = strtoull(option, &endptr, 0);
2360 switch (*endptr) {
2361 case 0: case 'M': case 'm':
2362 value <<= 20;
2363 break;
2364 case 'G': case 'g':
2365 value <<= 30;
2366 break;
2368 node_mem[nodenr] = value;
2370 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2371 node_cpumask[nodenr] = 0;
2372 } else {
2373 value = strtoull(option, &endptr, 10);
2374 if (value >= 64) {
2375 value = 63;
2376 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2377 } else {
2378 if (*endptr == '-') {
2379 endvalue = strtoull(endptr+1, &endptr, 10);
2380 if (endvalue >= 63) {
2381 endvalue = 62;
2382 fprintf(stderr,
2383 "only 63 CPUs in NUMA mode supported.\n");
2385 value = (1 << (endvalue + 1)) - (1 << value);
2386 } else {
2387 value = 1 << value;
2390 node_cpumask[nodenr] = value;
2392 nb_numa_nodes++;
2394 return;
2397 static void smp_parse(const char *optarg)
2399 int smp, sockets = 0, threads = 0, cores = 0;
2400 char *endptr;
2401 char option[128];
2403 smp = strtoul(optarg, &endptr, 10);
2404 if (endptr != optarg) {
2405 if (*endptr == ',') {
2406 endptr++;
2409 if (get_param_value(option, 128, "sockets", endptr) != 0)
2410 sockets = strtoull(option, NULL, 10);
2411 if (get_param_value(option, 128, "cores", endptr) != 0)
2412 cores = strtoull(option, NULL, 10);
2413 if (get_param_value(option, 128, "threads", endptr) != 0)
2414 threads = strtoull(option, NULL, 10);
2415 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2416 max_cpus = strtoull(option, NULL, 10);
2418 /* compute missing values, prefer sockets over cores over threads */
2419 if (smp == 0 || sockets == 0) {
2420 sockets = sockets > 0 ? sockets : 1;
2421 cores = cores > 0 ? cores : 1;
2422 threads = threads > 0 ? threads : 1;
2423 if (smp == 0) {
2424 smp = cores * threads * sockets;
2425 } else {
2426 sockets = smp / (cores * threads);
2428 } else {
2429 if (cores == 0) {
2430 threads = threads > 0 ? threads : 1;
2431 cores = smp / (sockets * threads);
2432 } else {
2433 if (sockets == 0) {
2434 sockets = smp / (cores * threads);
2435 } else {
2436 threads = smp / (cores * sockets);
2440 smp_cpus = smp;
2441 smp_cores = cores > 0 ? cores : 1;
2442 smp_threads = threads > 0 ? threads : 1;
2443 if (max_cpus == 0)
2444 max_cpus = smp_cpus;
2447 /***********************************************************/
2448 /* USB devices */
2450 static void usb_msd_password_cb(void *opaque, int err)
2452 USBDevice *dev = opaque;
2454 if (!err)
2455 usb_device_attach(dev);
2456 else
2457 dev->info->handle_destroy(dev);
2460 static struct {
2461 const char *name;
2462 const char *qdev;
2463 } usbdevs[] = {
2465 .name = "mouse",
2466 .qdev = "QEMU USB Mouse",
2468 .name = "tablet",
2469 .qdev = "QEMU USB Tablet",
2471 .name = "keyboard",
2472 .qdev = "QEMU USB Keyboard",
2474 .name = "wacom-tablet",
2475 .qdev = "QEMU PenPartner Tablet",
2479 static int usb_device_add(const char *devname, int is_hotplug)
2481 const char *p;
2482 USBBus *bus = usb_bus_find(-1 /* any */);
2483 USBDevice *dev = NULL;
2484 int i;
2486 if (!usb_enabled)
2487 return -1;
2489 /* simple devices which don't need extra care */
2490 for (i = 0; i < ARRAY_SIZE(usbdevs); i++) {
2491 if (strcmp(devname, usbdevs[i].name) != 0)
2492 continue;
2493 dev = usb_create_simple(bus, usbdevs[i].qdev);
2494 goto done;
2497 /* the other ones */
2498 if (strstart(devname, "host:", &p)) {
2499 dev = usb_host_device_open(p);
2500 } else if (strstart(devname, "disk:", &p)) {
2501 BlockDriverState *bs;
2503 dev = usb_msd_init(p);
2504 if (!dev)
2505 return -1;
2506 bs = usb_msd_get_bdrv(dev);
2507 if (bdrv_key_required(bs)) {
2508 autostart = 0;
2509 if (is_hotplug) {
2510 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2511 dev);
2512 return 0;
2515 } else if (strstart(devname, "serial:", &p)) {
2516 dev = usb_serial_init(p);
2517 #ifdef CONFIG_BRLAPI
2518 } else if (!strcmp(devname, "braille")) {
2519 dev = usb_baum_init();
2520 #endif
2521 } else if (strstart(devname, "net:", &p)) {
2522 int nic = nb_nics;
2524 if (net_client_init(NULL, "nic", p) < 0)
2525 return -1;
2526 nd_table[nic].model = "usb";
2527 dev = usb_net_init(&nd_table[nic]);
2528 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2529 dev = usb_bt_init(devname[2] ? hci_init(p) :
2530 bt_new_hci(qemu_find_bt_vlan(0)));
2531 } else {
2532 return -1;
2534 if (!dev)
2535 return -1;
2537 done:
2538 return 0;
2541 static int usb_device_del(const char *devname)
2543 int bus_num, addr;
2544 const char *p;
2546 if (strstart(devname, "host:", &p))
2547 return usb_host_device_close(p);
2549 if (!usb_enabled)
2550 return -1;
2552 p = strchr(devname, '.');
2553 if (!p)
2554 return -1;
2555 bus_num = strtoul(devname, NULL, 0);
2556 addr = strtoul(p + 1, NULL, 0);
2558 return usb_device_delete_addr(bus_num, addr);
2561 static int usb_parse(const char *cmdline)
2563 return usb_device_add(cmdline, 0);
2566 void do_usb_add(Monitor *mon, const QDict *qdict)
2568 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2571 void do_usb_del(Monitor *mon, const QDict *qdict)
2573 usb_device_del(qdict_get_str(qdict, "devname"));
2576 /***********************************************************/
2577 /* PCMCIA/Cardbus */
2579 static struct pcmcia_socket_entry_s {
2580 PCMCIASocket *socket;
2581 struct pcmcia_socket_entry_s *next;
2582 } *pcmcia_sockets = 0;
2584 void pcmcia_socket_register(PCMCIASocket *socket)
2586 struct pcmcia_socket_entry_s *entry;
2588 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2589 entry->socket = socket;
2590 entry->next = pcmcia_sockets;
2591 pcmcia_sockets = entry;
2594 void pcmcia_socket_unregister(PCMCIASocket *socket)
2596 struct pcmcia_socket_entry_s *entry, **ptr;
2598 ptr = &pcmcia_sockets;
2599 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2600 if (entry->socket == socket) {
2601 *ptr = entry->next;
2602 qemu_free(entry);
2606 void pcmcia_info(Monitor *mon)
2608 struct pcmcia_socket_entry_s *iter;
2610 if (!pcmcia_sockets)
2611 monitor_printf(mon, "No PCMCIA sockets\n");
2613 for (iter = pcmcia_sockets; iter; iter = iter->next)
2614 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2615 iter->socket->attached ? iter->socket->card_string :
2616 "Empty");
2619 /***********************************************************/
2620 /* register display */
2622 struct DisplayAllocator default_allocator = {
2623 defaultallocator_create_displaysurface,
2624 defaultallocator_resize_displaysurface,
2625 defaultallocator_free_displaysurface
2628 void register_displaystate(DisplayState *ds)
2630 DisplayState **s;
2631 s = &display_state;
2632 while (*s != NULL)
2633 s = &(*s)->next;
2634 ds->next = NULL;
2635 *s = ds;
2638 DisplayState *get_displaystate(void)
2640 return display_state;
2643 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2645 if(ds->allocator == &default_allocator) ds->allocator = da;
2646 return ds->allocator;
2649 /* dumb display */
2651 static void dumb_display_init(void)
2653 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2654 ds->allocator = &default_allocator;
2655 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2656 register_displaystate(ds);
2659 /***********************************************************/
2660 /* I/O handling */
2662 typedef struct IOHandlerRecord {
2663 int fd;
2664 IOCanRWHandler *fd_read_poll;
2665 IOHandler *fd_read;
2666 IOHandler *fd_write;
2667 int deleted;
2668 void *opaque;
2669 /* temporary data */
2670 struct pollfd *ufd;
2671 struct IOHandlerRecord *next;
2672 } IOHandlerRecord;
2674 static IOHandlerRecord *first_io_handler;
2676 /* XXX: fd_read_poll should be suppressed, but an API change is
2677 necessary in the character devices to suppress fd_can_read(). */
2678 int qemu_set_fd_handler2(int fd,
2679 IOCanRWHandler *fd_read_poll,
2680 IOHandler *fd_read,
2681 IOHandler *fd_write,
2682 void *opaque)
2684 IOHandlerRecord **pioh, *ioh;
2686 if (!fd_read && !fd_write) {
2687 pioh = &first_io_handler;
2688 for(;;) {
2689 ioh = *pioh;
2690 if (ioh == NULL)
2691 break;
2692 if (ioh->fd == fd) {
2693 ioh->deleted = 1;
2694 break;
2696 pioh = &ioh->next;
2698 } else {
2699 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2700 if (ioh->fd == fd)
2701 goto found;
2703 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2704 ioh->next = first_io_handler;
2705 first_io_handler = ioh;
2706 found:
2707 ioh->fd = fd;
2708 ioh->fd_read_poll = fd_read_poll;
2709 ioh->fd_read = fd_read;
2710 ioh->fd_write = fd_write;
2711 ioh->opaque = opaque;
2712 ioh->deleted = 0;
2714 qemu_notify_event();
2715 return 0;
2718 int qemu_set_fd_handler(int fd,
2719 IOHandler *fd_read,
2720 IOHandler *fd_write,
2721 void *opaque)
2723 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2726 #ifdef _WIN32
2727 /***********************************************************/
2728 /* Polling handling */
2730 typedef struct PollingEntry {
2731 PollingFunc *func;
2732 void *opaque;
2733 struct PollingEntry *next;
2734 } PollingEntry;
2736 static PollingEntry *first_polling_entry;
2738 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2740 PollingEntry **ppe, *pe;
2741 pe = qemu_mallocz(sizeof(PollingEntry));
2742 pe->func = func;
2743 pe->opaque = opaque;
2744 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2745 *ppe = pe;
2746 return 0;
2749 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2751 PollingEntry **ppe, *pe;
2752 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2753 pe = *ppe;
2754 if (pe->func == func && pe->opaque == opaque) {
2755 *ppe = pe->next;
2756 qemu_free(pe);
2757 break;
2762 /***********************************************************/
2763 /* Wait objects support */
2764 typedef struct WaitObjects {
2765 int num;
2766 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2767 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2768 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2769 } WaitObjects;
2771 static WaitObjects wait_objects = {0};
2773 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2775 WaitObjects *w = &wait_objects;
2777 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2778 return -1;
2779 w->events[w->num] = handle;
2780 w->func[w->num] = func;
2781 w->opaque[w->num] = opaque;
2782 w->num++;
2783 return 0;
2786 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2788 int i, found;
2789 WaitObjects *w = &wait_objects;
2791 found = 0;
2792 for (i = 0; i < w->num; i++) {
2793 if (w->events[i] == handle)
2794 found = 1;
2795 if (found) {
2796 w->events[i] = w->events[i + 1];
2797 w->func[i] = w->func[i + 1];
2798 w->opaque[i] = w->opaque[i + 1];
2801 if (found)
2802 w->num--;
2804 #endif
2806 /***********************************************************/
2807 /* ram save/restore */
2809 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2810 #define RAM_SAVE_FLAG_COMPRESS 0x02
2811 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2812 #define RAM_SAVE_FLAG_PAGE 0x08
2813 #define RAM_SAVE_FLAG_EOS 0x10
2815 static int is_dup_page(uint8_t *page, uint8_t ch)
2817 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2818 uint32_t *array = (uint32_t *)page;
2819 int i;
2821 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2822 if (array[i] != val)
2823 return 0;
2826 return 1;
2829 static int ram_save_block(QEMUFile *f)
2831 static ram_addr_t current_addr = 0;
2832 ram_addr_t saved_addr = current_addr;
2833 ram_addr_t addr = 0;
2834 int found = 0;
2836 while (addr < last_ram_offset) {
2837 if (kvm_enabled() && current_addr == 0) {
2838 int r;
2839 r = kvm_update_dirty_pages_log();
2840 if (r) {
2841 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
2842 qemu_file_set_error(f);
2843 return 0;
2846 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2847 uint8_t *p;
2849 cpu_physical_memory_reset_dirty(current_addr,
2850 current_addr + TARGET_PAGE_SIZE,
2851 MIGRATION_DIRTY_FLAG);
2853 p = qemu_get_ram_ptr(current_addr);
2855 if (is_dup_page(p, *p)) {
2856 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2857 qemu_put_byte(f, *p);
2858 } else {
2859 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2860 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2863 found = 1;
2864 break;
2866 addr += TARGET_PAGE_SIZE;
2867 current_addr = (saved_addr + addr) % last_ram_offset;
2870 return found;
2873 static uint64_t bytes_transferred = 0;
2875 static ram_addr_t ram_save_remaining(void)
2877 ram_addr_t addr;
2878 ram_addr_t count = 0;
2880 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2881 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2882 count++;
2885 return count;
2888 uint64_t ram_bytes_remaining(void)
2890 return ram_save_remaining() * TARGET_PAGE_SIZE;
2893 uint64_t ram_bytes_transferred(void)
2895 return bytes_transferred;
2898 uint64_t ram_bytes_total(void)
2900 return last_ram_offset;
2903 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
2905 ram_addr_t addr;
2906 uint64_t bytes_transferred_last;
2907 double bwidth = 0;
2908 uint64_t expected_time = 0;
2910 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2911 qemu_file_set_error(f);
2912 return 0;
2915 if (stage == 1) {
2916 /* Make sure all dirty bits are set */
2917 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2918 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2919 cpu_physical_memory_set_dirty(addr);
2922 /* Enable dirty memory tracking */
2923 cpu_physical_memory_set_dirty_tracking(1);
2925 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2928 bytes_transferred_last = bytes_transferred;
2929 bwidth = get_clock();
2931 while (!qemu_file_rate_limit(f)) {
2932 int ret;
2934 ret = ram_save_block(f);
2935 bytes_transferred += ret * TARGET_PAGE_SIZE;
2936 if (ret == 0) /* no more blocks */
2937 break;
2940 bwidth = get_clock() - bwidth;
2941 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2943 /* if we haven't transferred anything this round, force expected_time to a
2944 * a very high value, but without crashing */
2945 if (bwidth == 0)
2946 bwidth = 0.000001;
2948 /* try transferring iterative blocks of memory */
2950 if (stage == 3) {
2952 /* flush all remaining blocks regardless of rate limiting */
2953 while (ram_save_block(f) != 0) {
2954 bytes_transferred += TARGET_PAGE_SIZE;
2956 cpu_physical_memory_set_dirty_tracking(0);
2959 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2961 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2963 return (stage == 2) && (expected_time <= migrate_max_downtime());
2966 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2968 ram_addr_t addr;
2969 int flags;
2971 if (version_id != 3)
2972 return -EINVAL;
2974 do {
2975 addr = qemu_get_be64(f);
2977 flags = addr & ~TARGET_PAGE_MASK;
2978 addr &= TARGET_PAGE_MASK;
2980 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2981 if (addr != last_ram_offset)
2982 return -EINVAL;
2985 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2986 uint8_t ch = qemu_get_byte(f);
2987 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2988 #ifndef _WIN32
2989 if (ch == 0 &&
2990 (!kvm_enabled() || kvm_has_sync_mmu())) {
2991 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2993 #endif
2994 } else if (flags & RAM_SAVE_FLAG_PAGE)
2995 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2996 } while (!(flags & RAM_SAVE_FLAG_EOS));
2998 return 0;
3001 void qemu_service_io(void)
3003 qemu_notify_event();
3006 /***********************************************************/
3007 /* bottom halves (can be seen as timers which expire ASAP) */
3009 struct QEMUBH {
3010 QEMUBHFunc *cb;
3011 void *opaque;
3012 int scheduled;
3013 int idle;
3014 int deleted;
3015 QEMUBH *next;
3018 static QEMUBH *first_bh = NULL;
3020 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3022 QEMUBH *bh;
3023 bh = qemu_mallocz(sizeof(QEMUBH));
3024 bh->cb = cb;
3025 bh->opaque = opaque;
3026 bh->next = first_bh;
3027 first_bh = bh;
3028 return bh;
3031 int qemu_bh_poll(void)
3033 QEMUBH *bh, **bhp;
3034 int ret;
3036 ret = 0;
3037 for (bh = first_bh; bh; bh = bh->next) {
3038 if (!bh->deleted && bh->scheduled) {
3039 bh->scheduled = 0;
3040 if (!bh->idle)
3041 ret = 1;
3042 bh->idle = 0;
3043 bh->cb(bh->opaque);
3047 /* remove deleted bhs */
3048 bhp = &first_bh;
3049 while (*bhp) {
3050 bh = *bhp;
3051 if (bh->deleted) {
3052 *bhp = bh->next;
3053 qemu_free(bh);
3054 } else
3055 bhp = &bh->next;
3058 return ret;
3061 void qemu_bh_schedule_idle(QEMUBH *bh)
3063 if (bh->scheduled)
3064 return;
3065 bh->scheduled = 1;
3066 bh->idle = 1;
3069 void qemu_bh_schedule(QEMUBH *bh)
3071 if (bh->scheduled)
3072 return;
3073 bh->scheduled = 1;
3074 bh->idle = 0;
3075 /* stop the currently executing CPU to execute the BH ASAP */
3076 qemu_notify_event();
3079 void qemu_bh_cancel(QEMUBH *bh)
3081 bh->scheduled = 0;
3084 void qemu_bh_delete(QEMUBH *bh)
3086 bh->scheduled = 0;
3087 bh->deleted = 1;
3090 static void qemu_bh_update_timeout(int *timeout)
3092 QEMUBH *bh;
3094 for (bh = first_bh; bh; bh = bh->next) {
3095 if (!bh->deleted && bh->scheduled) {
3096 if (bh->idle) {
3097 /* idle bottom halves will be polled at least
3098 * every 10ms */
3099 *timeout = MIN(10, *timeout);
3100 } else {
3101 /* non-idle bottom halves will be executed
3102 * immediately */
3103 *timeout = 0;
3104 break;
3110 /***********************************************************/
3111 /* machine registration */
3113 static QEMUMachine *first_machine = NULL;
3114 QEMUMachine *current_machine = NULL;
3116 int qemu_register_machine(QEMUMachine *m)
3118 QEMUMachine **pm;
3119 pm = &first_machine;
3120 while (*pm != NULL)
3121 pm = &(*pm)->next;
3122 m->next = NULL;
3123 *pm = m;
3124 return 0;
3127 static QEMUMachine *find_machine(const char *name)
3129 QEMUMachine *m;
3131 for(m = first_machine; m != NULL; m = m->next) {
3132 if (!strcmp(m->name, name))
3133 return m;
3134 if (m->alias && !strcmp(m->alias, name))
3135 return m;
3137 return NULL;
3140 static QEMUMachine *find_default_machine(void)
3142 QEMUMachine *m;
3144 for(m = first_machine; m != NULL; m = m->next) {
3145 if (m->is_default) {
3146 return m;
3149 return NULL;
3152 /***********************************************************/
3153 /* main execution loop */
3155 static void gui_update(void *opaque)
3157 uint64_t interval = GUI_REFRESH_INTERVAL;
3158 DisplayState *ds = opaque;
3159 DisplayChangeListener *dcl = ds->listeners;
3161 dpy_refresh(ds);
3163 while (dcl != NULL) {
3164 if (dcl->gui_timer_interval &&
3165 dcl->gui_timer_interval < interval)
3166 interval = dcl->gui_timer_interval;
3167 dcl = dcl->next;
3169 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3172 static void nographic_update(void *opaque)
3174 uint64_t interval = GUI_REFRESH_INTERVAL;
3176 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3179 struct vm_change_state_entry {
3180 VMChangeStateHandler *cb;
3181 void *opaque;
3182 QLIST_ENTRY (vm_change_state_entry) entries;
3185 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3187 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3188 void *opaque)
3190 VMChangeStateEntry *e;
3192 e = qemu_mallocz(sizeof (*e));
3194 e->cb = cb;
3195 e->opaque = opaque;
3196 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3197 return e;
3200 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3202 QLIST_REMOVE (e, entries);
3203 qemu_free (e);
3206 static void vm_state_notify(int running, int reason)
3208 VMChangeStateEntry *e;
3210 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3211 e->cb(e->opaque, running, reason);
3215 static void resume_all_vcpus(void);
3216 static void pause_all_vcpus(void);
3218 void vm_start(void)
3220 if (!vm_running) {
3221 cpu_enable_ticks();
3222 vm_running = 1;
3223 vm_state_notify(1, 0);
3224 qemu_rearm_alarm_timer(alarm_timer);
3225 resume_all_vcpus();
3229 /* reset/shutdown handler */
3231 typedef struct QEMUResetEntry {
3232 QTAILQ_ENTRY(QEMUResetEntry) entry;
3233 QEMUResetHandler *func;
3234 void *opaque;
3235 } QEMUResetEntry;
3237 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3238 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3239 static int reset_requested;
3240 static int shutdown_requested;
3241 static int powerdown_requested;
3242 static int debug_requested;
3243 static int vmstop_requested;
3245 int qemu_no_shutdown(void)
3247 int r = no_shutdown;
3248 no_shutdown = 0;
3249 return r;
3252 int qemu_shutdown_requested(void)
3254 int r = shutdown_requested;
3255 shutdown_requested = 0;
3256 return r;
3259 int qemu_reset_requested(void)
3261 int r = reset_requested;
3262 reset_requested = 0;
3263 return r;
3266 int qemu_powerdown_requested(void)
3268 int r = powerdown_requested;
3269 powerdown_requested = 0;
3270 return r;
3273 static int qemu_debug_requested(void)
3275 int r = debug_requested;
3276 debug_requested = 0;
3277 return r;
3280 static int qemu_vmstop_requested(void)
3282 int r = vmstop_requested;
3283 vmstop_requested = 0;
3284 return r;
3287 static void do_vm_stop(int reason)
3289 if (vm_running) {
3290 cpu_disable_ticks();
3291 vm_running = 0;
3292 pause_all_vcpus();
3293 vm_state_notify(0, reason);
3297 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3299 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3301 re->func = func;
3302 re->opaque = opaque;
3303 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3306 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3308 QEMUResetEntry *re;
3310 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3311 if (re->func == func && re->opaque == opaque) {
3312 QTAILQ_REMOVE(&reset_handlers, re, entry);
3313 qemu_free(re);
3314 return;
3319 void qemu_system_reset(void)
3321 QEMUResetEntry *re, *nre;
3323 /* reset all devices */
3324 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3325 re->func(re->opaque);
3329 void qemu_system_reset_request(void)
3331 if (no_reboot) {
3332 shutdown_requested = 1;
3333 } else {
3334 reset_requested = 1;
3336 if (cpu_single_env) {
3337 cpu_single_env->stopped = 1;
3339 qemu_notify_event();
3342 void qemu_system_shutdown_request(void)
3344 shutdown_requested = 1;
3345 qemu_notify_event();
3348 void qemu_system_powerdown_request(void)
3350 powerdown_requested = 1;
3351 qemu_notify_event();
3354 #ifdef CONFIG_IOTHREAD
3355 static void qemu_system_vmstop_request(int reason)
3357 vmstop_requested = reason;
3358 qemu_notify_event();
3360 #endif
3362 #ifndef _WIN32
3363 static int io_thread_fd = -1;
3365 static void qemu_event_increment(void)
3367 static const char byte = 0;
3369 if (io_thread_fd == -1)
3370 return;
3372 write(io_thread_fd, &byte, sizeof(byte));
3375 static void qemu_event_read(void *opaque)
3377 int fd = (unsigned long)opaque;
3378 ssize_t len;
3380 /* Drain the notify pipe */
3381 do {
3382 char buffer[512];
3383 len = read(fd, buffer, sizeof(buffer));
3384 } while ((len == -1 && errno == EINTR) || len > 0);
3387 static int qemu_event_init(void)
3389 int err;
3390 int fds[2];
3392 err = pipe(fds);
3393 if (err == -1)
3394 return -errno;
3396 err = fcntl_setfl(fds[0], O_NONBLOCK);
3397 if (err < 0)
3398 goto fail;
3400 err = fcntl_setfl(fds[1], O_NONBLOCK);
3401 if (err < 0)
3402 goto fail;
3404 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3405 (void *)(unsigned long)fds[0]);
3407 io_thread_fd = fds[1];
3408 return 0;
3410 fail:
3411 close(fds[0]);
3412 close(fds[1]);
3413 return err;
3415 #else
3416 HANDLE qemu_event_handle;
3418 static void dummy_event_handler(void *opaque)
3422 static int qemu_event_init(void)
3424 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3425 if (!qemu_event_handle) {
3426 perror("Failed CreateEvent");
3427 return -1;
3429 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3430 return 0;
3433 static void qemu_event_increment(void)
3435 SetEvent(qemu_event_handle);
3437 #endif
3439 static int cpu_can_run(CPUState *env)
3441 if (env->stop)
3442 return 0;
3443 if (env->stopped)
3444 return 0;
3445 return 1;
3448 #ifndef CONFIG_IOTHREAD
3449 static int qemu_init_main_loop(void)
3451 return qemu_event_init();
3454 void qemu_init_vcpu(void *_env)
3456 CPUState *env = _env;
3458 if (kvm_enabled())
3459 kvm_init_vcpu(env);
3460 env->nr_cores = smp_cores;
3461 env->nr_threads = smp_threads;
3462 return;
3465 int qemu_cpu_self(void *env)
3467 return 1;
3470 static void resume_all_vcpus(void)
3474 static void pause_all_vcpus(void)
3478 void qemu_cpu_kick(void *env)
3480 return;
3483 void qemu_notify_event(void)
3485 CPUState *env = cpu_single_env;
3487 if (kvm_enabled()) {
3488 qemu_kvm_notify_work();
3489 return;
3491 if (env) {
3492 cpu_exit(env);
3496 #ifdef KVM_UPSTREAM
3497 #define qemu_mutex_lock_iothread() do { } while (0)
3498 #define qemu_mutex_unlock_iothread() do { } while (0)
3499 #endif
3501 void vm_stop(int reason)
3503 do_vm_stop(reason);
3506 #else /* CONFIG_IOTHREAD */
3508 #include "qemu-thread.h"
3510 QemuMutex qemu_global_mutex;
3511 static QemuMutex qemu_fair_mutex;
3513 static QemuThread io_thread;
3515 static QemuThread *tcg_cpu_thread;
3516 static QemuCond *tcg_halt_cond;
3518 static int qemu_system_ready;
3519 /* cpu creation */
3520 static QemuCond qemu_cpu_cond;
3521 /* system init */
3522 static QemuCond qemu_system_cond;
3523 static QemuCond qemu_pause_cond;
3525 static void block_io_signals(void);
3526 static void unblock_io_signals(void);
3527 static int tcg_has_work(void);
3529 static int qemu_init_main_loop(void)
3531 int ret;
3533 ret = qemu_event_init();
3534 if (ret)
3535 return ret;
3537 qemu_cond_init(&qemu_pause_cond);
3538 qemu_mutex_init(&qemu_fair_mutex);
3539 qemu_mutex_init(&qemu_global_mutex);
3540 qemu_mutex_lock(&qemu_global_mutex);
3542 unblock_io_signals();
3543 qemu_thread_self(&io_thread);
3545 return 0;
3548 static void qemu_wait_io_event(CPUState *env)
3550 while (!tcg_has_work())
3551 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3553 qemu_mutex_unlock(&qemu_global_mutex);
3556 * Users of qemu_global_mutex can be starved, having no chance
3557 * to acquire it since this path will get to it first.
3558 * So use another lock to provide fairness.
3560 qemu_mutex_lock(&qemu_fair_mutex);
3561 qemu_mutex_unlock(&qemu_fair_mutex);
3563 qemu_mutex_lock(&qemu_global_mutex);
3564 if (env->stop) {
3565 env->stop = 0;
3566 env->stopped = 1;
3567 qemu_cond_signal(&qemu_pause_cond);
3571 static int qemu_cpu_exec(CPUState *env);
3573 static void *kvm_cpu_thread_fn(void *arg)
3575 CPUState *env = arg;
3577 block_io_signals();
3578 qemu_thread_self(env->thread);
3579 if (kvm_enabled())
3580 kvm_init_vcpu(env);
3582 /* signal CPU creation */
3583 qemu_mutex_lock(&qemu_global_mutex);
3584 env->created = 1;
3585 qemu_cond_signal(&qemu_cpu_cond);
3587 /* and wait for machine initialization */
3588 while (!qemu_system_ready)
3589 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3591 while (1) {
3592 if (cpu_can_run(env))
3593 qemu_cpu_exec(env);
3594 qemu_wait_io_event(env);
3597 return NULL;
3600 static void tcg_cpu_exec(void);
3602 static void *tcg_cpu_thread_fn(void *arg)
3604 CPUState *env = arg;
3606 block_io_signals();
3607 qemu_thread_self(env->thread);
3609 /* signal CPU creation */
3610 qemu_mutex_lock(&qemu_global_mutex);
3611 for (env = first_cpu; env != NULL; env = env->next_cpu)
3612 env->created = 1;
3613 qemu_cond_signal(&qemu_cpu_cond);
3615 /* and wait for machine initialization */
3616 while (!qemu_system_ready)
3617 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3619 while (1) {
3620 tcg_cpu_exec();
3621 qemu_wait_io_event(cur_cpu);
3624 return NULL;
3627 void qemu_cpu_kick(void *_env)
3629 CPUState *env = _env;
3630 qemu_cond_broadcast(env->halt_cond);
3631 if (kvm_enabled())
3632 qemu_thread_signal(env->thread, SIGUSR1);
3635 int qemu_cpu_self(void *env)
3637 return (cpu_single_env != NULL);
3640 static void cpu_signal(int sig)
3642 if (cpu_single_env)
3643 cpu_exit(cpu_single_env);
3646 static void block_io_signals(void)
3648 sigset_t set;
3649 struct sigaction sigact;
3651 sigemptyset(&set);
3652 sigaddset(&set, SIGUSR2);
3653 sigaddset(&set, SIGIO);
3654 sigaddset(&set, SIGALRM);
3655 pthread_sigmask(SIG_BLOCK, &set, NULL);
3657 sigemptyset(&set);
3658 sigaddset(&set, SIGUSR1);
3659 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3661 memset(&sigact, 0, sizeof(sigact));
3662 sigact.sa_handler = cpu_signal;
3663 sigaction(SIGUSR1, &sigact, NULL);
3666 static void unblock_io_signals(void)
3668 sigset_t set;
3670 sigemptyset(&set);
3671 sigaddset(&set, SIGUSR2);
3672 sigaddset(&set, SIGIO);
3673 sigaddset(&set, SIGALRM);
3674 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3676 sigemptyset(&set);
3677 sigaddset(&set, SIGUSR1);
3678 pthread_sigmask(SIG_BLOCK, &set, NULL);
3681 static void qemu_signal_lock(unsigned int msecs)
3683 qemu_mutex_lock(&qemu_fair_mutex);
3685 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3686 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3687 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3688 break;
3690 qemu_mutex_unlock(&qemu_fair_mutex);
3693 static void qemu_mutex_lock_iothread(void)
3695 if (kvm_enabled()) {
3696 qemu_mutex_lock(&qemu_fair_mutex);
3697 qemu_mutex_lock(&qemu_global_mutex);
3698 qemu_mutex_unlock(&qemu_fair_mutex);
3699 } else
3700 qemu_signal_lock(100);
3703 static void qemu_mutex_unlock_iothread(void)
3705 qemu_mutex_unlock(&qemu_global_mutex);
3708 static int all_vcpus_paused(void)
3710 CPUState *penv = first_cpu;
3712 while (penv) {
3713 if (!penv->stopped)
3714 return 0;
3715 penv = (CPUState *)penv->next_cpu;
3718 return 1;
3721 static void pause_all_vcpus(void)
3723 CPUState *penv = first_cpu;
3725 while (penv) {
3726 penv->stop = 1;
3727 qemu_thread_signal(penv->thread, SIGUSR1);
3728 qemu_cpu_kick(penv);
3729 penv = (CPUState *)penv->next_cpu;
3732 while (!all_vcpus_paused()) {
3733 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3734 penv = first_cpu;
3735 while (penv) {
3736 qemu_thread_signal(penv->thread, SIGUSR1);
3737 penv = (CPUState *)penv->next_cpu;
3742 static void resume_all_vcpus(void)
3744 CPUState *penv = first_cpu;
3746 while (penv) {
3747 penv->stop = 0;
3748 penv->stopped = 0;
3749 qemu_thread_signal(penv->thread, SIGUSR1);
3750 qemu_cpu_kick(penv);
3751 penv = (CPUState *)penv->next_cpu;
3755 static void tcg_init_vcpu(void *_env)
3757 CPUState *env = _env;
3758 /* share a single thread for all cpus with TCG */
3759 if (!tcg_cpu_thread) {
3760 env->thread = qemu_mallocz(sizeof(QemuThread));
3761 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3762 qemu_cond_init(env->halt_cond);
3763 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3764 while (env->created == 0)
3765 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3766 tcg_cpu_thread = env->thread;
3767 tcg_halt_cond = env->halt_cond;
3768 } else {
3769 env->thread = tcg_cpu_thread;
3770 env->halt_cond = tcg_halt_cond;
3774 static void kvm_start_vcpu(CPUState *env)
3776 env->thread = qemu_mallocz(sizeof(QemuThread));
3777 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3778 qemu_cond_init(env->halt_cond);
3779 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3780 while (env->created == 0)
3781 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3784 void qemu_init_vcpu(void *_env)
3786 CPUState *env = _env;
3788 if (kvm_enabled())
3789 kvm_start_vcpu(env);
3790 else
3791 tcg_init_vcpu(env);
3792 env->nr_cores = smp_cores;
3793 env->nr_threads = smp_threads;
3796 void qemu_notify_event(void)
3798 qemu_event_increment();
3801 void vm_stop(int reason)
3803 QemuThread me;
3804 qemu_thread_self(&me);
3806 if (!qemu_thread_equal(&me, &io_thread)) {
3807 qemu_system_vmstop_request(reason);
3809 * FIXME: should not return to device code in case
3810 * vm_stop() has been requested.
3812 if (cpu_single_env) {
3813 cpu_exit(cpu_single_env);
3814 cpu_single_env->stop = 1;
3816 return;
3818 do_vm_stop(reason);
3821 #endif
3824 #ifdef _WIN32
3825 static void host_main_loop_wait(int *timeout)
3827 int ret, ret2, i;
3828 PollingEntry *pe;
3831 /* XXX: need to suppress polling by better using win32 events */
3832 ret = 0;
3833 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3834 ret |= pe->func(pe->opaque);
3836 if (ret == 0) {
3837 int err;
3838 WaitObjects *w = &wait_objects;
3840 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3841 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3842 if (w->func[ret - WAIT_OBJECT_0])
3843 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3845 /* Check for additional signaled events */
3846 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3848 /* Check if event is signaled */
3849 ret2 = WaitForSingleObject(w->events[i], 0);
3850 if(ret2 == WAIT_OBJECT_0) {
3851 if (w->func[i])
3852 w->func[i](w->opaque[i]);
3853 } else if (ret2 == WAIT_TIMEOUT) {
3854 } else {
3855 err = GetLastError();
3856 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3859 } else if (ret == WAIT_TIMEOUT) {
3860 } else {
3861 err = GetLastError();
3862 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3866 *timeout = 0;
3868 #else
3869 static void host_main_loop_wait(int *timeout)
3872 #endif
3874 void main_loop_wait(int timeout)
3876 IOHandlerRecord *ioh;
3877 fd_set rfds, wfds, xfds;
3878 int ret, nfds;
3879 struct timeval tv;
3881 qemu_bh_update_timeout(&timeout);
3883 host_main_loop_wait(&timeout);
3885 /* poll any events */
3886 /* XXX: separate device handlers from system ones */
3887 nfds = -1;
3888 FD_ZERO(&rfds);
3889 FD_ZERO(&wfds);
3890 FD_ZERO(&xfds);
3891 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3892 if (ioh->deleted)
3893 continue;
3894 if (ioh->fd_read &&
3895 (!ioh->fd_read_poll ||
3896 ioh->fd_read_poll(ioh->opaque) != 0)) {
3897 FD_SET(ioh->fd, &rfds);
3898 if (ioh->fd > nfds)
3899 nfds = ioh->fd;
3901 if (ioh->fd_write) {
3902 FD_SET(ioh->fd, &wfds);
3903 if (ioh->fd > nfds)
3904 nfds = ioh->fd;
3908 tv.tv_sec = timeout / 1000;
3909 tv.tv_usec = (timeout % 1000) * 1000;
3911 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3913 qemu_mutex_unlock_iothread();
3914 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3915 qemu_mutex_lock_iothread();
3916 if (ret > 0) {
3917 IOHandlerRecord **pioh;
3919 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3920 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3921 ioh->fd_read(ioh->opaque);
3922 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3923 FD_CLR(ioh->fd, &rfds);
3925 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3926 ioh->fd_write(ioh->opaque);
3930 /* remove deleted IO handlers */
3931 pioh = &first_io_handler;
3932 while (*pioh) {
3933 ioh = *pioh;
3934 if (ioh->deleted) {
3935 *pioh = ioh->next;
3936 qemu_free(ioh);
3937 } else
3938 pioh = &ioh->next;
3942 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3944 /* rearm timer, if not periodic */
3945 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3946 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3947 qemu_rearm_alarm_timer(alarm_timer);
3950 /* vm time timers */
3951 if (vm_running) {
3952 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3953 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3954 qemu_get_clock(vm_clock));
3957 /* real time timers */
3958 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3959 qemu_get_clock(rt_clock));
3961 /* Check bottom-halves last in case any of the earlier events triggered
3962 them. */
3963 qemu_bh_poll();
3967 static int qemu_cpu_exec(CPUState *env)
3969 int ret;
3970 #ifdef CONFIG_PROFILER
3971 int64_t ti;
3972 #endif
3974 #ifdef CONFIG_PROFILER
3975 ti = profile_getclock();
3976 #endif
3977 if (use_icount) {
3978 int64_t count;
3979 int decr;
3980 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3981 env->icount_decr.u16.low = 0;
3982 env->icount_extra = 0;
3983 count = qemu_next_deadline();
3984 count = (count + (1 << icount_time_shift) - 1)
3985 >> icount_time_shift;
3986 qemu_icount += count;
3987 decr = (count > 0xffff) ? 0xffff : count;
3988 count -= decr;
3989 env->icount_decr.u16.low = decr;
3990 env->icount_extra = count;
3992 ret = cpu_exec(env);
3993 #ifdef CONFIG_PROFILER
3994 qemu_time += profile_getclock() - ti;
3995 #endif
3996 if (use_icount) {
3997 /* Fold pending instructions back into the
3998 instruction counter, and clear the interrupt flag. */
3999 qemu_icount -= (env->icount_decr.u16.low
4000 + env->icount_extra);
4001 env->icount_decr.u32 = 0;
4002 env->icount_extra = 0;
4004 return ret;
4007 static void tcg_cpu_exec(void)
4009 int ret = 0;
4011 if (next_cpu == NULL)
4012 next_cpu = first_cpu;
4013 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4014 CPUState *env = cur_cpu = next_cpu;
4016 if (!vm_running)
4017 break;
4018 if (timer_alarm_pending) {
4019 timer_alarm_pending = 0;
4020 break;
4022 if (cpu_can_run(env))
4023 ret = qemu_cpu_exec(env);
4024 if (ret == EXCP_DEBUG) {
4025 gdb_set_stop_cpu(env);
4026 debug_requested = 1;
4027 break;
4032 static int cpu_has_work(CPUState *env)
4034 if (env->stop)
4035 return 1;
4036 if (env->stopped)
4037 return 0;
4038 if (!env->halted)
4039 return 1;
4040 if (qemu_cpu_has_work(env))
4041 return 1;
4042 return 0;
4045 static int tcg_has_work(void)
4047 CPUState *env;
4049 for (env = first_cpu; env != NULL; env = env->next_cpu)
4050 if (cpu_has_work(env))
4051 return 1;
4052 return 0;
4055 static int qemu_calculate_timeout(void)
4057 #ifndef CONFIG_IOTHREAD
4058 int timeout;
4060 if (!vm_running)
4061 timeout = 5000;
4062 else if (tcg_has_work())
4063 timeout = 0;
4064 else if (!use_icount)
4065 timeout = 5000;
4066 else {
4067 /* XXX: use timeout computed from timers */
4068 int64_t add;
4069 int64_t delta;
4070 /* Advance virtual time to the next event. */
4071 if (use_icount == 1) {
4072 /* When not using an adaptive execution frequency
4073 we tend to get badly out of sync with real time,
4074 so just delay for a reasonable amount of time. */
4075 delta = 0;
4076 } else {
4077 delta = cpu_get_icount() - cpu_get_clock();
4079 if (delta > 0) {
4080 /* If virtual time is ahead of real time then just
4081 wait for IO. */
4082 timeout = (delta / 1000000) + 1;
4083 } else {
4084 /* Wait for either IO to occur or the next
4085 timer event. */
4086 add = qemu_next_deadline();
4087 /* We advance the timer before checking for IO.
4088 Limit the amount we advance so that early IO
4089 activity won't get the guest too far ahead. */
4090 if (add > 10000000)
4091 add = 10000000;
4092 delta += add;
4093 add = (add + (1 << icount_time_shift) - 1)
4094 >> icount_time_shift;
4095 qemu_icount += add;
4096 timeout = delta / 1000000;
4097 if (timeout < 0)
4098 timeout = 0;
4102 return timeout;
4103 #else /* CONFIG_IOTHREAD */
4104 return 1000;
4105 #endif
4108 static int vm_can_run(void)
4110 if (powerdown_requested)
4111 return 0;
4112 if (reset_requested)
4113 return 0;
4114 if (shutdown_requested)
4115 return 0;
4116 if (debug_requested)
4117 return 0;
4118 return 1;
4121 qemu_irq qemu_system_powerdown;
4123 static void main_loop(void)
4125 int r;
4127 if (kvm_enabled()) {
4128 kvm_main_loop();
4129 cpu_disable_ticks();
4130 return;
4133 #ifdef CONFIG_IOTHREAD
4134 qemu_system_ready = 1;
4135 qemu_cond_broadcast(&qemu_system_cond);
4136 #endif
4138 for (;;) {
4139 do {
4140 #ifdef CONFIG_PROFILER
4141 int64_t ti;
4142 #endif
4143 #ifndef CONFIG_IOTHREAD
4144 tcg_cpu_exec();
4145 #endif
4146 #ifdef CONFIG_PROFILER
4147 ti = profile_getclock();
4148 #endif
4149 main_loop_wait(qemu_calculate_timeout());
4150 #ifdef CONFIG_PROFILER
4151 dev_time += profile_getclock() - ti;
4152 #endif
4153 } while (vm_can_run());
4155 if (qemu_debug_requested())
4156 vm_stop(EXCP_DEBUG);
4157 if (qemu_shutdown_requested()) {
4158 if (no_shutdown) {
4159 vm_stop(0);
4160 no_shutdown = 0;
4161 } else
4162 break;
4164 if (qemu_reset_requested()) {
4165 pause_all_vcpus();
4166 qemu_system_reset();
4167 resume_all_vcpus();
4169 if (qemu_powerdown_requested()) {
4170 qemu_irq_raise(qemu_system_powerdown);
4172 if ((r = qemu_vmstop_requested()))
4173 vm_stop(r);
4175 pause_all_vcpus();
4178 static void version(void)
4180 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4183 static void help(int exitcode)
4185 version();
4186 printf("usage: %s [options] [disk_image]\n"
4187 "\n"
4188 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4189 "\n"
4190 #define DEF(option, opt_arg, opt_enum, opt_help) \
4191 opt_help
4192 #define DEFHEADING(text) stringify(text) "\n"
4193 #include "qemu-options.h"
4194 #undef DEF
4195 #undef DEFHEADING
4196 #undef GEN_DOCS
4197 "\n"
4198 "During emulation, the following keys are useful:\n"
4199 "ctrl-alt-f toggle full screen\n"
4200 "ctrl-alt-n switch to virtual console 'n'\n"
4201 "ctrl-alt toggle mouse and keyboard grab\n"
4202 "\n"
4203 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4205 "qemu",
4206 DEFAULT_RAM_SIZE,
4207 #ifndef _WIN32
4208 DEFAULT_NETWORK_SCRIPT,
4209 DEFAULT_NETWORK_DOWN_SCRIPT,
4210 #endif
4211 DEFAULT_GDBSTUB_PORT,
4212 "/tmp/qemu.log");
4213 exit(exitcode);
4216 #define HAS_ARG 0x0001
4218 enum {
4219 #define DEF(option, opt_arg, opt_enum, opt_help) \
4220 opt_enum,
4221 #define DEFHEADING(text)
4222 #include "qemu-options.h"
4223 #undef DEF
4224 #undef DEFHEADING
4225 #undef GEN_DOCS
4228 typedef struct QEMUOption {
4229 const char *name;
4230 int flags;
4231 int index;
4232 } QEMUOption;
4234 static const QEMUOption qemu_options[] = {
4235 { "h", 0, QEMU_OPTION_h },
4236 #define DEF(option, opt_arg, opt_enum, opt_help) \
4237 { option, opt_arg, opt_enum },
4238 #define DEFHEADING(text)
4239 #include "qemu-options.h"
4240 #undef DEF
4241 #undef DEFHEADING
4242 #undef GEN_DOCS
4243 { NULL },
4246 #ifdef HAS_AUDIO
4247 struct soundhw soundhw[] = {
4248 #ifdef HAS_AUDIO_CHOICE
4249 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4251 "pcspk",
4252 "PC speaker",
4255 { .init_isa = pcspk_audio_init }
4257 #endif
4259 #ifdef CONFIG_SB16
4261 "sb16",
4262 "Creative Sound Blaster 16",
4265 { .init_isa = SB16_init }
4267 #endif
4269 #ifdef CONFIG_CS4231A
4271 "cs4231a",
4272 "CS4231A",
4275 { .init_isa = cs4231a_init }
4277 #endif
4279 #ifdef CONFIG_ADLIB
4281 "adlib",
4282 #ifdef HAS_YMF262
4283 "Yamaha YMF262 (OPL3)",
4284 #else
4285 "Yamaha YM3812 (OPL2)",
4286 #endif
4289 { .init_isa = Adlib_init }
4291 #endif
4293 #ifdef CONFIG_GUS
4295 "gus",
4296 "Gravis Ultrasound GF1",
4299 { .init_isa = GUS_init }
4301 #endif
4303 #ifdef CONFIG_AC97
4305 "ac97",
4306 "Intel 82801AA AC97 Audio",
4309 { .init_pci = ac97_init }
4311 #endif
4313 #ifdef CONFIG_ES1370
4315 "es1370",
4316 "ENSONIQ AudioPCI ES1370",
4319 { .init_pci = es1370_init }
4321 #endif
4323 #endif /* HAS_AUDIO_CHOICE */
4325 { NULL, NULL, 0, 0, { NULL } }
4328 static void select_soundhw (const char *optarg)
4330 struct soundhw *c;
4332 if (*optarg == '?') {
4333 show_valid_cards:
4335 printf ("Valid sound card names (comma separated):\n");
4336 for (c = soundhw; c->name; ++c) {
4337 printf ("%-11s %s\n", c->name, c->descr);
4339 printf ("\n-soundhw all will enable all of the above\n");
4340 exit (*optarg != '?');
4342 else {
4343 size_t l;
4344 const char *p;
4345 char *e;
4346 int bad_card = 0;
4348 if (!strcmp (optarg, "all")) {
4349 for (c = soundhw; c->name; ++c) {
4350 c->enabled = 1;
4352 return;
4355 p = optarg;
4356 while (*p) {
4357 e = strchr (p, ',');
4358 l = !e ? strlen (p) : (size_t) (e - p);
4360 for (c = soundhw; c->name; ++c) {
4361 if (!strncmp (c->name, p, l) && !c->name[l]) {
4362 c->enabled = 1;
4363 break;
4367 if (!c->name) {
4368 if (l > 80) {
4369 fprintf (stderr,
4370 "Unknown sound card name (too big to show)\n");
4372 else {
4373 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4374 (int) l, p);
4376 bad_card = 1;
4378 p += l + (e != NULL);
4381 if (bad_card)
4382 goto show_valid_cards;
4385 #endif
4387 static void select_vgahw (const char *p)
4389 const char *opts;
4391 vga_interface_type = VGA_NONE;
4392 if (strstart(p, "std", &opts)) {
4393 vga_interface_type = VGA_STD;
4394 } else if (strstart(p, "cirrus", &opts)) {
4395 vga_interface_type = VGA_CIRRUS;
4396 } else if (strstart(p, "vmware", &opts)) {
4397 vga_interface_type = VGA_VMWARE;
4398 } else if (strstart(p, "xenfb", &opts)) {
4399 vga_interface_type = VGA_XENFB;
4400 } else if (!strstart(p, "none", &opts)) {
4401 invalid_vga:
4402 fprintf(stderr, "Unknown vga type: %s\n", p);
4403 exit(1);
4405 while (*opts) {
4406 const char *nextopt;
4408 if (strstart(opts, ",retrace=", &nextopt)) {
4409 opts = nextopt;
4410 if (strstart(opts, "dumb", &nextopt))
4411 vga_retrace_method = VGA_RETRACE_DUMB;
4412 else if (strstart(opts, "precise", &nextopt))
4413 vga_retrace_method = VGA_RETRACE_PRECISE;
4414 else goto invalid_vga;
4415 } else goto invalid_vga;
4416 opts = nextopt;
4420 #ifdef TARGET_I386
4421 static int balloon_parse(const char *arg)
4423 QemuOpts *opts;
4425 if (strcmp(arg, "none") == 0) {
4426 return 0;
4429 if (!strncmp(arg, "virtio", 6)) {
4430 if (arg[6] == ',') {
4431 /* have params -> parse them */
4432 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4433 if (!opts)
4434 return -1;
4435 } else {
4436 /* create empty opts */
4437 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4439 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4440 return 0;
4443 return -1;
4445 #endif
4447 #ifdef _WIN32
4448 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4450 exit(STATUS_CONTROL_C_EXIT);
4451 return TRUE;
4453 #endif
4455 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4457 int ret;
4459 if(strlen(str) != 36)
4460 return -1;
4462 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4463 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4464 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4466 if(ret != 16)
4467 return -1;
4469 #ifdef TARGET_I386
4470 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4471 #endif
4473 return 0;
4476 #define MAX_NET_CLIENTS 32
4478 #ifndef _WIN32
4480 static void termsig_handler(int signal)
4482 qemu_system_shutdown_request();
4485 static void sigchld_handler(int signal)
4487 waitpid(-1, NULL, WNOHANG);
4490 static void sighandler_setup(void)
4492 struct sigaction act;
4494 memset(&act, 0, sizeof(act));
4495 act.sa_handler = termsig_handler;
4496 sigaction(SIGINT, &act, NULL);
4497 sigaction(SIGHUP, &act, NULL);
4498 sigaction(SIGTERM, &act, NULL);
4500 act.sa_handler = sigchld_handler;
4501 act.sa_flags = SA_NOCLDSTOP;
4502 sigaction(SIGCHLD, &act, NULL);
4505 #endif
4507 #ifdef _WIN32
4508 /* Look for support files in the same directory as the executable. */
4509 static char *find_datadir(const char *argv0)
4511 char *p;
4512 char buf[MAX_PATH];
4513 DWORD len;
4515 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4516 if (len == 0) {
4517 return NULL;
4520 buf[len] = 0;
4521 p = buf + len - 1;
4522 while (p != buf && *p != '\\')
4523 p--;
4524 *p = 0;
4525 if (access(buf, R_OK) == 0) {
4526 return qemu_strdup(buf);
4528 return NULL;
4530 #else /* !_WIN32 */
4532 /* Find a likely location for support files using the location of the binary.
4533 For installed binaries this will be "$bindir/../share/qemu". When
4534 running from the build tree this will be "$bindir/../pc-bios". */
4535 #define SHARE_SUFFIX "/share/qemu"
4536 #define BUILD_SUFFIX "/pc-bios"
4537 static char *find_datadir(const char *argv0)
4539 char *dir;
4540 char *p = NULL;
4541 char *res;
4542 char buf[PATH_MAX];
4543 size_t max_len;
4545 #if defined(__linux__)
4547 int len;
4548 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4549 if (len > 0) {
4550 buf[len] = 0;
4551 p = buf;
4554 #elif defined(__FreeBSD__)
4556 int len;
4557 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4558 if (len > 0) {
4559 buf[len] = 0;
4560 p = buf;
4563 #endif
4564 /* If we don't have any way of figuring out the actual executable
4565 location then try argv[0]. */
4566 if (!p) {
4567 p = realpath(argv0, buf);
4568 if (!p) {
4569 return NULL;
4572 dir = dirname(p);
4573 dir = dirname(dir);
4575 max_len = strlen(dir) +
4576 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4577 res = qemu_mallocz(max_len);
4578 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4579 if (access(res, R_OK)) {
4580 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4581 if (access(res, R_OK)) {
4582 qemu_free(res);
4583 res = NULL;
4587 return res;
4589 #undef SHARE_SUFFIX
4590 #undef BUILD_SUFFIX
4591 #endif
4593 char *qemu_find_file(int type, const char *name)
4595 int len;
4596 const char *subdir;
4597 char *buf;
4599 /* If name contains path separators then try it as a straight path. */
4600 if ((strchr(name, '/') || strchr(name, '\\'))
4601 && access(name, R_OK) == 0) {
4602 return qemu_strdup(name);
4604 switch (type) {
4605 case QEMU_FILE_TYPE_BIOS:
4606 subdir = "";
4607 break;
4608 case QEMU_FILE_TYPE_KEYMAP:
4609 subdir = "keymaps/";
4610 break;
4611 default:
4612 abort();
4614 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4615 buf = qemu_mallocz(len);
4616 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4617 if (access(buf, R_OK)) {
4618 qemu_free(buf);
4619 return NULL;
4621 return buf;
4624 static int device_init_func(QemuOpts *opts, void *opaque)
4626 DeviceState *dev;
4628 dev = qdev_device_add(opts);
4629 if (!dev)
4630 return -1;
4631 return 0;
4634 struct device_config {
4635 enum {
4636 DEV_USB, /* -usbdevice */
4637 DEV_BT, /* -bt */
4638 } type;
4639 const char *cmdline;
4640 QTAILQ_ENTRY(device_config) next;
4642 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4644 static void add_device_config(int type, const char *cmdline)
4646 struct device_config *conf;
4648 conf = qemu_mallocz(sizeof(*conf));
4649 conf->type = type;
4650 conf->cmdline = cmdline;
4651 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4654 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4656 struct device_config *conf;
4657 int rc;
4659 QTAILQ_FOREACH(conf, &device_configs, next) {
4660 if (conf->type != type)
4661 continue;
4662 rc = func(conf->cmdline);
4663 if (0 != rc)
4664 return rc;
4666 return 0;
4669 int main(int argc, char **argv, char **envp)
4671 const char *gdbstub_dev = NULL;
4672 uint32_t boot_devices_bitmap = 0;
4673 int i;
4674 int snapshot, linux_boot, net_boot;
4675 const char *initrd_filename;
4676 const char *kernel_filename, *kernel_cmdline;
4677 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4678 DisplayState *ds;
4679 DisplayChangeListener *dcl;
4680 int cyls, heads, secs, translation;
4681 const char *net_clients[MAX_NET_CLIENTS];
4682 int nb_net_clients;
4683 QemuOpts *hda_opts = NULL, *opts;
4684 int optind;
4685 const char *r, *optarg;
4686 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4687 const char *monitor_devices[MAX_MONITOR_DEVICES];
4688 int monitor_device_index;
4689 const char *serial_devices[MAX_SERIAL_PORTS];
4690 int serial_device_index;
4691 const char *parallel_devices[MAX_PARALLEL_PORTS];
4692 int parallel_device_index;
4693 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4694 int virtio_console_index;
4695 const char *loadvm = NULL;
4696 QEMUMachine *machine;
4697 const char *cpu_model;
4698 #ifndef _WIN32
4699 int fds[2];
4700 #endif
4701 int tb_size;
4702 const char *pid_file = NULL;
4703 const char *incoming = NULL;
4704 #ifndef _WIN32
4705 int fd = 0;
4706 struct passwd *pwd = NULL;
4707 const char *chroot_dir = NULL;
4708 const char *run_as = NULL;
4709 #endif
4710 CPUState *env;
4711 int show_vnc_port = 0;
4713 qemu_errors_to_file(stderr);
4714 qemu_cache_utils_init(envp);
4716 QLIST_INIT (&vm_change_state_head);
4717 #ifndef _WIN32
4719 struct sigaction act;
4720 sigfillset(&act.sa_mask);
4721 act.sa_flags = 0;
4722 act.sa_handler = SIG_IGN;
4723 sigaction(SIGPIPE, &act, NULL);
4725 #else
4726 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4727 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4728 QEMU to run on a single CPU */
4730 HANDLE h;
4731 DWORD mask, smask;
4732 int i;
4733 h = GetCurrentProcess();
4734 if (GetProcessAffinityMask(h, &mask, &smask)) {
4735 for(i = 0; i < 32; i++) {
4736 if (mask & (1 << i))
4737 break;
4739 if (i != 32) {
4740 mask = 1 << i;
4741 SetProcessAffinityMask(h, mask);
4745 #endif
4747 module_call_init(MODULE_INIT_MACHINE);
4748 machine = find_default_machine();
4749 cpu_model = NULL;
4750 initrd_filename = NULL;
4751 ram_size = 0;
4752 snapshot = 0;
4753 kernel_filename = NULL;
4754 kernel_cmdline = "";
4755 cyls = heads = secs = 0;
4756 translation = BIOS_ATA_TRANSLATION_AUTO;
4758 serial_devices[0] = "vc:80Cx24C";
4759 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4760 serial_devices[i] = NULL;
4761 serial_device_index = 0;
4763 parallel_devices[0] = "vc:80Cx24C";
4764 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4765 parallel_devices[i] = NULL;
4766 parallel_device_index = 0;
4768 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4769 virtio_consoles[i] = NULL;
4770 virtio_console_index = 0;
4772 monitor_devices[0] = "vc:80Cx24C";
4773 for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4774 monitor_devices[i] = NULL;
4776 monitor_device_index = 0;
4778 for (i = 0; i < MAX_NODES; i++) {
4779 node_mem[i] = 0;
4780 node_cpumask[i] = 0;
4783 assigned_devices_index = 0;
4785 nb_net_clients = 0;
4786 nb_numa_nodes = 0;
4787 nb_nics = 0;
4789 tb_size = 0;
4790 autostart= 1;
4792 optind = 1;
4793 for(;;) {
4794 if (optind >= argc)
4795 break;
4796 r = argv[optind];
4797 if (r[0] != '-') {
4798 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4799 } else {
4800 const QEMUOption *popt;
4802 optind++;
4803 /* Treat --foo the same as -foo. */
4804 if (r[1] == '-')
4805 r++;
4806 popt = qemu_options;
4807 for(;;) {
4808 if (!popt->name) {
4809 fprintf(stderr, "%s: invalid option -- '%s'\n",
4810 argv[0], r);
4811 exit(1);
4813 if (!strcmp(popt->name, r + 1))
4814 break;
4815 popt++;
4817 if (popt->flags & HAS_ARG) {
4818 if (optind >= argc) {
4819 fprintf(stderr, "%s: option '%s' requires an argument\n",
4820 argv[0], r);
4821 exit(1);
4823 optarg = argv[optind++];
4824 } else {
4825 optarg = NULL;
4828 switch(popt->index) {
4829 case QEMU_OPTION_M:
4830 machine = find_machine(optarg);
4831 if (!machine) {
4832 QEMUMachine *m;
4833 printf("Supported machines are:\n");
4834 for(m = first_machine; m != NULL; m = m->next) {
4835 if (m->alias)
4836 printf("%-10s %s (alias of %s)\n",
4837 m->alias, m->desc, m->name);
4838 printf("%-10s %s%s\n",
4839 m->name, m->desc,
4840 m->is_default ? " (default)" : "");
4842 exit(*optarg != '?');
4844 break;
4845 case QEMU_OPTION_cpu:
4846 /* hw initialization will check this */
4847 if (*optarg == '?') {
4848 /* XXX: implement xxx_cpu_list for targets that still miss it */
4849 #if defined(cpu_list)
4850 cpu_list(stdout, &fprintf);
4851 #endif
4852 exit(0);
4853 } else {
4854 cpu_model = optarg;
4856 break;
4857 case QEMU_OPTION_initrd:
4858 initrd_filename = optarg;
4859 break;
4860 case QEMU_OPTION_hda:
4861 if (cyls == 0)
4862 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4863 else
4864 hda_opts = drive_add(optarg, HD_ALIAS
4865 ",cyls=%d,heads=%d,secs=%d%s",
4866 0, cyls, heads, secs,
4867 translation == BIOS_ATA_TRANSLATION_LBA ?
4868 ",trans=lba" :
4869 translation == BIOS_ATA_TRANSLATION_NONE ?
4870 ",trans=none" : "");
4871 break;
4872 case QEMU_OPTION_hdb:
4873 case QEMU_OPTION_hdc:
4874 case QEMU_OPTION_hdd:
4875 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4876 break;
4877 case QEMU_OPTION_drive:
4878 drive_add(NULL, "%s", optarg);
4879 break;
4880 case QEMU_OPTION_set:
4881 if (qemu_set_option(optarg) != 0)
4882 exit(1);
4883 break;
4884 case QEMU_OPTION_mtdblock:
4885 drive_add(optarg, MTD_ALIAS);
4886 break;
4887 case QEMU_OPTION_sd:
4888 drive_add(optarg, SD_ALIAS);
4889 break;
4890 case QEMU_OPTION_pflash:
4891 drive_add(optarg, PFLASH_ALIAS);
4892 break;
4893 case QEMU_OPTION_snapshot:
4894 snapshot = 1;
4895 break;
4896 case QEMU_OPTION_hdachs:
4898 const char *p;
4899 p = optarg;
4900 cyls = strtol(p, (char **)&p, 0);
4901 if (cyls < 1 || cyls > 16383)
4902 goto chs_fail;
4903 if (*p != ',')
4904 goto chs_fail;
4905 p++;
4906 heads = strtol(p, (char **)&p, 0);
4907 if (heads < 1 || heads > 16)
4908 goto chs_fail;
4909 if (*p != ',')
4910 goto chs_fail;
4911 p++;
4912 secs = strtol(p, (char **)&p, 0);
4913 if (secs < 1 || secs > 63)
4914 goto chs_fail;
4915 if (*p == ',') {
4916 p++;
4917 if (!strcmp(p, "none"))
4918 translation = BIOS_ATA_TRANSLATION_NONE;
4919 else if (!strcmp(p, "lba"))
4920 translation = BIOS_ATA_TRANSLATION_LBA;
4921 else if (!strcmp(p, "auto"))
4922 translation = BIOS_ATA_TRANSLATION_AUTO;
4923 else
4924 goto chs_fail;
4925 } else if (*p != '\0') {
4926 chs_fail:
4927 fprintf(stderr, "qemu: invalid physical CHS format\n");
4928 exit(1);
4930 if (hda_opts != NULL) {
4931 char num[16];
4932 snprintf(num, sizeof(num), "%d", cyls);
4933 qemu_opt_set(hda_opts, "cyls", num);
4934 snprintf(num, sizeof(num), "%d", heads);
4935 qemu_opt_set(hda_opts, "heads", num);
4936 snprintf(num, sizeof(num), "%d", secs);
4937 qemu_opt_set(hda_opts, "secs", num);
4938 if (translation == BIOS_ATA_TRANSLATION_LBA)
4939 qemu_opt_set(hda_opts, "trans", "lba");
4940 if (translation == BIOS_ATA_TRANSLATION_NONE)
4941 qemu_opt_set(hda_opts, "trans", "none");
4944 break;
4945 case QEMU_OPTION_numa:
4946 if (nb_numa_nodes >= MAX_NODES) {
4947 fprintf(stderr, "qemu: too many NUMA nodes\n");
4948 exit(1);
4950 numa_add(optarg);
4951 break;
4952 case QEMU_OPTION_nographic:
4953 display_type = DT_NOGRAPHIC;
4954 break;
4955 #ifdef CONFIG_CURSES
4956 case QEMU_OPTION_curses:
4957 display_type = DT_CURSES;
4958 break;
4959 #endif
4960 case QEMU_OPTION_portrait:
4961 graphic_rotate = 1;
4962 break;
4963 case QEMU_OPTION_kernel:
4964 kernel_filename = optarg;
4965 break;
4966 case QEMU_OPTION_append:
4967 kernel_cmdline = optarg;
4968 break;
4969 case QEMU_OPTION_cdrom:
4970 drive_add(optarg, CDROM_ALIAS);
4971 break;
4972 case QEMU_OPTION_boot:
4974 static const char * const params[] = {
4975 "order", "once", "menu", NULL
4977 char buf[sizeof(boot_devices)];
4978 char *standard_boot_devices;
4979 int legacy = 0;
4981 if (!strchr(optarg, '=')) {
4982 legacy = 1;
4983 pstrcpy(buf, sizeof(buf), optarg);
4984 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4985 fprintf(stderr,
4986 "qemu: unknown boot parameter '%s' in '%s'\n",
4987 buf, optarg);
4988 exit(1);
4991 if (legacy ||
4992 get_param_value(buf, sizeof(buf), "order", optarg)) {
4993 boot_devices_bitmap = parse_bootdevices(buf);
4994 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4996 if (!legacy) {
4997 if (get_param_value(buf, sizeof(buf),
4998 "once", optarg)) {
4999 boot_devices_bitmap |= parse_bootdevices(buf);
5000 standard_boot_devices = qemu_strdup(boot_devices);
5001 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5002 qemu_register_reset(restore_boot_devices,
5003 standard_boot_devices);
5005 if (get_param_value(buf, sizeof(buf),
5006 "menu", optarg)) {
5007 if (!strcmp(buf, "on")) {
5008 boot_menu = 1;
5009 } else if (!strcmp(buf, "off")) {
5010 boot_menu = 0;
5011 } else {
5012 fprintf(stderr,
5013 "qemu: invalid option value '%s'\n",
5014 buf);
5015 exit(1);
5020 break;
5021 case QEMU_OPTION_fda:
5022 case QEMU_OPTION_fdb:
5023 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5024 break;
5025 #ifdef TARGET_I386
5026 case QEMU_OPTION_no_fd_bootchk:
5027 fd_bootchk = 0;
5028 break;
5029 #endif
5030 case QEMU_OPTION_net:
5031 if (nb_net_clients >= MAX_NET_CLIENTS) {
5032 fprintf(stderr, "qemu: too many network clients\n");
5033 exit(1);
5035 net_clients[nb_net_clients] = optarg;
5036 nb_net_clients++;
5037 break;
5038 #ifdef CONFIG_SLIRP
5039 case QEMU_OPTION_tftp:
5040 legacy_tftp_prefix = optarg;
5041 break;
5042 case QEMU_OPTION_bootp:
5043 legacy_bootp_filename = optarg;
5044 break;
5045 #ifndef _WIN32
5046 case QEMU_OPTION_smb:
5047 net_slirp_smb(optarg);
5048 break;
5049 #endif
5050 case QEMU_OPTION_redir:
5051 net_slirp_redir(optarg);
5052 break;
5053 #endif
5054 case QEMU_OPTION_bt:
5055 add_device_config(DEV_BT, optarg);
5056 break;
5057 #ifdef HAS_AUDIO
5058 case QEMU_OPTION_audio_help:
5059 AUD_help ();
5060 exit (0);
5061 break;
5062 case QEMU_OPTION_soundhw:
5063 select_soundhw (optarg);
5064 break;
5065 #endif
5066 case QEMU_OPTION_h:
5067 help(0);
5068 break;
5069 case QEMU_OPTION_version:
5070 version();
5071 exit(0);
5072 break;
5073 case QEMU_OPTION_m: {
5074 uint64_t value;
5075 char *ptr;
5077 value = strtoul(optarg, &ptr, 10);
5078 switch (*ptr) {
5079 case 0: case 'M': case 'm':
5080 value <<= 20;
5081 break;
5082 case 'G': case 'g':
5083 value <<= 30;
5084 break;
5085 default:
5086 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5087 exit(1);
5090 /* On 32-bit hosts, QEMU is limited by virtual address space */
5091 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5092 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5093 exit(1);
5095 if (value != (uint64_t)(ram_addr_t)value) {
5096 fprintf(stderr, "qemu: ram size too large\n");
5097 exit(1);
5099 ram_size = value;
5100 break;
5102 case QEMU_OPTION_d:
5104 int mask;
5105 const CPULogItem *item;
5107 mask = cpu_str_to_log_mask(optarg);
5108 if (!mask) {
5109 printf("Log items (comma separated):\n");
5110 for(item = cpu_log_items; item->mask != 0; item++) {
5111 printf("%-10s %s\n", item->name, item->help);
5113 exit(1);
5115 cpu_set_log(mask);
5117 break;
5118 case QEMU_OPTION_s:
5119 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5120 break;
5121 case QEMU_OPTION_gdb:
5122 gdbstub_dev = optarg;
5123 break;
5124 case QEMU_OPTION_L:
5125 data_dir = optarg;
5126 break;
5127 case QEMU_OPTION_bios:
5128 bios_name = optarg;
5129 break;
5130 case QEMU_OPTION_singlestep:
5131 singlestep = 1;
5132 break;
5133 case QEMU_OPTION_S:
5134 autostart = 0;
5135 break;
5136 #ifndef _WIN32
5137 case QEMU_OPTION_k:
5138 keyboard_layout = optarg;
5139 break;
5140 #endif
5141 case QEMU_OPTION_localtime:
5142 rtc_utc = 0;
5143 break;
5144 case QEMU_OPTION_vga:
5145 select_vgahw (optarg);
5146 break;
5147 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5148 case QEMU_OPTION_g:
5150 const char *p;
5151 int w, h, depth;
5152 p = optarg;
5153 w = strtol(p, (char **)&p, 10);
5154 if (w <= 0) {
5155 graphic_error:
5156 fprintf(stderr, "qemu: invalid resolution or depth\n");
5157 exit(1);
5159 if (*p != 'x')
5160 goto graphic_error;
5161 p++;
5162 h = strtol(p, (char **)&p, 10);
5163 if (h <= 0)
5164 goto graphic_error;
5165 if (*p == 'x') {
5166 p++;
5167 depth = strtol(p, (char **)&p, 10);
5168 if (depth != 8 && depth != 15 && depth != 16 &&
5169 depth != 24 && depth != 32)
5170 goto graphic_error;
5171 } else if (*p == '\0') {
5172 depth = graphic_depth;
5173 } else {
5174 goto graphic_error;
5177 graphic_width = w;
5178 graphic_height = h;
5179 graphic_depth = depth;
5181 break;
5182 #endif
5183 case QEMU_OPTION_echr:
5185 char *r;
5186 term_escape_char = strtol(optarg, &r, 0);
5187 if (r == optarg)
5188 printf("Bad argument to echr\n");
5189 break;
5191 case QEMU_OPTION_monitor:
5192 if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5193 fprintf(stderr, "qemu: too many monitor devices\n");
5194 exit(1);
5196 monitor_devices[monitor_device_index] = optarg;
5197 monitor_device_index++;
5198 break;
5199 case QEMU_OPTION_chardev:
5200 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5201 if (!opts) {
5202 fprintf(stderr, "parse error: %s\n", optarg);
5203 exit(1);
5205 if (NULL == qemu_chr_open_opts(opts, NULL)) {
5206 exit(1);
5208 break;
5209 case QEMU_OPTION_serial:
5210 if (serial_device_index >= MAX_SERIAL_PORTS) {
5211 fprintf(stderr, "qemu: too many serial ports\n");
5212 exit(1);
5214 serial_devices[serial_device_index] = optarg;
5215 serial_device_index++;
5216 break;
5217 case QEMU_OPTION_watchdog:
5218 if (watchdog) {
5219 fprintf(stderr,
5220 "qemu: only one watchdog option may be given\n");
5221 return 1;
5223 watchdog = optarg;
5224 break;
5225 case QEMU_OPTION_watchdog_action:
5226 if (select_watchdog_action(optarg) == -1) {
5227 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5228 exit(1);
5230 break;
5231 case QEMU_OPTION_virtiocon:
5232 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5233 fprintf(stderr, "qemu: too many virtio consoles\n");
5234 exit(1);
5236 virtio_consoles[virtio_console_index] = optarg;
5237 virtio_console_index++;
5238 break;
5239 case QEMU_OPTION_parallel:
5240 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5241 fprintf(stderr, "qemu: too many parallel ports\n");
5242 exit(1);
5244 parallel_devices[parallel_device_index] = optarg;
5245 parallel_device_index++;
5246 break;
5247 case QEMU_OPTION_loadvm:
5248 loadvm = optarg;
5249 break;
5250 case QEMU_OPTION_full_screen:
5251 full_screen = 1;
5252 break;
5253 #ifdef CONFIG_SDL
5254 case QEMU_OPTION_no_frame:
5255 no_frame = 1;
5256 break;
5257 case QEMU_OPTION_alt_grab:
5258 alt_grab = 1;
5259 break;
5260 case QEMU_OPTION_no_quit:
5261 no_quit = 1;
5262 break;
5263 case QEMU_OPTION_sdl:
5264 display_type = DT_SDL;
5265 break;
5266 #endif
5267 case QEMU_OPTION_pidfile:
5268 pid_file = optarg;
5269 break;
5270 #ifdef TARGET_I386
5271 case QEMU_OPTION_win2k_hack:
5272 win2k_install_hack = 1;
5273 break;
5274 case QEMU_OPTION_rtc_td_hack:
5275 rtc_td_hack = 1;
5276 break;
5277 case QEMU_OPTION_acpitable:
5278 if(acpi_table_add(optarg) < 0) {
5279 fprintf(stderr, "Wrong acpi table provided\n");
5280 exit(1);
5282 break;
5283 case QEMU_OPTION_smbios:
5284 if(smbios_entry_add(optarg) < 0) {
5285 fprintf(stderr, "Wrong smbios provided\n");
5286 exit(1);
5288 break;
5289 #endif
5290 #ifdef CONFIG_KVM
5291 #ifdef KVM_UPSTREAM
5292 case QEMU_OPTION_enable_kvm:
5293 kvm_allowed = 1;
5294 #endif
5295 break;
5296 case QEMU_OPTION_no_kvm:
5297 kvm_allowed = 0;
5298 break;
5299 case QEMU_OPTION_no_kvm_irqchip: {
5300 kvm_irqchip = 0;
5301 kvm_pit = 0;
5302 break;
5304 case QEMU_OPTION_no_kvm_pit: {
5305 kvm_pit = 0;
5306 break;
5308 case QEMU_OPTION_no_kvm_pit_reinjection: {
5309 kvm_pit_reinject = 0;
5310 break;
5312 case QEMU_OPTION_enable_nesting: {
5313 kvm_nested = 1;
5314 break;
5316 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5317 case QEMU_OPTION_pcidevice:
5318 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5319 fprintf(stderr, "Too many assigned devices\n");
5320 exit(1);
5322 assigned_devices[assigned_devices_index] = optarg;
5323 assigned_devices_index++;
5324 break;
5325 #endif
5326 #endif
5327 case QEMU_OPTION_usb:
5328 usb_enabled = 1;
5329 break;
5330 case QEMU_OPTION_usbdevice:
5331 usb_enabled = 1;
5332 add_device_config(DEV_USB, optarg);
5333 break;
5334 case QEMU_OPTION_device:
5335 opts = qemu_opts_parse(&qemu_device_opts, optarg, "driver");
5336 if (!opts) {
5337 fprintf(stderr, "parse error: %s\n", optarg);
5338 exit(1);
5340 break;
5341 case QEMU_OPTION_smp:
5342 smp_parse(optarg);
5343 if (smp_cpus < 1) {
5344 fprintf(stderr, "Invalid number of CPUs\n");
5345 exit(1);
5347 if (max_cpus < smp_cpus) {
5348 fprintf(stderr, "maxcpus must be equal to or greater than "
5349 "smp\n");
5350 exit(1);
5352 if (max_cpus > 255) {
5353 fprintf(stderr, "Unsupported number of maxcpus\n");
5354 exit(1);
5356 break;
5357 case QEMU_OPTION_vnc:
5358 display_type = DT_VNC;
5359 vnc_display = optarg;
5360 break;
5361 #ifdef TARGET_I386
5362 case QEMU_OPTION_no_acpi:
5363 acpi_enabled = 0;
5364 break;
5365 case QEMU_OPTION_no_hpet:
5366 no_hpet = 1;
5367 break;
5368 case QEMU_OPTION_balloon:
5369 if (balloon_parse(optarg) < 0) {
5370 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5371 exit(1);
5373 break;
5374 #endif
5375 case QEMU_OPTION_no_reboot:
5376 no_reboot = 1;
5377 break;
5378 case QEMU_OPTION_no_shutdown:
5379 no_shutdown = 1;
5380 break;
5381 case QEMU_OPTION_show_cursor:
5382 cursor_hide = 0;
5383 break;
5384 case QEMU_OPTION_uuid:
5385 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5386 fprintf(stderr, "Fail to parse UUID string."
5387 " Wrong format.\n");
5388 exit(1);
5390 break;
5391 #ifndef _WIN32
5392 case QEMU_OPTION_daemonize:
5393 daemonize = 1;
5394 break;
5395 #endif
5396 case QEMU_OPTION_option_rom:
5397 if (nb_option_roms >= MAX_OPTION_ROMS) {
5398 fprintf(stderr, "Too many option ROMs\n");
5399 exit(1);
5401 option_rom[nb_option_roms] = optarg;
5402 nb_option_roms++;
5403 break;
5404 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5405 case QEMU_OPTION_semihosting:
5406 semihosting_enabled = 1;
5407 break;
5408 #endif
5409 case QEMU_OPTION_tdf:
5410 time_drift_fix = 1;
5411 break;
5412 case QEMU_OPTION_kvm_shadow_memory:
5413 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5414 break;
5415 case QEMU_OPTION_mempath:
5416 mem_path = optarg;
5417 break;
5418 #ifdef MAP_POPULATE
5419 case QEMU_OPTION_mem_prealloc:
5420 mem_prealloc = !mem_prealloc;
5421 break;
5422 #endif
5423 case QEMU_OPTION_name:
5424 qemu_name = qemu_strdup(optarg);
5426 char *p = strchr(qemu_name, ',');
5427 if (p != NULL) {
5428 *p++ = 0;
5429 if (strncmp(p, "process=", 8)) {
5430 fprintf(stderr, "Unknown subargument %s to -name", p);
5431 exit(1);
5433 p += 8;
5434 set_proc_name(p);
5437 break;
5438 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5439 case QEMU_OPTION_prom_env:
5440 if (nb_prom_envs >= MAX_PROM_ENVS) {
5441 fprintf(stderr, "Too many prom variables\n");
5442 exit(1);
5444 prom_envs[nb_prom_envs] = optarg;
5445 nb_prom_envs++;
5446 break;
5447 #endif
5448 #ifdef TARGET_ARM
5449 case QEMU_OPTION_old_param:
5450 old_param = 1;
5451 break;
5452 #endif
5453 case QEMU_OPTION_clock:
5454 configure_alarms(optarg);
5455 break;
5456 case QEMU_OPTION_startdate:
5458 struct tm tm;
5459 time_t rtc_start_date;
5460 if (!strcmp(optarg, "now")) {
5461 rtc_date_offset = -1;
5462 } else {
5463 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5464 &tm.tm_year,
5465 &tm.tm_mon,
5466 &tm.tm_mday,
5467 &tm.tm_hour,
5468 &tm.tm_min,
5469 &tm.tm_sec) == 6) {
5470 /* OK */
5471 } else if (sscanf(optarg, "%d-%d-%d",
5472 &tm.tm_year,
5473 &tm.tm_mon,
5474 &tm.tm_mday) == 3) {
5475 tm.tm_hour = 0;
5476 tm.tm_min = 0;
5477 tm.tm_sec = 0;
5478 } else {
5479 goto date_fail;
5481 tm.tm_year -= 1900;
5482 tm.tm_mon--;
5483 rtc_start_date = mktimegm(&tm);
5484 if (rtc_start_date == -1) {
5485 date_fail:
5486 fprintf(stderr, "Invalid date format. Valid format are:\n"
5487 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5488 exit(1);
5490 rtc_date_offset = time(NULL) - rtc_start_date;
5493 break;
5494 case QEMU_OPTION_tb_size:
5495 tb_size = strtol(optarg, NULL, 0);
5496 if (tb_size < 0)
5497 tb_size = 0;
5498 break;
5499 case QEMU_OPTION_icount:
5500 use_icount = 1;
5501 if (strcmp(optarg, "auto") == 0) {
5502 icount_time_shift = -1;
5503 } else {
5504 icount_time_shift = strtol(optarg, NULL, 0);
5506 break;
5507 case QEMU_OPTION_incoming:
5508 incoming = optarg;
5509 break;
5510 #ifndef _WIN32
5511 case QEMU_OPTION_chroot:
5512 chroot_dir = optarg;
5513 break;
5514 case QEMU_OPTION_runas:
5515 run_as = optarg;
5516 break;
5517 case QEMU_OPTION_nvram:
5518 nvram = optarg;
5519 break;
5520 #endif
5521 #ifdef CONFIG_XEN
5522 case QEMU_OPTION_xen_domid:
5523 xen_domid = atoi(optarg);
5524 break;
5525 case QEMU_OPTION_xen_create:
5526 xen_mode = XEN_CREATE;
5527 break;
5528 case QEMU_OPTION_xen_attach:
5529 xen_mode = XEN_ATTACH;
5530 break;
5531 #endif
5536 if (kvm_enabled()) {
5537 int ret;
5539 ret = kvm_init(smp_cpus);
5540 if (ret < 0) {
5541 #if defined(KVM_UPSTREAM) || defined(NO_CPU_EMULATION)
5542 fprintf(stderr, "failed to initialize KVM\n");
5543 exit(1);
5544 #endif
5545 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5546 kvm_allowed = 0;
5550 /* If no data_dir is specified then try to find it relative to the
5551 executable path. */
5552 if (!data_dir) {
5553 data_dir = find_datadir(argv[0]);
5555 /* If all else fails use the install patch specified when building. */
5556 if (!data_dir) {
5557 data_dir = CONFIG_QEMU_SHAREDIR;
5561 * Default to max_cpus = smp_cpus, in case the user doesn't
5562 * specify a max_cpus value.
5564 if (!max_cpus)
5565 max_cpus = smp_cpus;
5567 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5568 if (smp_cpus > machine->max_cpus) {
5569 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5570 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5571 machine->max_cpus);
5572 exit(1);
5575 if (display_type == DT_NOGRAPHIC) {
5576 if (serial_device_index == 0)
5577 serial_devices[0] = "stdio";
5578 if (parallel_device_index == 0)
5579 parallel_devices[0] = "null";
5580 if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5581 monitor_devices[0] = "stdio";
5585 #ifndef _WIN32
5586 if (daemonize) {
5587 pid_t pid;
5589 if (pipe(fds) == -1)
5590 exit(1);
5592 pid = fork();
5593 if (pid > 0) {
5594 uint8_t status;
5595 ssize_t len;
5597 close(fds[1]);
5599 again:
5600 len = read(fds[0], &status, 1);
5601 if (len == -1 && (errno == EINTR))
5602 goto again;
5604 if (len != 1)
5605 exit(1);
5606 else if (status == 1) {
5607 fprintf(stderr, "Could not acquire pidfile\n");
5608 exit(1);
5609 } else
5610 exit(0);
5611 } else if (pid < 0)
5612 exit(1);
5614 setsid();
5616 pid = fork();
5617 if (pid > 0)
5618 exit(0);
5619 else if (pid < 0)
5620 exit(1);
5622 umask(027);
5624 signal(SIGTSTP, SIG_IGN);
5625 signal(SIGTTOU, SIG_IGN);
5626 signal(SIGTTIN, SIG_IGN);
5629 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5630 if (daemonize) {
5631 uint8_t status = 1;
5632 write(fds[1], &status, 1);
5633 } else
5634 fprintf(stderr, "Could not acquire pid file\n");
5635 exit(1);
5637 #endif
5639 if (qemu_init_main_loop()) {
5640 fprintf(stderr, "qemu_init_main_loop failed\n");
5641 exit(1);
5643 linux_boot = (kernel_filename != NULL);
5645 if (!linux_boot && *kernel_cmdline != '\0') {
5646 fprintf(stderr, "-append only allowed with -kernel option\n");
5647 exit(1);
5650 if (!linux_boot && initrd_filename != NULL) {
5651 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5652 exit(1);
5655 #ifndef _WIN32
5656 /* Win32 doesn't support line-buffering and requires size >= 2 */
5657 setvbuf(stdout, NULL, _IOLBF, 0);
5658 #endif
5660 init_timers();
5661 if (init_timer_alarm() < 0) {
5662 fprintf(stderr, "could not initialize alarm timer\n");
5663 exit(1);
5665 if (use_icount && icount_time_shift < 0) {
5666 use_icount = 2;
5667 /* 125MIPS seems a reasonable initial guess at the guest speed.
5668 It will be corrected fairly quickly anyway. */
5669 icount_time_shift = 3;
5670 init_icount_adjust();
5673 #ifdef _WIN32
5674 socket_init();
5675 #endif
5677 /* init network clients */
5678 if (nb_net_clients == 0) {
5679 /* if no clients, we use a default config */
5680 net_clients[nb_net_clients++] = "nic";
5681 #ifdef CONFIG_SLIRP
5682 net_clients[nb_net_clients++] = "user";
5683 #endif
5686 for(i = 0;i < nb_net_clients; i++) {
5687 if (net_client_parse(net_clients[i]) < 0)
5688 exit(1);
5691 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5692 net_set_boot_mask(net_boot);
5694 net_client_check();
5696 /* init the bluetooth world */
5697 if (foreach_device_config(DEV_BT, bt_parse))
5698 exit(1);
5700 /* init the memory */
5701 if (ram_size == 0)
5702 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5704 /* init the dynamic translator */
5705 cpu_exec_init_all(tb_size * 1024 * 1024);
5707 bdrv_init();
5709 /* we always create the cdrom drive, even if no disk is there */
5710 drive_add(NULL, CDROM_ALIAS);
5712 /* we always create at least one floppy */
5713 drive_add(NULL, FD_ALIAS, 0);
5715 /* we always create one sd slot, even if no card is in it */
5716 drive_add(NULL, SD_ALIAS);
5718 /* open the virtual block devices */
5719 if (snapshot)
5720 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5721 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5722 exit(1);
5724 vmstate_register(0, &vmstate_timers ,&timers_state);
5725 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5727 /* Maintain compatibility with multiple stdio monitors */
5728 if (!strcmp(monitor_devices[0],"stdio")) {
5729 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5730 const char *devname = serial_devices[i];
5731 if (devname && !strcmp(devname,"mon:stdio")) {
5732 monitor_devices[0] = NULL;
5733 break;
5734 } else if (devname && !strcmp(devname,"stdio")) {
5735 monitor_devices[0] = NULL;
5736 serial_devices[i] = "mon:stdio";
5737 break;
5742 if (nb_numa_nodes > 0) {
5743 int i;
5745 if (nb_numa_nodes > smp_cpus) {
5746 nb_numa_nodes = smp_cpus;
5749 /* If no memory size if given for any node, assume the default case
5750 * and distribute the available memory equally across all nodes
5752 for (i = 0; i < nb_numa_nodes; i++) {
5753 if (node_mem[i] != 0)
5754 break;
5756 if (i == nb_numa_nodes) {
5757 uint64_t usedmem = 0;
5759 /* On Linux, the each node's border has to be 8MB aligned,
5760 * the final node gets the rest.
5762 for (i = 0; i < nb_numa_nodes - 1; i++) {
5763 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5764 usedmem += node_mem[i];
5766 node_mem[i] = ram_size - usedmem;
5769 for (i = 0; i < nb_numa_nodes; i++) {
5770 if (node_cpumask[i] != 0)
5771 break;
5773 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5774 * must cope with this anyway, because there are BIOSes out there in
5775 * real machines which also use this scheme.
5777 if (i == nb_numa_nodes) {
5778 for (i = 0; i < smp_cpus; i++) {
5779 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5784 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5785 const char *devname = monitor_devices[i];
5786 if (devname && strcmp(devname, "none")) {
5787 char label[32];
5788 if (i == 0) {
5789 snprintf(label, sizeof(label), "monitor");
5790 } else {
5791 snprintf(label, sizeof(label), "monitor%d", i);
5793 monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5794 if (!monitor_hds[i]) {
5795 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5796 devname);
5797 exit(1);
5802 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5803 const char *devname = serial_devices[i];
5804 if (devname && strcmp(devname, "none")) {
5805 char label[32];
5806 snprintf(label, sizeof(label), "serial%d", i);
5807 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5808 if (!serial_hds[i]) {
5809 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5810 devname);
5811 exit(1);
5816 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5817 const char *devname = parallel_devices[i];
5818 if (devname && strcmp(devname, "none")) {
5819 char label[32];
5820 snprintf(label, sizeof(label), "parallel%d", i);
5821 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5822 if (!parallel_hds[i]) {
5823 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5824 devname);
5825 exit(1);
5830 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5831 const char *devname = virtio_consoles[i];
5832 if (devname && strcmp(devname, "none")) {
5833 char label[32];
5834 snprintf(label, sizeof(label), "virtcon%d", i);
5835 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5836 if (!virtcon_hds[i]) {
5837 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5838 devname);
5839 exit(1);
5844 module_call_init(MODULE_INIT_DEVICE);
5846 if (watchdog) {
5847 i = select_watchdog(watchdog);
5848 if (i > 0)
5849 exit (i == 1 ? 1 : 0);
5852 if (machine->compat_props) {
5853 qdev_prop_register_compat(machine->compat_props);
5855 machine->init(ram_size, boot_devices,
5856 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5859 #ifndef _WIN32
5860 /* must be after terminal init, SDL library changes signal handlers */
5861 sighandler_setup();
5862 #endif
5864 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5865 for (i = 0; i < nb_numa_nodes; i++) {
5866 if (node_cpumask[i] & (1 << env->cpu_index)) {
5867 env->numa_node = i;
5872 current_machine = machine;
5874 /* init USB devices */
5875 if (usb_enabled) {
5876 foreach_device_config(DEV_USB, usb_parse);
5879 /* init generic devices */
5880 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5881 exit(1);
5883 if (!display_state)
5884 dumb_display_init();
5885 /* just use the first displaystate for the moment */
5886 ds = display_state;
5888 if (display_type == DT_DEFAULT) {
5889 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5890 display_type = DT_SDL;
5891 #else
5892 display_type = DT_VNC;
5893 vnc_display = "localhost:0,to=99";
5894 show_vnc_port = 1;
5895 #endif
5899 switch (display_type) {
5900 case DT_NOGRAPHIC:
5901 break;
5902 #if defined(CONFIG_CURSES)
5903 case DT_CURSES:
5904 curses_display_init(ds, full_screen);
5905 break;
5906 #endif
5907 #if defined(CONFIG_SDL)
5908 case DT_SDL:
5909 sdl_display_init(ds, full_screen, no_frame);
5910 break;
5911 #elif defined(CONFIG_COCOA)
5912 case DT_SDL:
5913 cocoa_display_init(ds, full_screen);
5914 break;
5915 #endif
5916 case DT_VNC:
5917 vnc_display_init(ds);
5918 if (vnc_display_open(ds, vnc_display) < 0)
5919 exit(1);
5921 if (show_vnc_port) {
5922 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5924 break;
5925 default:
5926 break;
5928 dpy_resize(ds);
5930 dcl = ds->listeners;
5931 while (dcl != NULL) {
5932 if (dcl->dpy_refresh != NULL) {
5933 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5934 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5936 dcl = dcl->next;
5939 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5940 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5941 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5944 text_consoles_set_display(display_state);
5945 qemu_chr_initial_reset();
5947 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5948 if (monitor_devices[i] && monitor_hds[i]) {
5949 monitor_init(monitor_hds[i],
5950 MONITOR_USE_READLINE |
5951 ((i == 0) ? MONITOR_IS_DEFAULT : 0));
5955 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5956 const char *devname = serial_devices[i];
5957 if (devname && strcmp(devname, "none")) {
5958 if (strstart(devname, "vc", 0))
5959 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5963 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5964 const char *devname = parallel_devices[i];
5965 if (devname && strcmp(devname, "none")) {
5966 if (strstart(devname, "vc", 0))
5967 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5971 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5972 const char *devname = virtio_consoles[i];
5973 if (virtcon_hds[i] && devname) {
5974 if (strstart(devname, "vc", 0))
5975 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5979 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5980 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5981 gdbstub_dev);
5982 exit(1);
5985 if (loadvm) {
5986 if (load_vmstate(cur_mon, loadvm) < 0) {
5987 autostart = 0;
5991 if (incoming) {
5992 qemu_start_incoming_migration(incoming);
5993 } else if (autostart) {
5994 vm_start();
5997 #ifndef _WIN32
5998 if (daemonize) {
5999 uint8_t status = 0;
6000 ssize_t len;
6002 again1:
6003 len = write(fds[1], &status, 1);
6004 if (len == -1 && (errno == EINTR))
6005 goto again1;
6007 if (len != 1)
6008 exit(1);
6010 chdir("/");
6011 TFR(fd = open("/dev/null", O_RDWR));
6012 if (fd == -1)
6013 exit(1);
6016 if (run_as) {
6017 pwd = getpwnam(run_as);
6018 if (!pwd) {
6019 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6020 exit(1);
6024 if (chroot_dir) {
6025 if (chroot(chroot_dir) < 0) {
6026 fprintf(stderr, "chroot failed\n");
6027 exit(1);
6029 chdir("/");
6032 if (run_as) {
6033 if (setgid(pwd->pw_gid) < 0) {
6034 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6035 exit(1);
6037 if (setuid(pwd->pw_uid) < 0) {
6038 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6039 exit(1);
6041 if (setuid(0) != -1) {
6042 fprintf(stderr, "Dropping privileges failed\n");
6043 exit(1);
6047 if (daemonize) {
6048 dup2(fd, 0);
6049 dup2(fd, 1);
6050 dup2(fd, 2);
6052 close(fd);
6054 #endif
6056 main_loop();
6057 quit_timers();
6058 net_cleanup();
6060 return 0;