net: fix vnet_hdr bustage with slirp
[qemu-kvm/markmc.git] / vl.c
blob80ad7aee1099bf68a3398e51a97b23f55aa82683
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"
34 /* Needed early to override system queue definitions on BSD */
35 #include "sys-queue.h"
37 #ifndef _WIN32
38 #include <libgen.h>
39 #include <pwd.h>
40 #include <sys/times.h>
41 #include <sys/wait.h>
42 #include <termios.h>
43 #include <sys/mman.h>
44 #include <sys/ioctl.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <net/if.h>
49 #if defined(__NetBSD__)
50 #include <net/if_tap.h>
51 #endif
52 #ifdef __linux__
53 #include <linux/if_tun.h>
54 #endif
55 #include <arpa/inet.h>
56 #include <dirent.h>
57 #include <netdb.h>
58 #include <sys/select.h>
59 #ifdef CONFIG_BSD
60 #include <sys/stat.h>
61 #if defined(__FreeBSD__) || defined(__DragonFly__)
62 #include <libutil.h>
63 #else
64 #include <util.h>
65 #endif
66 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
67 #include <freebsd/stdlib.h>
68 #else
69 #ifdef __linux__
70 #include <pty.h>
71 #include <malloc.h>
72 #include <linux/rtc.h>
73 #include <sys/prctl.h>
75 /* For the benefit of older linux systems which don't supply it,
76 we use a local copy of hpet.h. */
77 /* #include <linux/hpet.h> */
78 #include "hpet.h"
80 #include <linux/ppdev.h>
81 #include <linux/parport.h>
82 #endif
83 #ifdef __sun__
84 #include <sys/stat.h>
85 #include <sys/ethernet.h>
86 #include <sys/sockio.h>
87 #include <netinet/arp.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> // must come after ip.h
92 #include <netinet/udp.h>
93 #include <netinet/tcp.h>
94 #include <net/if.h>
95 #include <syslog.h>
96 #include <stropts.h>
97 #endif
98 #endif
99 #endif
101 #if defined(__OpenBSD__)
102 #include <util.h>
103 #endif
105 #if defined(CONFIG_VDE)
106 #include <libvdeplug.h>
107 #endif
109 #ifdef _WIN32
110 #include <windows.h>
111 #include <mmsystem.h>
112 #endif
114 #ifdef CONFIG_SDL
115 #if defined(__APPLE__) || defined(main)
116 #include <SDL.h>
117 int qemu_main(int argc, char **argv, char **envp);
118 int main(int argc, char **argv)
120 return qemu_main(argc, argv, NULL);
122 #undef main
123 #define main qemu_main
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "hw/hw.h"
133 #include "hw/boards.h"
134 #include "hw/usb.h"
135 #include "hw/pcmcia.h"
136 #include "hw/pc.h"
137 #include "hw/audiodev.h"
138 #include "hw/isa.h"
139 #include "hw/baum.h"
140 #include "hw/bt.h"
141 #include "hw/watchdog.h"
142 #include "hw/smbios.h"
143 #include "hw/xen.h"
144 #include "hw/qdev.h"
145 #include "bt-host.h"
146 #include "net.h"
147 #include "monitor.h"
148 #include "console.h"
149 #include "sysemu.h"
150 #include "gdbstub.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
154 #include "block.h"
155 #include "dma.h"
156 #include "audio/audio.h"
157 #include "migration.h"
158 #include "kvm.h"
159 #include "balloon.h"
160 #include "qemu-option.h"
161 #include "qemu-kvm.h"
162 #include "hw/device-assignment.h"
164 #include "disas.h"
166 #include "exec-all.h"
168 #include "qemu_socket.h"
170 #include "slirp/libslirp.h"
172 //#define DEBUG_NET
173 //#define DEBUG_SLIRP
175 #define DEFAULT_RAM_SIZE 128
177 static const char *data_dir;
178 const char *bios_name = NULL;
179 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
180 to store the VM snapshots */
181 struct drivelist drives = TAILQ_HEAD_INITIALIZER(drives);
182 struct driveoptlist driveopts = TAILQ_HEAD_INITIALIZER(driveopts);
183 DriveInfo *extboot_drive = NULL;
184 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
185 static DisplayState *display_state;
186 DisplayType display_type = DT_DEFAULT;
187 const char* keyboard_layout = NULL;
188 int64_t ticks_per_sec;
189 ram_addr_t ram_size;
190 int nb_nics;
191 NICInfo nd_table[MAX_NICS];
192 int vm_running;
193 int autostart;
194 static int rtc_utc = 1;
195 static int rtc_date_offset = -1; /* -1 means no change */
196 int cirrus_vga_enabled = 1;
197 int std_vga_enabled = 0;
198 int vmsvga_enabled = 0;
199 int xenfb_enabled = 0;
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 const char *vnc_display;
228 int acpi_enabled = 1;
229 #ifdef TARGET_I386
230 int no_hpet = 0;
231 #endif
232 int virtio_balloon = 1;
233 const char *virtio_balloon_devaddr;
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 WatchdogTimerModel *watchdog = NULL;
244 int watchdog_action = WDT_RESET;
245 const char *option_rom[MAX_OPTION_ROMS];
246 int nb_option_roms;
247 int semihosting_enabled = 0;
248 int time_drift_fix = 0;
249 unsigned int kvm_shadow_memory = 0;
250 const char *mem_path = NULL;
251 #ifdef MAP_POPULATE
252 int mem_prealloc = 1; /* force preallocation of physical target memory */
253 #endif
254 #ifdef TARGET_ARM
255 int old_param = 0;
256 #endif
257 const char *qemu_name;
258 int alt_grab = 0;
259 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
260 unsigned int nb_prom_envs = 0;
261 const char *prom_envs[MAX_PROM_ENVS];
262 #endif
263 const char *nvram = NULL;
264 int boot_menu;
266 int nb_numa_nodes;
267 uint64_t node_mem[MAX_NODES];
268 uint64_t node_cpumask[MAX_NODES];
270 static CPUState *cur_cpu;
271 static CPUState *next_cpu;
272 static int timer_alarm_pending = 1;
273 /* Conversion factor from emulated instructions to virtual clock ticks. */
274 static int icount_time_shift;
275 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
276 #define MAX_ICOUNT_SHIFT 10
277 /* Compensate for varying guest execution speed. */
278 static int64_t qemu_icount_bias;
279 static QEMUTimer *icount_rt_timer;
280 static QEMUTimer *icount_vm_timer;
281 static QEMUTimer *nographic_timer;
283 uint8_t qemu_uuid[16];
285 static QEMUBootSetHandler *boot_set_handler;
286 static void *boot_set_opaque;
288 /***********************************************************/
289 /* x86 ISA bus support */
291 target_phys_addr_t isa_mem_base = 0;
292 PicState2 *isa_pic;
294 /***********************************************************/
295 void hw_error(const char *fmt, ...)
297 va_list ap;
298 CPUState *env;
300 va_start(ap, fmt);
301 fprintf(stderr, "qemu: hardware error: ");
302 vfprintf(stderr, fmt, ap);
303 fprintf(stderr, "\n");
304 for(env = first_cpu; env != NULL; env = env->next_cpu) {
305 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
306 #ifdef TARGET_I386
307 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
308 #else
309 cpu_dump_state(env, stderr, fprintf, 0);
310 #endif
312 va_end(ap);
313 abort();
316 static void set_proc_name(const char *s)
318 #ifdef __linux__
319 char name[16];
320 if (!s)
321 return;
322 name[sizeof(name) - 1] = 0;
323 strncpy(name, s, sizeof(name));
324 /* Could rewrite argv[0] too, but that's a bit more complicated.
325 This simple way is enough for `top'. */
326 prctl(PR_SET_NAME, name);
327 #endif
330 /***************/
331 /* ballooning */
333 static QEMUBalloonEvent *qemu_balloon_event;
334 void *qemu_balloon_event_opaque;
336 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
338 qemu_balloon_event = func;
339 qemu_balloon_event_opaque = opaque;
342 void qemu_balloon(ram_addr_t target)
344 if (qemu_balloon_event)
345 qemu_balloon_event(qemu_balloon_event_opaque, target);
348 ram_addr_t qemu_balloon_status(void)
350 if (qemu_balloon_event)
351 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
352 return 0;
355 /***********************************************************/
356 /* keyboard/mouse */
358 static QEMUPutKBDEvent *qemu_put_kbd_event;
359 static void *qemu_put_kbd_event_opaque;
360 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
361 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
363 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
365 qemu_put_kbd_event_opaque = opaque;
366 qemu_put_kbd_event = func;
369 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
370 void *opaque, int absolute,
371 const char *name)
373 QEMUPutMouseEntry *s, *cursor;
375 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
377 s->qemu_put_mouse_event = func;
378 s->qemu_put_mouse_event_opaque = opaque;
379 s->qemu_put_mouse_event_absolute = absolute;
380 s->qemu_put_mouse_event_name = qemu_strdup(name);
381 s->next = NULL;
383 if (!qemu_put_mouse_event_head) {
384 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
385 return s;
388 cursor = qemu_put_mouse_event_head;
389 while (cursor->next != NULL)
390 cursor = cursor->next;
392 cursor->next = s;
393 qemu_put_mouse_event_current = s;
395 return s;
398 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
400 QEMUPutMouseEntry *prev = NULL, *cursor;
402 if (!qemu_put_mouse_event_head || entry == NULL)
403 return;
405 cursor = qemu_put_mouse_event_head;
406 while (cursor != NULL && cursor != entry) {
407 prev = cursor;
408 cursor = cursor->next;
411 if (cursor == NULL) // does not exist or list empty
412 return;
413 else if (prev == NULL) { // entry is head
414 qemu_put_mouse_event_head = cursor->next;
415 if (qemu_put_mouse_event_current == entry)
416 qemu_put_mouse_event_current = cursor->next;
417 qemu_free(entry->qemu_put_mouse_event_name);
418 qemu_free(entry);
419 return;
422 prev->next = entry->next;
424 if (qemu_put_mouse_event_current == entry)
425 qemu_put_mouse_event_current = prev;
427 qemu_free(entry->qemu_put_mouse_event_name);
428 qemu_free(entry);
431 void kbd_put_keycode(int keycode)
433 if (qemu_put_kbd_event) {
434 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
438 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
440 QEMUPutMouseEvent *mouse_event;
441 void *mouse_event_opaque;
442 int width;
444 if (!qemu_put_mouse_event_current) {
445 return;
448 mouse_event =
449 qemu_put_mouse_event_current->qemu_put_mouse_event;
450 mouse_event_opaque =
451 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
453 if (mouse_event) {
454 if (graphic_rotate) {
455 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
456 width = 0x7fff;
457 else
458 width = graphic_width - 1;
459 mouse_event(mouse_event_opaque,
460 width - dy, dx, dz, buttons_state);
461 } else
462 mouse_event(mouse_event_opaque,
463 dx, dy, dz, buttons_state);
467 int kbd_mouse_is_absolute(void)
469 if (!qemu_put_mouse_event_current)
470 return 0;
472 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
475 void do_info_mice(Monitor *mon)
477 QEMUPutMouseEntry *cursor;
478 int index = 0;
480 if (!qemu_put_mouse_event_head) {
481 monitor_printf(mon, "No mouse devices connected\n");
482 return;
485 monitor_printf(mon, "Mouse devices available:\n");
486 cursor = qemu_put_mouse_event_head;
487 while (cursor != NULL) {
488 monitor_printf(mon, "%c Mouse #%d: %s\n",
489 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
490 index, cursor->qemu_put_mouse_event_name);
491 index++;
492 cursor = cursor->next;
496 void do_mouse_set(Monitor *mon, int index)
498 QEMUPutMouseEntry *cursor;
499 int i = 0;
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 #define QEMU_TIMER_BASE 1000000000LL
547 #ifdef WIN32
549 static int64_t clock_freq;
551 static void init_get_clock(void)
553 LARGE_INTEGER freq;
554 int ret;
555 ret = QueryPerformanceFrequency(&freq);
556 if (ret == 0) {
557 fprintf(stderr, "Could not calibrate ticks\n");
558 exit(1);
560 clock_freq = freq.QuadPart;
563 static int64_t get_clock(void)
565 LARGE_INTEGER ti;
566 QueryPerformanceCounter(&ti);
567 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
570 #else
572 static int use_rt_clock;
574 static void init_get_clock(void)
576 use_rt_clock = 0;
577 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
578 || defined(__DragonFly__)
580 struct timespec ts;
581 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
582 use_rt_clock = 1;
585 #endif
588 static int64_t get_clock(void)
590 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
591 || defined(__DragonFly__)
592 if (use_rt_clock) {
593 struct timespec ts;
594 clock_gettime(CLOCK_MONOTONIC, &ts);
595 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
596 } else
597 #endif
599 /* XXX: using gettimeofday leads to problems if the date
600 changes, so it should be avoided. */
601 struct timeval tv;
602 gettimeofday(&tv, NULL);
603 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
606 #endif
608 /* Return the virtual CPU time, based on the instruction counter. */
609 static int64_t cpu_get_icount(void)
611 int64_t icount;
612 CPUState *env = cpu_single_env;;
613 icount = qemu_icount;
614 if (env) {
615 if (!can_do_io(env))
616 fprintf(stderr, "Bad clock read\n");
617 icount -= (env->icount_decr.u16.low + env->icount_extra);
619 return qemu_icount_bias + (icount << icount_time_shift);
622 /***********************************************************/
623 /* guest cycle counter */
625 static int64_t cpu_ticks_prev;
626 static int64_t cpu_ticks_offset;
627 static int64_t cpu_clock_offset;
628 static int cpu_ticks_enabled;
630 /* return the host CPU cycle counter and handle stop/restart */
631 int64_t cpu_get_ticks(void)
633 if (use_icount) {
634 return cpu_get_icount();
636 if (!cpu_ticks_enabled) {
637 return cpu_ticks_offset;
638 } else {
639 int64_t ticks;
640 ticks = cpu_get_real_ticks();
641 if (cpu_ticks_prev > ticks) {
642 /* Note: non increasing ticks may happen if the host uses
643 software suspend */
644 cpu_ticks_offset += cpu_ticks_prev - ticks;
646 cpu_ticks_prev = ticks;
647 return ticks + cpu_ticks_offset;
651 /* return the host CPU monotonic timer and handle stop/restart */
652 static int64_t cpu_get_clock(void)
654 int64_t ti;
655 if (!cpu_ticks_enabled) {
656 return cpu_clock_offset;
657 } else {
658 ti = get_clock();
659 return ti + cpu_clock_offset;
663 /* enable cpu_get_ticks() */
664 void cpu_enable_ticks(void)
666 if (!cpu_ticks_enabled) {
667 cpu_ticks_offset -= cpu_get_real_ticks();
668 cpu_clock_offset -= get_clock();
669 cpu_ticks_enabled = 1;
673 /* disable cpu_get_ticks() : the clock is stopped. You must not call
674 cpu_get_ticks() after that. */
675 void cpu_disable_ticks(void)
677 if (cpu_ticks_enabled) {
678 cpu_ticks_offset = cpu_get_ticks();
679 cpu_clock_offset = cpu_get_clock();
680 cpu_ticks_enabled = 0;
684 /***********************************************************/
685 /* timers */
687 #define QEMU_TIMER_REALTIME 0
688 #define QEMU_TIMER_VIRTUAL 1
690 struct QEMUClock {
691 int type;
692 /* XXX: add frequency */
695 struct QEMUTimer {
696 QEMUClock *clock;
697 int64_t expire_time;
698 QEMUTimerCB *cb;
699 void *opaque;
700 struct QEMUTimer *next;
703 struct qemu_alarm_timer {
704 char const *name;
705 unsigned int flags;
707 int (*start)(struct qemu_alarm_timer *t);
708 void (*stop)(struct qemu_alarm_timer *t);
709 void (*rearm)(struct qemu_alarm_timer *t);
710 void *priv;
713 #define ALARM_FLAG_DYNTICKS 0x1
714 #define ALARM_FLAG_EXPIRED 0x2
716 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
718 return t && (t->flags & ALARM_FLAG_DYNTICKS);
721 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
723 if (!alarm_has_dynticks(t))
724 return;
726 t->rearm(t);
729 /* TODO: MIN_TIMER_REARM_US should be optimized */
730 #define MIN_TIMER_REARM_US 250
732 static struct qemu_alarm_timer *alarm_timer;
734 #ifdef _WIN32
736 struct qemu_alarm_win32 {
737 MMRESULT timerId;
738 unsigned int period;
739 } alarm_win32_data = {0, -1};
741 static int win32_start_timer(struct qemu_alarm_timer *t);
742 static void win32_stop_timer(struct qemu_alarm_timer *t);
743 static void win32_rearm_timer(struct qemu_alarm_timer *t);
745 #else
747 static int unix_start_timer(struct qemu_alarm_timer *t);
748 static void unix_stop_timer(struct qemu_alarm_timer *t);
750 #ifdef __linux__
752 static int dynticks_start_timer(struct qemu_alarm_timer *t);
753 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
754 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
756 static int hpet_start_timer(struct qemu_alarm_timer *t);
757 static void hpet_stop_timer(struct qemu_alarm_timer *t);
759 static int rtc_start_timer(struct qemu_alarm_timer *t);
760 static void rtc_stop_timer(struct qemu_alarm_timer *t);
762 #endif /* __linux__ */
764 #endif /* _WIN32 */
766 /* Correlation between real and virtual time is always going to be
767 fairly approximate, so ignore small variation.
768 When the guest is idle real and virtual time will be aligned in
769 the IO wait loop. */
770 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
772 static void icount_adjust(void)
774 int64_t cur_time;
775 int64_t cur_icount;
776 int64_t delta;
777 static int64_t last_delta;
778 /* If the VM is not running, then do nothing. */
779 if (!vm_running)
780 return;
782 cur_time = cpu_get_clock();
783 cur_icount = qemu_get_clock(vm_clock);
784 delta = cur_icount - cur_time;
785 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
786 if (delta > 0
787 && last_delta + ICOUNT_WOBBLE < delta * 2
788 && icount_time_shift > 0) {
789 /* The guest is getting too far ahead. Slow time down. */
790 icount_time_shift--;
792 if (delta < 0
793 && last_delta - ICOUNT_WOBBLE > delta * 2
794 && icount_time_shift < MAX_ICOUNT_SHIFT) {
795 /* The guest is getting too far behind. Speed time up. */
796 icount_time_shift++;
798 last_delta = delta;
799 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
802 static void icount_adjust_rt(void * opaque)
804 qemu_mod_timer(icount_rt_timer,
805 qemu_get_clock(rt_clock) + 1000);
806 icount_adjust();
809 static void icount_adjust_vm(void * opaque)
811 qemu_mod_timer(icount_vm_timer,
812 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
813 icount_adjust();
816 static void init_icount_adjust(void)
818 /* Have both realtime and virtual time triggers for speed adjustment.
819 The realtime trigger catches emulated time passing too slowly,
820 the virtual time trigger catches emulated time passing too fast.
821 Realtime triggers occur even when idle, so use them less frequently
822 than VM triggers. */
823 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
824 qemu_mod_timer(icount_rt_timer,
825 qemu_get_clock(rt_clock) + 1000);
826 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
827 qemu_mod_timer(icount_vm_timer,
828 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
831 static struct qemu_alarm_timer alarm_timers[] = {
832 #ifndef _WIN32
833 #ifdef __linux__
834 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
835 dynticks_stop_timer, dynticks_rearm_timer, NULL},
836 /* HPET - if available - is preferred */
837 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
838 /* ...otherwise try RTC */
839 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
840 #endif
841 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
842 #else
843 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
844 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
845 {"win32", 0, win32_start_timer,
846 win32_stop_timer, NULL, &alarm_win32_data},
847 #endif
848 {NULL, }
851 static void show_available_alarms(void)
853 int i;
855 printf("Available alarm timers, in order of precedence:\n");
856 for (i = 0; alarm_timers[i].name; i++)
857 printf("%s\n", alarm_timers[i].name);
860 static void configure_alarms(char const *opt)
862 int i;
863 int cur = 0;
864 int count = ARRAY_SIZE(alarm_timers) - 1;
865 char *arg;
866 char *name;
867 struct qemu_alarm_timer tmp;
869 if (!strcmp(opt, "?")) {
870 show_available_alarms();
871 exit(0);
874 arg = strdup(opt);
876 /* Reorder the array */
877 name = strtok(arg, ",");
878 while (name) {
879 for (i = 0; i < count && alarm_timers[i].name; i++) {
880 if (!strcmp(alarm_timers[i].name, name))
881 break;
884 if (i == count) {
885 fprintf(stderr, "Unknown clock %s\n", name);
886 goto next;
889 if (i < cur)
890 /* Ignore */
891 goto next;
893 /* Swap */
894 tmp = alarm_timers[i];
895 alarm_timers[i] = alarm_timers[cur];
896 alarm_timers[cur] = tmp;
898 cur++;
899 next:
900 name = strtok(NULL, ",");
903 free(arg);
905 if (cur) {
906 /* Disable remaining timers */
907 for (i = cur; i < count; i++)
908 alarm_timers[i].name = NULL;
909 } else {
910 show_available_alarms();
911 exit(1);
915 QEMUClock *rt_clock;
916 QEMUClock *vm_clock;
918 static QEMUTimer *active_timers[2];
920 static QEMUClock *qemu_new_clock(int type)
922 QEMUClock *clock;
923 clock = qemu_mallocz(sizeof(QEMUClock));
924 clock->type = type;
925 return clock;
928 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
930 QEMUTimer *ts;
932 ts = qemu_mallocz(sizeof(QEMUTimer));
933 ts->clock = clock;
934 ts->cb = cb;
935 ts->opaque = opaque;
936 return ts;
939 void qemu_free_timer(QEMUTimer *ts)
941 qemu_free(ts);
944 /* stop a timer, but do not dealloc it */
945 void qemu_del_timer(QEMUTimer *ts)
947 QEMUTimer **pt, *t;
949 /* NOTE: this code must be signal safe because
950 qemu_timer_expired() can be called from a signal. */
951 pt = &active_timers[ts->clock->type];
952 for(;;) {
953 t = *pt;
954 if (!t)
955 break;
956 if (t == ts) {
957 *pt = t->next;
958 break;
960 pt = &t->next;
964 /* modify the current timer so that it will be fired when current_time
965 >= expire_time. The corresponding callback will be called. */
966 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
968 QEMUTimer **pt, *t;
970 qemu_del_timer(ts);
972 /* add the timer in the sorted list */
973 /* NOTE: this code must be signal safe because
974 qemu_timer_expired() can be called from a signal. */
975 pt = &active_timers[ts->clock->type];
976 for(;;) {
977 t = *pt;
978 if (!t)
979 break;
980 if (t->expire_time > expire_time)
981 break;
982 pt = &t->next;
984 ts->expire_time = expire_time;
985 ts->next = *pt;
986 *pt = ts;
988 /* Rearm if necessary */
989 if (pt == &active_timers[ts->clock->type]) {
990 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
991 qemu_rearm_alarm_timer(alarm_timer);
993 /* Interrupt execution to force deadline recalculation. */
994 if (use_icount)
995 qemu_notify_event();
999 int qemu_timer_pending(QEMUTimer *ts)
1001 QEMUTimer *t;
1002 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1003 if (t == ts)
1004 return 1;
1006 return 0;
1009 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1011 if (!timer_head)
1012 return 0;
1013 return (timer_head->expire_time <= current_time);
1016 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1018 QEMUTimer *ts;
1020 for(;;) {
1021 ts = *ptimer_head;
1022 if (!ts || ts->expire_time > current_time)
1023 break;
1024 /* remove timer from the list before calling the callback */
1025 *ptimer_head = ts->next;
1026 ts->next = NULL;
1028 /* run the callback (the timer list can be modified) */
1029 ts->cb(ts->opaque);
1033 int64_t qemu_get_clock(QEMUClock *clock)
1035 switch(clock->type) {
1036 case QEMU_TIMER_REALTIME:
1037 return get_clock() / 1000000;
1038 default:
1039 case QEMU_TIMER_VIRTUAL:
1040 if (use_icount) {
1041 return cpu_get_icount();
1042 } else {
1043 return cpu_get_clock();
1048 static void init_timers(void)
1050 init_get_clock();
1051 ticks_per_sec = QEMU_TIMER_BASE;
1052 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1053 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1056 /* save a timer */
1057 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1059 uint64_t expire_time;
1061 if (qemu_timer_pending(ts)) {
1062 expire_time = ts->expire_time;
1063 } else {
1064 expire_time = -1;
1066 qemu_put_be64(f, expire_time);
1069 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1071 uint64_t expire_time;
1073 expire_time = qemu_get_be64(f);
1074 if (expire_time != -1) {
1075 qemu_mod_timer(ts, expire_time);
1076 } else {
1077 qemu_del_timer(ts);
1081 static void timer_save(QEMUFile *f, void *opaque)
1083 if (cpu_ticks_enabled) {
1084 hw_error("cannot save state if virtual timers are running");
1086 qemu_put_be64(f, cpu_ticks_offset);
1087 qemu_put_be64(f, ticks_per_sec);
1088 qemu_put_be64(f, cpu_clock_offset);
1091 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1093 if (version_id != 1 && version_id != 2)
1094 return -EINVAL;
1095 if (cpu_ticks_enabled) {
1096 return -EINVAL;
1098 cpu_ticks_offset=qemu_get_be64(f);
1099 ticks_per_sec=qemu_get_be64(f);
1100 if (version_id == 2) {
1101 cpu_clock_offset=qemu_get_be64(f);
1103 return 0;
1106 static void qemu_event_increment(void);
1108 #ifdef _WIN32
1109 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1110 DWORD_PTR dwUser, DWORD_PTR dw1,
1111 DWORD_PTR dw2)
1112 #else
1113 static void host_alarm_handler(int host_signum)
1114 #endif
1116 #if 0
1117 #define DISP_FREQ 1000
1119 static int64_t delta_min = INT64_MAX;
1120 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1121 static int count;
1122 ti = qemu_get_clock(vm_clock);
1123 if (last_clock != 0) {
1124 delta = ti - last_clock;
1125 if (delta < delta_min)
1126 delta_min = delta;
1127 if (delta > delta_max)
1128 delta_max = delta;
1129 delta_cum += delta;
1130 if (++count == DISP_FREQ) {
1131 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1132 muldiv64(delta_min, 1000000, ticks_per_sec),
1133 muldiv64(delta_max, 1000000, ticks_per_sec),
1134 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1135 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1136 count = 0;
1137 delta_min = INT64_MAX;
1138 delta_max = 0;
1139 delta_cum = 0;
1142 last_clock = ti;
1144 #endif
1145 if (alarm_has_dynticks(alarm_timer) ||
1146 (!use_icount &&
1147 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1148 qemu_get_clock(vm_clock))) ||
1149 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1150 qemu_get_clock(rt_clock))) {
1151 qemu_event_increment();
1152 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1154 #ifndef CONFIG_IOTHREAD
1155 if (next_cpu) {
1156 /* stop the currently executing cpu because a timer occured */
1157 cpu_exit(next_cpu);
1158 #ifdef CONFIG_KQEMU
1159 if (next_cpu->kqemu_enabled) {
1160 kqemu_cpu_interrupt(next_cpu);
1162 #endif
1164 #endif
1165 timer_alarm_pending = 1;
1166 qemu_notify_event();
1170 static int64_t qemu_next_deadline(void)
1172 int64_t delta;
1174 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1175 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1176 qemu_get_clock(vm_clock);
1177 } else {
1178 /* To avoid problems with overflow limit this to 2^32. */
1179 delta = INT32_MAX;
1182 if (delta < 0)
1183 delta = 0;
1185 return delta;
1188 #if defined(__linux__) || defined(_WIN32)
1189 static uint64_t qemu_next_deadline_dyntick(void)
1191 int64_t delta;
1192 int64_t rtdelta;
1194 if (use_icount)
1195 delta = INT32_MAX;
1196 else
1197 delta = (qemu_next_deadline() + 999) / 1000;
1199 if (active_timers[QEMU_TIMER_REALTIME]) {
1200 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1201 qemu_get_clock(rt_clock))*1000;
1202 if (rtdelta < delta)
1203 delta = rtdelta;
1206 if (delta < MIN_TIMER_REARM_US)
1207 delta = MIN_TIMER_REARM_US;
1209 return delta;
1211 #endif
1213 #ifndef _WIN32
1215 /* Sets a specific flag */
1216 static int fcntl_setfl(int fd, int flag)
1218 int flags;
1220 flags = fcntl(fd, F_GETFL);
1221 if (flags == -1)
1222 return -errno;
1224 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1225 return -errno;
1227 return 0;
1230 #if defined(__linux__)
1232 #define RTC_FREQ 1024
1234 static void enable_sigio_timer(int fd)
1236 struct sigaction act;
1238 /* timer signal */
1239 sigfillset(&act.sa_mask);
1240 act.sa_flags = 0;
1241 act.sa_handler = host_alarm_handler;
1243 sigaction(SIGIO, &act, NULL);
1244 fcntl_setfl(fd, O_ASYNC);
1245 fcntl(fd, F_SETOWN, getpid());
1248 static int hpet_start_timer(struct qemu_alarm_timer *t)
1250 struct hpet_info info;
1251 int r, fd;
1253 fd = open("/dev/hpet", O_RDONLY);
1254 if (fd < 0)
1255 return -1;
1257 /* Set frequency */
1258 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1259 if (r < 0) {
1260 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1261 "error, but for better emulation accuracy type:\n"
1262 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1263 goto fail;
1266 /* Check capabilities */
1267 r = ioctl(fd, HPET_INFO, &info);
1268 if (r < 0)
1269 goto fail;
1271 /* Enable periodic mode */
1272 r = ioctl(fd, HPET_EPI, 0);
1273 if (info.hi_flags && (r < 0))
1274 goto fail;
1276 /* Enable interrupt */
1277 r = ioctl(fd, HPET_IE_ON, 0);
1278 if (r < 0)
1279 goto fail;
1281 enable_sigio_timer(fd);
1282 t->priv = (void *)(long)fd;
1284 return 0;
1285 fail:
1286 close(fd);
1287 return -1;
1290 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1292 int fd = (long)t->priv;
1294 close(fd);
1297 static int rtc_start_timer(struct qemu_alarm_timer *t)
1299 int rtc_fd;
1300 unsigned long current_rtc_freq = 0;
1302 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1303 if (rtc_fd < 0)
1304 return -1;
1305 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1306 if (current_rtc_freq != RTC_FREQ &&
1307 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1308 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1309 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1310 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1311 goto fail;
1313 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1314 fail:
1315 close(rtc_fd);
1316 return -1;
1319 enable_sigio_timer(rtc_fd);
1321 t->priv = (void *)(long)rtc_fd;
1323 return 0;
1326 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1328 int rtc_fd = (long)t->priv;
1330 close(rtc_fd);
1333 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1335 struct sigevent ev;
1336 timer_t host_timer;
1337 struct sigaction act;
1339 sigfillset(&act.sa_mask);
1340 act.sa_flags = 0;
1341 act.sa_handler = host_alarm_handler;
1343 sigaction(SIGALRM, &act, NULL);
1346 * Initialize ev struct to 0 to avoid valgrind complaining
1347 * about uninitialized data in timer_create call
1349 memset(&ev, 0, sizeof(ev));
1350 ev.sigev_value.sival_int = 0;
1351 ev.sigev_notify = SIGEV_SIGNAL;
1352 ev.sigev_signo = SIGALRM;
1354 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1355 perror("timer_create");
1357 /* disable dynticks */
1358 fprintf(stderr, "Dynamic Ticks disabled\n");
1360 return -1;
1363 t->priv = (void *)(long)host_timer;
1365 return 0;
1368 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1370 timer_t host_timer = (timer_t)(long)t->priv;
1372 timer_delete(host_timer);
1375 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1377 timer_t host_timer = (timer_t)(long)t->priv;
1378 struct itimerspec timeout;
1379 int64_t nearest_delta_us = INT64_MAX;
1380 int64_t current_us;
1382 if (!active_timers[QEMU_TIMER_REALTIME] &&
1383 !active_timers[QEMU_TIMER_VIRTUAL])
1384 return;
1386 nearest_delta_us = qemu_next_deadline_dyntick();
1388 /* check whether a timer is already running */
1389 if (timer_gettime(host_timer, &timeout)) {
1390 perror("gettime");
1391 fprintf(stderr, "Internal timer error: aborting\n");
1392 exit(1);
1394 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1395 if (current_us && current_us <= nearest_delta_us)
1396 return;
1398 timeout.it_interval.tv_sec = 0;
1399 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1400 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1401 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1402 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1403 perror("settime");
1404 fprintf(stderr, "Internal timer error: aborting\n");
1405 exit(1);
1409 #endif /* defined(__linux__) */
1411 static int unix_start_timer(struct qemu_alarm_timer *t)
1413 struct sigaction act;
1414 struct itimerval itv;
1415 int err;
1417 /* timer signal */
1418 sigfillset(&act.sa_mask);
1419 act.sa_flags = 0;
1420 act.sa_handler = host_alarm_handler;
1422 sigaction(SIGALRM, &act, NULL);
1424 itv.it_interval.tv_sec = 0;
1425 /* for i386 kernel 2.6 to get 1 ms */
1426 itv.it_interval.tv_usec = 999;
1427 itv.it_value.tv_sec = 0;
1428 itv.it_value.tv_usec = 10 * 1000;
1430 err = setitimer(ITIMER_REAL, &itv, NULL);
1431 if (err)
1432 return -1;
1434 return 0;
1437 static void unix_stop_timer(struct qemu_alarm_timer *t)
1439 struct itimerval itv;
1441 memset(&itv, 0, sizeof(itv));
1442 setitimer(ITIMER_REAL, &itv, NULL);
1445 #endif /* !defined(_WIN32) */
1448 #ifdef _WIN32
1450 static int win32_start_timer(struct qemu_alarm_timer *t)
1452 TIMECAPS tc;
1453 struct qemu_alarm_win32 *data = t->priv;
1454 UINT flags;
1456 memset(&tc, 0, sizeof(tc));
1457 timeGetDevCaps(&tc, sizeof(tc));
1459 if (data->period < tc.wPeriodMin)
1460 data->period = tc.wPeriodMin;
1462 timeBeginPeriod(data->period);
1464 flags = TIME_CALLBACK_FUNCTION;
1465 if (alarm_has_dynticks(t))
1466 flags |= TIME_ONESHOT;
1467 else
1468 flags |= TIME_PERIODIC;
1470 data->timerId = timeSetEvent(1, // interval (ms)
1471 data->period, // resolution
1472 host_alarm_handler, // function
1473 (DWORD)t, // parameter
1474 flags);
1476 if (!data->timerId) {
1477 perror("Failed to initialize win32 alarm timer");
1478 timeEndPeriod(data->period);
1479 return -1;
1482 return 0;
1485 static void win32_stop_timer(struct qemu_alarm_timer *t)
1487 struct qemu_alarm_win32 *data = t->priv;
1489 timeKillEvent(data->timerId);
1490 timeEndPeriod(data->period);
1493 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1495 struct qemu_alarm_win32 *data = t->priv;
1496 uint64_t nearest_delta_us;
1498 if (!active_timers[QEMU_TIMER_REALTIME] &&
1499 !active_timers[QEMU_TIMER_VIRTUAL])
1500 return;
1502 nearest_delta_us = qemu_next_deadline_dyntick();
1503 nearest_delta_us /= 1000;
1505 timeKillEvent(data->timerId);
1507 data->timerId = timeSetEvent(1,
1508 data->period,
1509 host_alarm_handler,
1510 (DWORD)t,
1511 TIME_ONESHOT | TIME_PERIODIC);
1513 if (!data->timerId) {
1514 perror("Failed to re-arm win32 alarm timer");
1516 timeEndPeriod(data->period);
1517 exit(1);
1521 #endif /* _WIN32 */
1523 static int init_timer_alarm(void)
1525 struct qemu_alarm_timer *t = NULL;
1526 int i, err = -1;
1528 for (i = 0; alarm_timers[i].name; i++) {
1529 t = &alarm_timers[i];
1531 err = t->start(t);
1532 if (!err)
1533 break;
1536 if (err) {
1537 err = -ENOENT;
1538 goto fail;
1541 alarm_timer = t;
1543 return 0;
1545 fail:
1546 return err;
1549 static void quit_timers(void)
1551 alarm_timer->stop(alarm_timer);
1552 alarm_timer = NULL;
1555 /***********************************************************/
1556 /* host time/date access */
1557 void qemu_get_timedate(struct tm *tm, int offset)
1559 time_t ti;
1560 struct tm *ret;
1562 time(&ti);
1563 ti += offset;
1564 if (rtc_date_offset == -1) {
1565 if (rtc_utc)
1566 ret = gmtime(&ti);
1567 else
1568 ret = localtime(&ti);
1569 } else {
1570 ti -= rtc_date_offset;
1571 ret = gmtime(&ti);
1574 memcpy(tm, ret, sizeof(struct tm));
1577 int qemu_timedate_diff(struct tm *tm)
1579 time_t seconds;
1581 if (rtc_date_offset == -1)
1582 if (rtc_utc)
1583 seconds = mktimegm(tm);
1584 else
1585 seconds = mktime(tm);
1586 else
1587 seconds = mktimegm(tm) + rtc_date_offset;
1589 return seconds - time(NULL);
1592 #ifdef _WIN32
1593 static void socket_cleanup(void)
1595 WSACleanup();
1598 static int socket_init(void)
1600 WSADATA Data;
1601 int ret, err;
1603 ret = WSAStartup(MAKEWORD(2,2), &Data);
1604 if (ret != 0) {
1605 err = WSAGetLastError();
1606 fprintf(stderr, "WSAStartup: %d\n", err);
1607 return -1;
1609 atexit(socket_cleanup);
1610 return 0;
1612 #endif
1614 /***********************************************************/
1615 /* Bluetooth support */
1616 static int nb_hcis;
1617 static int cur_hci;
1618 static struct HCIInfo *hci_table[MAX_NICS];
1620 static struct bt_vlan_s {
1621 struct bt_scatternet_s net;
1622 int id;
1623 struct bt_vlan_s *next;
1624 } *first_bt_vlan;
1626 /* find or alloc a new bluetooth "VLAN" */
1627 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1629 struct bt_vlan_s **pvlan, *vlan;
1630 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1631 if (vlan->id == id)
1632 return &vlan->net;
1634 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1635 vlan->id = id;
1636 pvlan = &first_bt_vlan;
1637 while (*pvlan != NULL)
1638 pvlan = &(*pvlan)->next;
1639 *pvlan = vlan;
1640 return &vlan->net;
1643 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1647 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1649 return -ENOTSUP;
1652 static struct HCIInfo null_hci = {
1653 .cmd_send = null_hci_send,
1654 .sco_send = null_hci_send,
1655 .acl_send = null_hci_send,
1656 .bdaddr_set = null_hci_addr_set,
1659 struct HCIInfo *qemu_next_hci(void)
1661 if (cur_hci == nb_hcis)
1662 return &null_hci;
1664 return hci_table[cur_hci++];
1667 static struct HCIInfo *hci_init(const char *str)
1669 char *endp;
1670 struct bt_scatternet_s *vlan = 0;
1672 if (!strcmp(str, "null"))
1673 /* null */
1674 return &null_hci;
1675 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1676 /* host[:hciN] */
1677 return bt_host_hci(str[4] ? str + 5 : "hci0");
1678 else if (!strncmp(str, "hci", 3)) {
1679 /* hci[,vlan=n] */
1680 if (str[3]) {
1681 if (!strncmp(str + 3, ",vlan=", 6)) {
1682 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1683 if (*endp)
1684 vlan = 0;
1686 } else
1687 vlan = qemu_find_bt_vlan(0);
1688 if (vlan)
1689 return bt_new_hci(vlan);
1692 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1694 return 0;
1697 static int bt_hci_parse(const char *str)
1699 struct HCIInfo *hci;
1700 bdaddr_t bdaddr;
1702 if (nb_hcis >= MAX_NICS) {
1703 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1704 return -1;
1707 hci = hci_init(str);
1708 if (!hci)
1709 return -1;
1711 bdaddr.b[0] = 0x52;
1712 bdaddr.b[1] = 0x54;
1713 bdaddr.b[2] = 0x00;
1714 bdaddr.b[3] = 0x12;
1715 bdaddr.b[4] = 0x34;
1716 bdaddr.b[5] = 0x56 + nb_hcis;
1717 hci->bdaddr_set(hci, bdaddr.b);
1719 hci_table[nb_hcis++] = hci;
1721 return 0;
1724 static void bt_vhci_add(int vlan_id)
1726 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1728 if (!vlan->slave)
1729 fprintf(stderr, "qemu: warning: adding a VHCI to "
1730 "an empty scatternet %i\n", vlan_id);
1732 bt_vhci_init(bt_new_hci(vlan));
1735 static struct bt_device_s *bt_device_add(const char *opt)
1737 struct bt_scatternet_s *vlan;
1738 int vlan_id = 0;
1739 char *endp = strstr(opt, ",vlan=");
1740 int len = (endp ? endp - opt : strlen(opt)) + 1;
1741 char devname[10];
1743 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1745 if (endp) {
1746 vlan_id = strtol(endp + 6, &endp, 0);
1747 if (*endp) {
1748 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1749 return 0;
1753 vlan = qemu_find_bt_vlan(vlan_id);
1755 if (!vlan->slave)
1756 fprintf(stderr, "qemu: warning: adding a slave device to "
1757 "an empty scatternet %i\n", vlan_id);
1759 if (!strcmp(devname, "keyboard"))
1760 return bt_keyboard_init(vlan);
1762 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1763 return 0;
1766 static int bt_parse(const char *opt)
1768 const char *endp, *p;
1769 int vlan;
1771 if (strstart(opt, "hci", &endp)) {
1772 if (!*endp || *endp == ',') {
1773 if (*endp)
1774 if (!strstart(endp, ",vlan=", 0))
1775 opt = endp + 1;
1777 return bt_hci_parse(opt);
1779 } else if (strstart(opt, "vhci", &endp)) {
1780 if (!*endp || *endp == ',') {
1781 if (*endp) {
1782 if (strstart(endp, ",vlan=", &p)) {
1783 vlan = strtol(p, (char **) &endp, 0);
1784 if (*endp) {
1785 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1786 return 1;
1788 } else {
1789 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1790 return 1;
1792 } else
1793 vlan = 0;
1795 bt_vhci_add(vlan);
1796 return 0;
1798 } else if (strstart(opt, "device:", &endp))
1799 return !bt_device_add(endp);
1801 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1802 return 1;
1805 /***********************************************************/
1806 /* QEMU Block devices */
1808 #define HD_ALIAS "index=%d,media=disk"
1809 #define CDROM_ALIAS "index=2,media=cdrom"
1810 #define FD_ALIAS "index=%d,if=floppy"
1811 #define PFLASH_ALIAS "if=pflash"
1812 #define MTD_ALIAS "if=mtd"
1813 #define SD_ALIAS "index=0,if=sd"
1815 static QemuOptsList drive_opt_list = {
1816 .name = "drive",
1817 .head = TAILQ_HEAD_INITIALIZER(drive_opt_list.head),
1818 .desc = {
1820 .name = "bus",
1821 .type = QEMU_OPT_NUMBER,
1822 .help = "bus number",
1824 .name = "unit",
1825 .type = QEMU_OPT_NUMBER,
1826 .help = "unit number (i.e. lun for scsi)",
1828 .name = "if",
1829 .type = QEMU_OPT_STRING,
1830 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
1832 .name = "index",
1833 .type = QEMU_OPT_NUMBER,
1835 .name = "cyls",
1836 .type = QEMU_OPT_NUMBER,
1837 .help = "number of cylinders (ide disk geometry)",
1839 .name = "heads",
1840 .type = QEMU_OPT_NUMBER,
1841 .help = "number of heads (ide disk geometry)",
1843 .name = "secs",
1844 .type = QEMU_OPT_NUMBER,
1845 .help = "number of sectors (ide disk geometry)",
1847 .name = "trans",
1848 .type = QEMU_OPT_STRING,
1849 .help = "chs translation (auto, lba. none)",
1851 .name = "media",
1852 .type = QEMU_OPT_STRING,
1853 .help = "media type (disk, cdrom)",
1855 .name = "snapshot",
1856 .type = QEMU_OPT_BOOL,
1858 .name = "file",
1859 .type = QEMU_OPT_STRING,
1860 .help = "disk image",
1862 .name = "cache",
1863 .type = QEMU_OPT_STRING,
1864 .help = "host cache usage (none, writeback, writethrough)",
1866 .name = "format",
1867 .type = QEMU_OPT_STRING,
1868 .help = "disk format (raw, qcow2, ...)",
1870 .name = "serial",
1871 .type = QEMU_OPT_STRING,
1873 .name = "werror",
1874 .type = QEMU_OPT_STRING,
1876 .name = "addr",
1877 .type = QEMU_OPT_STRING,
1878 .help = "pci address (virtio only)",
1880 .name = "boot",
1881 .type = QEMU_OPT_BOOL,
1882 .help = "make this a boot drive",
1884 { /* end if list */ }
1888 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1890 va_list ap;
1891 char optstr[1024];
1892 QemuOpts *opts;
1894 va_start(ap, fmt);
1895 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1896 va_end(ap);
1898 opts = qemu_opts_parse(&drive_opt_list, optstr, NULL);
1899 if (!opts) {
1900 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1901 __FUNCTION__, optstr);
1902 return NULL;
1904 if (file)
1905 qemu_opt_set(opts, "file", file);
1906 return opts;
1909 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1911 DriveInfo *dinfo;
1913 /* seek interface, bus and unit */
1915 TAILQ_FOREACH(dinfo, &drives, next) {
1916 if (dinfo->type == type &&
1917 dinfo->bus == bus &&
1918 dinfo->unit == unit)
1919 return dinfo;
1922 return NULL;
1925 DriveInfo *drive_get_by_id(char *id)
1927 DriveInfo *dinfo;
1929 TAILQ_FOREACH(dinfo, &drives, next) {
1930 if (strcmp(id, dinfo->id))
1931 continue;
1932 return dinfo;
1934 return NULL;
1937 int drive_get_max_bus(BlockInterfaceType type)
1939 int max_bus;
1940 DriveInfo *dinfo;
1942 max_bus = -1;
1943 TAILQ_FOREACH(dinfo, &drives, next) {
1944 if(dinfo->type == type &&
1945 dinfo->bus > max_bus)
1946 max_bus = dinfo->bus;
1948 return max_bus;
1951 const char *drive_get_serial(BlockDriverState *bdrv)
1953 DriveInfo *dinfo;
1955 TAILQ_FOREACH(dinfo, &drives, next) {
1956 if (dinfo->bdrv == bdrv)
1957 return dinfo->serial;
1960 return "\0";
1963 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1965 DriveInfo *dinfo;
1967 TAILQ_FOREACH(dinfo, &drives, next) {
1968 if (dinfo->bdrv == bdrv)
1969 return dinfo->onerror;
1972 return BLOCK_ERR_STOP_ENOSPC;
1975 static void bdrv_format_print(void *opaque, const char *name)
1977 fprintf(stderr, " %s", name);
1980 void drive_uninit(BlockDriverState *bdrv)
1982 DriveInfo *dinfo;
1984 TAILQ_FOREACH(dinfo, &drives, next) {
1985 if (dinfo->bdrv != bdrv)
1986 continue;
1987 qemu_opts_del(dinfo->opts);
1988 TAILQ_REMOVE(&drives, dinfo, next);
1989 qemu_free(dinfo);
1990 break;
1994 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1995 int *fatal_error)
1997 const char *buf;
1998 const char *file = NULL;
1999 char devname[128];
2000 const char *serial;
2001 const char *mediastr = "";
2002 BlockInterfaceType type;
2003 enum { MEDIA_DISK, MEDIA_CDROM } media;
2004 int bus_id, unit_id;
2005 int cyls, heads, secs, translation;
2006 BlockDriver *drv = NULL;
2007 QEMUMachine *machine = opaque;
2008 int max_devs;
2009 int index;
2010 int cache;
2011 int bdrv_flags, onerror;
2012 const char *devaddr;
2013 DriveInfo *dinfo;
2014 int is_extboot = 0;
2015 int snapshot = 0;
2017 *fatal_error = 1;
2019 translation = BIOS_ATA_TRANSLATION_AUTO;
2020 cache = 1;
2022 if (machine->use_scsi) {
2023 type = IF_SCSI;
2024 max_devs = MAX_SCSI_DEVS;
2025 pstrcpy(devname, sizeof(devname), "scsi");
2026 } else {
2027 type = IF_IDE;
2028 max_devs = MAX_IDE_DEVS;
2029 pstrcpy(devname, sizeof(devname), "ide");
2031 media = MEDIA_DISK;
2033 /* extract parameters */
2034 bus_id = qemu_opt_get_number(opts, "bus", 0);
2035 unit_id = qemu_opt_get_number(opts, "unit", -1);
2036 index = qemu_opt_get_number(opts, "index", -1);
2038 cyls = qemu_opt_get_number(opts, "cyls", 0);
2039 heads = qemu_opt_get_number(opts, "heads", 0);
2040 secs = qemu_opt_get_number(opts, "secs", 0);
2042 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2044 file = qemu_opt_get(opts, "file");
2045 serial = qemu_opt_get(opts, "serial");
2047 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2048 pstrcpy(devname, sizeof(devname), buf);
2049 if (!strcmp(buf, "ide")) {
2050 type = IF_IDE;
2051 max_devs = MAX_IDE_DEVS;
2052 } else if (!strcmp(buf, "scsi")) {
2053 type = IF_SCSI;
2054 max_devs = MAX_SCSI_DEVS;
2055 } else if (!strcmp(buf, "floppy")) {
2056 type = IF_FLOPPY;
2057 max_devs = 0;
2058 } else if (!strcmp(buf, "pflash")) {
2059 type = IF_PFLASH;
2060 max_devs = 0;
2061 } else if (!strcmp(buf, "mtd")) {
2062 type = IF_MTD;
2063 max_devs = 0;
2064 } else if (!strcmp(buf, "sd")) {
2065 type = IF_SD;
2066 max_devs = 0;
2067 } else if (!strcmp(buf, "virtio")) {
2068 type = IF_VIRTIO;
2069 max_devs = 0;
2070 } else if (!strcmp(buf, "xen")) {
2071 type = IF_XEN;
2072 max_devs = 0;
2073 } else {
2074 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2075 return NULL;
2079 if (cyls || heads || secs) {
2080 if (cyls < 1 || cyls > 16383) {
2081 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2082 return NULL;
2084 if (heads < 1 || heads > 16) {
2085 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2086 return NULL;
2088 if (secs < 1 || secs > 63) {
2089 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2090 return NULL;
2094 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2095 if (!cyls) {
2096 fprintf(stderr,
2097 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2098 buf);
2099 return NULL;
2101 if (!strcmp(buf, "none"))
2102 translation = BIOS_ATA_TRANSLATION_NONE;
2103 else if (!strcmp(buf, "lba"))
2104 translation = BIOS_ATA_TRANSLATION_LBA;
2105 else if (!strcmp(buf, "auto"))
2106 translation = BIOS_ATA_TRANSLATION_AUTO;
2107 else {
2108 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2109 return NULL;
2113 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2114 if (!strcmp(buf, "disk")) {
2115 media = MEDIA_DISK;
2116 } else if (!strcmp(buf, "cdrom")) {
2117 if (cyls || secs || heads) {
2118 fprintf(stderr,
2119 "qemu: '%s' invalid physical CHS format\n", buf);
2120 return NULL;
2122 media = MEDIA_CDROM;
2123 } else {
2124 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2125 return NULL;
2129 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2130 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2131 cache = 0;
2132 else if (!strcmp(buf, "writethrough"))
2133 cache = 1;
2134 else if (!strcmp(buf, "writeback"))
2135 cache = 2;
2136 else {
2137 fprintf(stderr, "qemu: invalid cache option\n");
2138 return NULL;
2142 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2143 if (strcmp(buf, "?") == 0) {
2144 fprintf(stderr, "qemu: Supported formats:");
2145 bdrv_iterate_format(bdrv_format_print, NULL);
2146 fprintf(stderr, "\n");
2147 return NULL;
2149 drv = bdrv_find_format(buf);
2150 if (!drv) {
2151 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2152 return NULL;
2156 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
2157 if (is_extboot && extboot_drive) {
2158 fprintf(stderr, "qemu: two bootable drives specified\n");
2159 return NULL;
2162 onerror = BLOCK_ERR_STOP_ENOSPC;
2163 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2164 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2165 fprintf(stderr, "werror is no supported by this format\n");
2166 return NULL;
2168 if (!strcmp(buf, "ignore"))
2169 onerror = BLOCK_ERR_IGNORE;
2170 else if (!strcmp(buf, "enospc"))
2171 onerror = BLOCK_ERR_STOP_ENOSPC;
2172 else if (!strcmp(buf, "stop"))
2173 onerror = BLOCK_ERR_STOP_ANY;
2174 else if (!strcmp(buf, "report"))
2175 onerror = BLOCK_ERR_REPORT;
2176 else {
2177 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2178 return NULL;
2182 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2183 if (type != IF_VIRTIO) {
2184 fprintf(stderr, "addr is not supported\n");
2185 return NULL;
2189 /* compute bus and unit according index */
2191 if (index != -1) {
2192 if (bus_id != 0 || unit_id != -1) {
2193 fprintf(stderr,
2194 "qemu: index cannot be used with bus and unit\n");
2195 return NULL;
2197 if (max_devs == 0)
2199 unit_id = index;
2200 bus_id = 0;
2201 } else {
2202 unit_id = index % max_devs;
2203 bus_id = index / max_devs;
2207 /* if user doesn't specify a unit_id,
2208 * try to find the first free
2211 if (unit_id == -1) {
2212 unit_id = 0;
2213 while (drive_get(type, bus_id, unit_id) != NULL) {
2214 unit_id++;
2215 if (max_devs && unit_id >= max_devs) {
2216 unit_id -= max_devs;
2217 bus_id++;
2222 /* check unit id */
2224 if (max_devs && unit_id >= max_devs) {
2225 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2226 unit_id, max_devs - 1);
2227 return NULL;
2231 * ignore multiple definitions
2234 if (drive_get(type, bus_id, unit_id) != NULL) {
2235 *fatal_error = 0;
2236 return NULL;
2239 /* init */
2241 dinfo = qemu_mallocz(sizeof(*dinfo));
2242 if ((buf = qemu_opt_get(opts, "id")) != NULL) {
2243 dinfo->id = qemu_strdup(buf);
2244 } else {
2245 /* no id supplied -> create one */
2246 dinfo->id = qemu_mallocz(32);
2247 if (type == IF_IDE || type == IF_SCSI)
2248 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2249 if (max_devs)
2250 snprintf(dinfo->id, 32, "%s%i%s%i",
2251 devname, bus_id, mediastr, unit_id);
2252 else
2253 snprintf(dinfo->id, 32, "%s%s%i",
2254 devname, mediastr, unit_id);
2256 dinfo->bdrv = bdrv_new(dinfo->id);
2257 dinfo->devaddr = devaddr;
2258 dinfo->type = type;
2259 dinfo->bus = bus_id;
2260 dinfo->unit = unit_id;
2261 dinfo->onerror = onerror;
2262 dinfo->opts = opts;
2263 if (serial)
2264 strncpy(dinfo->serial, serial, sizeof(serial));
2265 TAILQ_INSERT_TAIL(&drives, dinfo, next);
2266 if (is_extboot) {
2267 extboot_drive = dinfo;
2270 switch(type) {
2271 case IF_IDE:
2272 case IF_SCSI:
2273 case IF_XEN:
2274 switch(media) {
2275 case MEDIA_DISK:
2276 if (cyls != 0) {
2277 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2278 bdrv_set_translation_hint(dinfo->bdrv, translation);
2280 break;
2281 case MEDIA_CDROM:
2282 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2283 break;
2285 break;
2286 case IF_SD:
2287 /* FIXME: This isn't really a floppy, but it's a reasonable
2288 approximation. */
2289 case IF_FLOPPY:
2290 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2291 break;
2292 case IF_PFLASH:
2293 case IF_MTD:
2294 case IF_VIRTIO:
2295 break;
2296 case IF_COUNT:
2297 abort();
2299 if (!file) {
2300 *fatal_error = 0;
2301 return NULL;
2303 bdrv_flags = 0;
2304 if (snapshot) {
2305 bdrv_flags |= BDRV_O_SNAPSHOT;
2306 cache = 2; /* always use write-back with snapshot */
2308 if (cache == 0) /* no caching */
2309 bdrv_flags |= BDRV_O_NOCACHE;
2310 else if (cache == 2) /* write-back */
2311 bdrv_flags |= BDRV_O_CACHE_WB;
2312 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2313 fprintf(stderr, "qemu: could not open disk image %s\n",
2314 file);
2315 return NULL;
2317 if (bdrv_key_required(dinfo->bdrv))
2318 autostart = 0;
2319 *fatal_error = 0;
2320 return dinfo;
2323 static int drive_init_func(QemuOpts *opts, void *opaque)
2325 QEMUMachine *machine = opaque;
2326 int fatal_error = 0;
2328 if (drive_init(opts, machine, &fatal_error) == NULL) {
2329 if (fatal_error)
2330 return 1;
2332 return 0;
2335 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2337 if (NULL == qemu_opt_get(opts, "snapshot")) {
2338 qemu_opt_set(opts, "snapshot", "on");
2340 return 0;
2343 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2345 boot_set_handler = func;
2346 boot_set_opaque = opaque;
2349 int qemu_boot_set(const char *boot_devices)
2351 if (!boot_set_handler) {
2352 return -EINVAL;
2354 return boot_set_handler(boot_set_opaque, boot_devices);
2357 static int parse_bootdevices(char *devices)
2359 /* We just do some generic consistency checks */
2360 const char *p;
2361 int bitmap = 0;
2363 for (p = devices; *p != '\0'; p++) {
2364 /* Allowed boot devices are:
2365 * a-b: floppy disk drives
2366 * c-f: IDE disk drives
2367 * g-m: machine implementation dependant drives
2368 * n-p: network devices
2369 * It's up to each machine implementation to check if the given boot
2370 * devices match the actual hardware implementation and firmware
2371 * features.
2373 if (*p < 'a' || *p > 'p') {
2374 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2375 exit(1);
2377 if (bitmap & (1 << (*p - 'a'))) {
2378 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2379 exit(1);
2381 bitmap |= 1 << (*p - 'a');
2383 return bitmap;
2386 static void restore_boot_devices(void *opaque)
2388 char *standard_boot_devices = opaque;
2390 qemu_boot_set(standard_boot_devices);
2392 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2393 qemu_free(standard_boot_devices);
2396 static void numa_add(const char *optarg)
2398 char option[128];
2399 char *endptr;
2400 unsigned long long value, endvalue;
2401 int nodenr;
2403 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2404 if (!strcmp(option, "node")) {
2405 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2406 nodenr = nb_numa_nodes;
2407 } else {
2408 nodenr = strtoull(option, NULL, 10);
2411 if (get_param_value(option, 128, "mem", optarg) == 0) {
2412 node_mem[nodenr] = 0;
2413 } else {
2414 value = strtoull(option, &endptr, 0);
2415 switch (*endptr) {
2416 case 0: case 'M': case 'm':
2417 value <<= 20;
2418 break;
2419 case 'G': case 'g':
2420 value <<= 30;
2421 break;
2423 node_mem[nodenr] = value;
2425 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2426 node_cpumask[nodenr] = 0;
2427 } else {
2428 value = strtoull(option, &endptr, 10);
2429 if (value >= 64) {
2430 value = 63;
2431 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2432 } else {
2433 if (*endptr == '-') {
2434 endvalue = strtoull(endptr+1, &endptr, 10);
2435 if (endvalue >= 63) {
2436 endvalue = 62;
2437 fprintf(stderr,
2438 "only 63 CPUs in NUMA mode supported.\n");
2440 value = (1 << (endvalue + 1)) - (1 << value);
2441 } else {
2442 value = 1 << value;
2445 node_cpumask[nodenr] = value;
2447 nb_numa_nodes++;
2449 return;
2452 /***********************************************************/
2453 /* USB devices */
2455 static USBPort *used_usb_ports;
2456 static USBPort *free_usb_ports;
2458 /* ??? Maybe change this to register a hub to keep track of the topology. */
2459 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2460 usb_attachfn attach)
2462 port->opaque = opaque;
2463 port->index = index;
2464 port->attach = attach;
2465 port->next = free_usb_ports;
2466 free_usb_ports = port;
2469 int usb_device_add_dev(USBDevice *dev)
2471 USBPort *port;
2473 /* Find a USB port to add the device to. */
2474 port = free_usb_ports;
2475 if (!port->next) {
2476 USBDevice *hub;
2478 /* Create a new hub and chain it on. */
2479 free_usb_ports = NULL;
2480 port->next = used_usb_ports;
2481 used_usb_ports = port;
2483 hub = usb_hub_init(VM_USB_HUB_SIZE);
2484 usb_attach(port, hub);
2485 port = free_usb_ports;
2488 free_usb_ports = port->next;
2489 port->next = used_usb_ports;
2490 used_usb_ports = port;
2491 usb_attach(port, dev);
2492 return 0;
2495 static void usb_msd_password_cb(void *opaque, int err)
2497 USBDevice *dev = opaque;
2499 if (!err)
2500 usb_device_add_dev(dev);
2501 else
2502 dev->handle_destroy(dev);
2505 static int usb_device_add(const char *devname, int is_hotplug)
2507 const char *p;
2508 USBDevice *dev;
2510 if (!free_usb_ports)
2511 return -1;
2513 if (strstart(devname, "host:", &p)) {
2514 dev = usb_host_device_open(p);
2515 } else if (!strcmp(devname, "mouse")) {
2516 dev = usb_mouse_init();
2517 } else if (!strcmp(devname, "tablet")) {
2518 dev = usb_tablet_init();
2519 } else if (!strcmp(devname, "keyboard")) {
2520 dev = usb_keyboard_init();
2521 } else if (strstart(devname, "disk:", &p)) {
2522 BlockDriverState *bs;
2524 dev = usb_msd_init(p);
2525 if (!dev)
2526 return -1;
2527 bs = usb_msd_get_bdrv(dev);
2528 if (bdrv_key_required(bs)) {
2529 autostart = 0;
2530 if (is_hotplug) {
2531 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2532 dev);
2533 return 0;
2536 } else if (!strcmp(devname, "wacom-tablet")) {
2537 dev = usb_wacom_init();
2538 } else if (strstart(devname, "serial:", &p)) {
2539 dev = usb_serial_init(p);
2540 #ifdef CONFIG_BRLAPI
2541 } else if (!strcmp(devname, "braille")) {
2542 dev = usb_baum_init();
2543 #endif
2544 } else if (strstart(devname, "net:", &p)) {
2545 int nic = nb_nics;
2547 if (net_client_init(NULL, "nic", p) < 0)
2548 return -1;
2549 nd_table[nic].model = "usb";
2550 dev = usb_net_init(&nd_table[nic]);
2551 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2552 dev = usb_bt_init(devname[2] ? hci_init(p) :
2553 bt_new_hci(qemu_find_bt_vlan(0)));
2554 } else {
2555 return -1;
2557 if (!dev)
2558 return -1;
2560 return usb_device_add_dev(dev);
2563 int usb_device_del_addr(int bus_num, int addr)
2565 USBPort *port;
2566 USBPort **lastp;
2567 USBDevice *dev;
2569 if (!used_usb_ports)
2570 return -1;
2572 if (bus_num != 0)
2573 return -1;
2575 lastp = &used_usb_ports;
2576 port = used_usb_ports;
2577 while (port && port->dev->addr != addr) {
2578 lastp = &port->next;
2579 port = port->next;
2582 if (!port)
2583 return -1;
2585 dev = port->dev;
2586 *lastp = port->next;
2587 usb_attach(port, NULL);
2588 dev->handle_destroy(dev);
2589 port->next = free_usb_ports;
2590 free_usb_ports = port;
2591 return 0;
2594 static int usb_device_del(const char *devname)
2596 int bus_num, addr;
2597 const char *p;
2599 if (strstart(devname, "host:", &p))
2600 return usb_host_device_close(p);
2602 if (!used_usb_ports)
2603 return -1;
2605 p = strchr(devname, '.');
2606 if (!p)
2607 return -1;
2608 bus_num = strtoul(devname, NULL, 0);
2609 addr = strtoul(p + 1, NULL, 0);
2611 return usb_device_del_addr(bus_num, addr);
2614 static int usb_parse(const char *cmdline)
2616 return usb_device_add(cmdline, 0);
2619 void do_usb_add(Monitor *mon, const char *devname)
2621 usb_device_add(devname, 1);
2624 void do_usb_del(Monitor *mon, const char *devname)
2626 usb_device_del(devname);
2629 void usb_info(Monitor *mon)
2631 USBDevice *dev;
2632 USBPort *port;
2633 const char *speed_str;
2635 if (!usb_enabled) {
2636 monitor_printf(mon, "USB support not enabled\n");
2637 return;
2640 for (port = used_usb_ports; port; port = port->next) {
2641 dev = port->dev;
2642 if (!dev)
2643 continue;
2644 switch(dev->speed) {
2645 case USB_SPEED_LOW:
2646 speed_str = "1.5";
2647 break;
2648 case USB_SPEED_FULL:
2649 speed_str = "12";
2650 break;
2651 case USB_SPEED_HIGH:
2652 speed_str = "480";
2653 break;
2654 default:
2655 speed_str = "?";
2656 break;
2658 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2659 0, dev->addr, speed_str, dev->devname);
2663 /***********************************************************/
2664 /* PCMCIA/Cardbus */
2666 static struct pcmcia_socket_entry_s {
2667 PCMCIASocket *socket;
2668 struct pcmcia_socket_entry_s *next;
2669 } *pcmcia_sockets = 0;
2671 void pcmcia_socket_register(PCMCIASocket *socket)
2673 struct pcmcia_socket_entry_s *entry;
2675 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2676 entry->socket = socket;
2677 entry->next = pcmcia_sockets;
2678 pcmcia_sockets = entry;
2681 void pcmcia_socket_unregister(PCMCIASocket *socket)
2683 struct pcmcia_socket_entry_s *entry, **ptr;
2685 ptr = &pcmcia_sockets;
2686 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2687 if (entry->socket == socket) {
2688 *ptr = entry->next;
2689 qemu_free(entry);
2693 void pcmcia_info(Monitor *mon)
2695 struct pcmcia_socket_entry_s *iter;
2697 if (!pcmcia_sockets)
2698 monitor_printf(mon, "No PCMCIA sockets\n");
2700 for (iter = pcmcia_sockets; iter; iter = iter->next)
2701 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2702 iter->socket->attached ? iter->socket->card_string :
2703 "Empty");
2706 /***********************************************************/
2707 /* register display */
2709 struct DisplayAllocator default_allocator = {
2710 defaultallocator_create_displaysurface,
2711 defaultallocator_resize_displaysurface,
2712 defaultallocator_free_displaysurface
2715 void register_displaystate(DisplayState *ds)
2717 DisplayState **s;
2718 s = &display_state;
2719 while (*s != NULL)
2720 s = &(*s)->next;
2721 ds->next = NULL;
2722 *s = ds;
2725 DisplayState *get_displaystate(void)
2727 return display_state;
2730 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2732 if(ds->allocator == &default_allocator) ds->allocator = da;
2733 return ds->allocator;
2736 /* dumb display */
2738 static void dumb_display_init(void)
2740 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2741 ds->allocator = &default_allocator;
2742 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2743 register_displaystate(ds);
2746 /***********************************************************/
2747 /* I/O handling */
2749 typedef struct IOHandlerRecord {
2750 int fd;
2751 IOCanRWHandler *fd_read_poll;
2752 IOHandler *fd_read;
2753 IOHandler *fd_write;
2754 int deleted;
2755 void *opaque;
2756 /* temporary data */
2757 struct pollfd *ufd;
2758 struct IOHandlerRecord *next;
2759 } IOHandlerRecord;
2761 static IOHandlerRecord *first_io_handler;
2763 /* XXX: fd_read_poll should be suppressed, but an API change is
2764 necessary in the character devices to suppress fd_can_read(). */
2765 int qemu_set_fd_handler2(int fd,
2766 IOCanRWHandler *fd_read_poll,
2767 IOHandler *fd_read,
2768 IOHandler *fd_write,
2769 void *opaque)
2771 IOHandlerRecord **pioh, *ioh;
2773 if (!fd_read && !fd_write) {
2774 pioh = &first_io_handler;
2775 for(;;) {
2776 ioh = *pioh;
2777 if (ioh == NULL)
2778 break;
2779 if (ioh->fd == fd) {
2780 ioh->deleted = 1;
2781 break;
2783 pioh = &ioh->next;
2785 } else {
2786 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2787 if (ioh->fd == fd)
2788 goto found;
2790 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2791 ioh->next = first_io_handler;
2792 first_io_handler = ioh;
2793 found:
2794 ioh->fd = fd;
2795 ioh->fd_read_poll = fd_read_poll;
2796 ioh->fd_read = fd_read;
2797 ioh->fd_write = fd_write;
2798 ioh->opaque = opaque;
2799 ioh->deleted = 0;
2801 qemu_notify_event();
2802 return 0;
2805 int qemu_set_fd_handler(int fd,
2806 IOHandler *fd_read,
2807 IOHandler *fd_write,
2808 void *opaque)
2810 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2813 #ifdef _WIN32
2814 /***********************************************************/
2815 /* Polling handling */
2817 typedef struct PollingEntry {
2818 PollingFunc *func;
2819 void *opaque;
2820 struct PollingEntry *next;
2821 } PollingEntry;
2823 static PollingEntry *first_polling_entry;
2825 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2827 PollingEntry **ppe, *pe;
2828 pe = qemu_mallocz(sizeof(PollingEntry));
2829 pe->func = func;
2830 pe->opaque = opaque;
2831 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2832 *ppe = pe;
2833 return 0;
2836 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2838 PollingEntry **ppe, *pe;
2839 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2840 pe = *ppe;
2841 if (pe->func == func && pe->opaque == opaque) {
2842 *ppe = pe->next;
2843 qemu_free(pe);
2844 break;
2849 /***********************************************************/
2850 /* Wait objects support */
2851 typedef struct WaitObjects {
2852 int num;
2853 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2854 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2855 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2856 } WaitObjects;
2858 static WaitObjects wait_objects = {0};
2860 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2862 WaitObjects *w = &wait_objects;
2864 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2865 return -1;
2866 w->events[w->num] = handle;
2867 w->func[w->num] = func;
2868 w->opaque[w->num] = opaque;
2869 w->num++;
2870 return 0;
2873 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2875 int i, found;
2876 WaitObjects *w = &wait_objects;
2878 found = 0;
2879 for (i = 0; i < w->num; i++) {
2880 if (w->events[i] == handle)
2881 found = 1;
2882 if (found) {
2883 w->events[i] = w->events[i + 1];
2884 w->func[i] = w->func[i + 1];
2885 w->opaque[i] = w->opaque[i + 1];
2888 if (found)
2889 w->num--;
2891 #endif
2893 /***********************************************************/
2894 /* ram save/restore */
2896 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2898 int v;
2900 v = qemu_get_byte(f);
2901 switch(v) {
2902 case 0:
2903 if (qemu_get_buffer(f, buf, len) != len)
2904 return -EIO;
2905 break;
2906 case 1:
2907 v = qemu_get_byte(f);
2908 memset(buf, v, len);
2909 break;
2910 default:
2911 return -EINVAL;
2914 if (qemu_file_has_error(f))
2915 return -EIO;
2917 return 0;
2920 static int ram_load_v1(QEMUFile *f, void *opaque)
2922 int ret;
2923 ram_addr_t i;
2925 if (qemu_get_be32(f) != last_ram_offset)
2926 return -EINVAL;
2927 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2928 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
2929 continue;
2930 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2931 if (ret)
2932 return ret;
2934 return 0;
2937 #define BDRV_HASH_BLOCK_SIZE 1024
2938 #define IOBUF_SIZE 4096
2939 #define RAM_CBLOCK_MAGIC 0xfabe
2941 typedef struct RamDecompressState {
2942 z_stream zstream;
2943 QEMUFile *f;
2944 uint8_t buf[IOBUF_SIZE];
2945 } RamDecompressState;
2947 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2949 int ret;
2950 memset(s, 0, sizeof(*s));
2951 s->f = f;
2952 ret = inflateInit(&s->zstream);
2953 if (ret != Z_OK)
2954 return -1;
2955 return 0;
2958 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2960 int ret, clen;
2962 s->zstream.avail_out = len;
2963 s->zstream.next_out = buf;
2964 while (s->zstream.avail_out > 0) {
2965 if (s->zstream.avail_in == 0) {
2966 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2967 return -1;
2968 clen = qemu_get_be16(s->f);
2969 if (clen > IOBUF_SIZE)
2970 return -1;
2971 qemu_get_buffer(s->f, s->buf, clen);
2972 s->zstream.avail_in = clen;
2973 s->zstream.next_in = s->buf;
2975 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2976 if (ret != Z_OK && ret != Z_STREAM_END) {
2977 return -1;
2980 return 0;
2983 static void ram_decompress_close(RamDecompressState *s)
2985 inflateEnd(&s->zstream);
2988 #define RAM_SAVE_FLAG_FULL 0x01
2989 #define RAM_SAVE_FLAG_COMPRESS 0x02
2990 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2991 #define RAM_SAVE_FLAG_PAGE 0x08
2992 #define RAM_SAVE_FLAG_EOS 0x10
2994 static int is_dup_page(uint8_t *page, uint8_t ch)
2996 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2997 uint32_t *array = (uint32_t *)page;
2998 int i;
3000 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3001 if (array[i] != val)
3002 return 0;
3005 return 1;
3008 static int ram_save_block(QEMUFile *f)
3010 static ram_addr_t current_addr = 0;
3011 ram_addr_t saved_addr = current_addr;
3012 ram_addr_t addr = 0;
3013 int found = 0;
3015 while (addr < last_ram_offset) {
3016 if (kvm_enabled() && current_addr == 0) {
3017 int r;
3018 r = kvm_update_dirty_pages_log();
3019 if (r) {
3020 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3021 qemu_file_set_error(f);
3022 return 0;
3025 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3026 uint8_t *p;
3028 cpu_physical_memory_reset_dirty(current_addr,
3029 current_addr + TARGET_PAGE_SIZE,
3030 MIGRATION_DIRTY_FLAG);
3032 p = qemu_get_ram_ptr(current_addr);
3034 if (is_dup_page(p, *p)) {
3035 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3036 qemu_put_byte(f, *p);
3037 } else {
3038 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3039 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3042 found = 1;
3043 break;
3045 addr += TARGET_PAGE_SIZE;
3046 current_addr = (saved_addr + addr) % last_ram_offset;
3049 return found;
3052 static uint64_t bytes_transferred = 0;
3054 static ram_addr_t ram_save_remaining(void)
3056 ram_addr_t addr;
3057 ram_addr_t count = 0;
3059 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3060 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3061 count++;
3064 return count;
3067 uint64_t ram_bytes_remaining(void)
3069 return ram_save_remaining() * TARGET_PAGE_SIZE;
3072 uint64_t ram_bytes_transferred(void)
3074 return bytes_transferred;
3077 uint64_t ram_bytes_total(void)
3079 return last_ram_offset;
3082 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3084 ram_addr_t addr;
3085 uint64_t bytes_transferred_last;
3086 double bwidth = 0;
3087 uint64_t expected_time = 0;
3089 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3090 qemu_file_set_error(f);
3091 return 0;
3094 if (stage == 1) {
3095 /* Make sure all dirty bits are set */
3096 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3097 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3098 cpu_physical_memory_set_dirty(addr);
3101 /* Enable dirty memory tracking */
3102 cpu_physical_memory_set_dirty_tracking(1);
3104 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3107 bytes_transferred_last = bytes_transferred;
3108 bwidth = get_clock();
3110 while (!qemu_file_rate_limit(f)) {
3111 int ret;
3113 ret = ram_save_block(f);
3114 bytes_transferred += ret * TARGET_PAGE_SIZE;
3115 if (ret == 0) /* no more blocks */
3116 break;
3119 bwidth = get_clock() - bwidth;
3120 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3122 /* if we haven't transferred anything this round, force expected_time to a
3123 * a very high value, but without crashing */
3124 if (bwidth == 0)
3125 bwidth = 0.000001;
3127 /* try transferring iterative blocks of memory */
3129 if (stage == 3) {
3131 /* flush all remaining blocks regardless of rate limiting */
3132 while (ram_save_block(f) != 0) {
3133 bytes_transferred += TARGET_PAGE_SIZE;
3135 cpu_physical_memory_set_dirty_tracking(0);
3138 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3140 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3142 return (stage == 2) && (expected_time <= migrate_max_downtime());
3145 static int ram_load_dead(QEMUFile *f, void *opaque)
3147 RamDecompressState s1, *s = &s1;
3148 uint8_t buf[10];
3149 ram_addr_t i;
3151 if (ram_decompress_open(s, f) < 0)
3152 return -EINVAL;
3153 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3154 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3155 continue;
3156 if (ram_decompress_buf(s, buf, 1) < 0) {
3157 fprintf(stderr, "Error while reading ram block header\n");
3158 goto error;
3160 if (buf[0] == 0) {
3161 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3162 BDRV_HASH_BLOCK_SIZE) < 0) {
3163 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3164 goto error;
3166 } else {
3167 error:
3168 printf("Error block header\n");
3169 return -EINVAL;
3172 ram_decompress_close(s);
3174 return 0;
3177 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3179 ram_addr_t addr;
3180 int flags;
3182 if (version_id == 1)
3183 return ram_load_v1(f, opaque);
3185 if (version_id == 2) {
3186 if (qemu_get_be32(f) != last_ram_offset)
3187 return -EINVAL;
3188 return ram_load_dead(f, opaque);
3191 if (version_id != 3)
3192 return -EINVAL;
3194 do {
3195 addr = qemu_get_be64(f);
3197 flags = addr & ~TARGET_PAGE_MASK;
3198 addr &= TARGET_PAGE_MASK;
3200 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3201 if (addr != last_ram_offset)
3202 return -EINVAL;
3205 if (flags & RAM_SAVE_FLAG_FULL) {
3206 if (ram_load_dead(f, opaque) < 0)
3207 return -EINVAL;
3210 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3211 uint8_t ch = qemu_get_byte(f);
3212 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3213 #ifndef _WIN32
3214 if (ch == 0 &&
3215 (!kvm_enabled() || kvm_has_sync_mmu())) {
3216 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3218 #endif
3219 } else if (flags & RAM_SAVE_FLAG_PAGE)
3220 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3221 } while (!(flags & RAM_SAVE_FLAG_EOS));
3223 return 0;
3226 void qemu_service_io(void)
3228 qemu_notify_event();
3231 /***********************************************************/
3232 /* bottom halves (can be seen as timers which expire ASAP) */
3234 struct QEMUBH {
3235 QEMUBHFunc *cb;
3236 void *opaque;
3237 int scheduled;
3238 int idle;
3239 int deleted;
3240 QEMUBH *next;
3243 static QEMUBH *first_bh = NULL;
3245 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3247 QEMUBH *bh;
3248 bh = qemu_mallocz(sizeof(QEMUBH));
3249 bh->cb = cb;
3250 bh->opaque = opaque;
3251 bh->next = first_bh;
3252 first_bh = bh;
3253 return bh;
3256 int qemu_bh_poll(void)
3258 QEMUBH *bh, **bhp;
3259 int ret;
3261 ret = 0;
3262 for (bh = first_bh; bh; bh = bh->next) {
3263 if (!bh->deleted && bh->scheduled) {
3264 bh->scheduled = 0;
3265 if (!bh->idle)
3266 ret = 1;
3267 bh->idle = 0;
3268 bh->cb(bh->opaque);
3272 /* remove deleted bhs */
3273 bhp = &first_bh;
3274 while (*bhp) {
3275 bh = *bhp;
3276 if (bh->deleted) {
3277 *bhp = bh->next;
3278 qemu_free(bh);
3279 } else
3280 bhp = &bh->next;
3283 return ret;
3286 void qemu_bh_schedule_idle(QEMUBH *bh)
3288 if (bh->scheduled)
3289 return;
3290 bh->scheduled = 1;
3291 bh->idle = 1;
3294 void qemu_bh_schedule(QEMUBH *bh)
3296 if (bh->scheduled)
3297 return;
3298 bh->scheduled = 1;
3299 bh->idle = 0;
3300 /* stop the currently executing CPU to execute the BH ASAP */
3301 qemu_notify_event();
3304 void qemu_bh_cancel(QEMUBH *bh)
3306 bh->scheduled = 0;
3309 void qemu_bh_delete(QEMUBH *bh)
3311 bh->scheduled = 0;
3312 bh->deleted = 1;
3315 static void qemu_bh_update_timeout(int *timeout)
3317 QEMUBH *bh;
3319 for (bh = first_bh; bh; bh = bh->next) {
3320 if (!bh->deleted && bh->scheduled) {
3321 if (bh->idle) {
3322 /* idle bottom halves will be polled at least
3323 * every 10ms */
3324 *timeout = MIN(10, *timeout);
3325 } else {
3326 /* non-idle bottom halves will be executed
3327 * immediately */
3328 *timeout = 0;
3329 break;
3335 /***********************************************************/
3336 /* machine registration */
3338 static QEMUMachine *first_machine = NULL;
3339 QEMUMachine *current_machine = NULL;
3341 int qemu_register_machine(QEMUMachine *m)
3343 QEMUMachine **pm;
3344 pm = &first_machine;
3345 while (*pm != NULL)
3346 pm = &(*pm)->next;
3347 m->next = NULL;
3348 *pm = m;
3349 return 0;
3352 static QEMUMachine *find_machine(const char *name)
3354 QEMUMachine *m;
3356 for(m = first_machine; m != NULL; m = m->next) {
3357 if (!strcmp(m->name, name))
3358 return m;
3359 if (m->alias && !strcmp(m->alias, name))
3360 return m;
3362 return NULL;
3365 static QEMUMachine *find_default_machine(void)
3367 QEMUMachine *m;
3369 for(m = first_machine; m != NULL; m = m->next) {
3370 if (m->is_default) {
3371 return m;
3374 return NULL;
3377 /***********************************************************/
3378 /* main execution loop */
3380 static void gui_update(void *opaque)
3382 uint64_t interval = GUI_REFRESH_INTERVAL;
3383 DisplayState *ds = opaque;
3384 DisplayChangeListener *dcl = ds->listeners;
3386 dpy_refresh(ds);
3388 while (dcl != NULL) {
3389 if (dcl->gui_timer_interval &&
3390 dcl->gui_timer_interval < interval)
3391 interval = dcl->gui_timer_interval;
3392 dcl = dcl->next;
3394 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3397 static void nographic_update(void *opaque)
3399 uint64_t interval = GUI_REFRESH_INTERVAL;
3401 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3404 struct vm_change_state_entry {
3405 VMChangeStateHandler *cb;
3406 void *opaque;
3407 LIST_ENTRY (vm_change_state_entry) entries;
3410 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3412 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3413 void *opaque)
3415 VMChangeStateEntry *e;
3417 e = qemu_mallocz(sizeof (*e));
3419 e->cb = cb;
3420 e->opaque = opaque;
3421 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3422 return e;
3425 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3427 LIST_REMOVE (e, entries);
3428 qemu_free (e);
3431 static void vm_state_notify(int running, int reason)
3433 VMChangeStateEntry *e;
3435 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3436 e->cb(e->opaque, running, reason);
3440 static void resume_all_vcpus(void);
3441 static void pause_all_vcpus(void);
3443 void vm_start(void)
3445 if (!vm_running) {
3446 cpu_enable_ticks();
3447 vm_running = 1;
3448 vm_state_notify(1, 0);
3449 qemu_rearm_alarm_timer(alarm_timer);
3450 resume_all_vcpus();
3454 /* reset/shutdown handler */
3456 typedef struct QEMUResetEntry {
3457 TAILQ_ENTRY(QEMUResetEntry) entry;
3458 QEMUResetHandler *func;
3459 void *opaque;
3460 } QEMUResetEntry;
3462 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3463 TAILQ_HEAD_INITIALIZER(reset_handlers);
3464 static int reset_requested;
3465 static int shutdown_requested;
3466 static int powerdown_requested;
3467 static int debug_requested;
3468 static int vmstop_requested;
3470 int qemu_no_shutdown(void)
3472 int r = no_shutdown;
3473 no_shutdown = 0;
3474 return r;
3477 int qemu_shutdown_requested(void)
3479 int r = shutdown_requested;
3480 shutdown_requested = 0;
3481 return r;
3484 int qemu_reset_requested(void)
3486 int r = reset_requested;
3487 reset_requested = 0;
3488 return r;
3491 int qemu_powerdown_requested(void)
3493 int r = powerdown_requested;
3494 powerdown_requested = 0;
3495 return r;
3498 static int qemu_debug_requested(void)
3500 int r = debug_requested;
3501 debug_requested = 0;
3502 return r;
3505 static int qemu_vmstop_requested(void)
3507 int r = vmstop_requested;
3508 vmstop_requested = 0;
3509 return r;
3512 static void do_vm_stop(int reason)
3514 if (vm_running) {
3515 cpu_disable_ticks();
3516 vm_running = 0;
3517 pause_all_vcpus();
3518 vm_state_notify(0, reason);
3522 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3524 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3526 re->func = func;
3527 re->opaque = opaque;
3528 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3531 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3533 QEMUResetEntry *re;
3535 TAILQ_FOREACH(re, &reset_handlers, entry) {
3536 if (re->func == func && re->opaque == opaque) {
3537 TAILQ_REMOVE(&reset_handlers, re, entry);
3538 qemu_free(re);
3539 return;
3544 void qemu_system_reset(void)
3546 QEMUResetEntry *re, *nre;
3548 /* reset all devices */
3549 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3550 re->func(re->opaque);
3554 void qemu_system_reset_request(void)
3556 if (no_reboot) {
3557 shutdown_requested = 1;
3558 } else {
3559 reset_requested = 1;
3561 if (cpu_single_env) {
3562 cpu_single_env->stopped = 1;
3564 qemu_notify_event();
3567 void qemu_system_shutdown_request(void)
3569 shutdown_requested = 1;
3570 qemu_notify_event();
3573 void qemu_system_powerdown_request(void)
3575 powerdown_requested = 1;
3576 qemu_notify_event();
3579 #ifdef CONFIG_IOTHREAD
3580 static void qemu_system_vmstop_request(int reason)
3582 vmstop_requested = reason;
3583 qemu_notify_event();
3585 #endif
3587 #ifndef _WIN32
3588 static int io_thread_fd = -1;
3590 static void qemu_event_increment(void)
3592 static const char byte = 0;
3594 if (io_thread_fd == -1)
3595 return;
3597 write(io_thread_fd, &byte, sizeof(byte));
3600 static void qemu_event_read(void *opaque)
3602 int fd = (unsigned long)opaque;
3603 ssize_t len;
3605 /* Drain the notify pipe */
3606 do {
3607 char buffer[512];
3608 len = read(fd, buffer, sizeof(buffer));
3609 } while ((len == -1 && errno == EINTR) || len > 0);
3612 static int qemu_event_init(void)
3614 int err;
3615 int fds[2];
3617 err = pipe(fds);
3618 if (err == -1)
3619 return -errno;
3621 err = fcntl_setfl(fds[0], O_NONBLOCK);
3622 if (err < 0)
3623 goto fail;
3625 err = fcntl_setfl(fds[1], O_NONBLOCK);
3626 if (err < 0)
3627 goto fail;
3629 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3630 (void *)(unsigned long)fds[0]);
3632 io_thread_fd = fds[1];
3633 return 0;
3635 fail:
3636 close(fds[0]);
3637 close(fds[1]);
3638 return err;
3640 #else
3641 HANDLE qemu_event_handle;
3643 static void dummy_event_handler(void *opaque)
3647 static int qemu_event_init(void)
3649 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3650 if (!qemu_event_handle) {
3651 perror("Failed CreateEvent");
3652 return -1;
3654 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3655 return 0;
3658 static void qemu_event_increment(void)
3660 SetEvent(qemu_event_handle);
3662 #endif
3664 static int cpu_can_run(CPUState *env)
3666 if (env->stop)
3667 return 0;
3668 if (env->stopped)
3669 return 0;
3670 return 1;
3673 #ifndef CONFIG_IOTHREAD
3674 static int qemu_init_main_loop(void)
3676 return qemu_event_init();
3679 void qemu_init_vcpu(void *_env)
3681 CPUState *env = _env;
3683 if (kvm_enabled())
3684 kvm_init_vcpu(env);
3685 return;
3688 int qemu_cpu_self(void *env)
3690 return 1;
3693 static void resume_all_vcpus(void)
3697 static void pause_all_vcpus(void)
3701 void qemu_cpu_kick(void *env)
3703 return;
3706 void qemu_notify_event(void)
3708 CPUState *env = cpu_single_env;
3710 if (kvm_enabled()) {
3711 qemu_kvm_notify_work();
3712 return;
3714 if (env) {
3715 cpu_exit(env);
3716 #ifdef USE_KQEMU
3717 if (env->kqemu_enabled)
3718 kqemu_cpu_interrupt(env);
3719 #endif
3723 #ifdef KVM_UPSTREAM
3724 #define qemu_mutex_lock_iothread() do { } while (0)
3725 #define qemu_mutex_unlock_iothread() do { } while (0)
3726 #endif
3728 void vm_stop(int reason)
3730 do_vm_stop(reason);
3733 #else /* CONFIG_IOTHREAD */
3735 #include "qemu-thread.h"
3737 QemuMutex qemu_global_mutex;
3738 static QemuMutex qemu_fair_mutex;
3740 static QemuThread io_thread;
3742 static QemuThread *tcg_cpu_thread;
3743 static QemuCond *tcg_halt_cond;
3745 static int qemu_system_ready;
3746 /* cpu creation */
3747 static QemuCond qemu_cpu_cond;
3748 /* system init */
3749 static QemuCond qemu_system_cond;
3750 static QemuCond qemu_pause_cond;
3752 static void block_io_signals(void);
3753 static void unblock_io_signals(void);
3754 static int tcg_has_work(void);
3756 static int qemu_init_main_loop(void)
3758 int ret;
3760 ret = qemu_event_init();
3761 if (ret)
3762 return ret;
3764 qemu_cond_init(&qemu_pause_cond);
3765 qemu_mutex_init(&qemu_fair_mutex);
3766 qemu_mutex_init(&qemu_global_mutex);
3767 qemu_mutex_lock(&qemu_global_mutex);
3769 unblock_io_signals();
3770 qemu_thread_self(&io_thread);
3772 return 0;
3775 static void qemu_wait_io_event(CPUState *env)
3777 while (!tcg_has_work())
3778 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3780 qemu_mutex_unlock(&qemu_global_mutex);
3783 * Users of qemu_global_mutex can be starved, having no chance
3784 * to acquire it since this path will get to it first.
3785 * So use another lock to provide fairness.
3787 qemu_mutex_lock(&qemu_fair_mutex);
3788 qemu_mutex_unlock(&qemu_fair_mutex);
3790 qemu_mutex_lock(&qemu_global_mutex);
3791 if (env->stop) {
3792 env->stop = 0;
3793 env->stopped = 1;
3794 qemu_cond_signal(&qemu_pause_cond);
3798 static int qemu_cpu_exec(CPUState *env);
3800 static void *kvm_cpu_thread_fn(void *arg)
3802 CPUState *env = arg;
3804 block_io_signals();
3805 qemu_thread_self(env->thread);
3807 /* signal CPU creation */
3808 qemu_mutex_lock(&qemu_global_mutex);
3809 env->created = 1;
3810 qemu_cond_signal(&qemu_cpu_cond);
3812 /* and wait for machine initialization */
3813 while (!qemu_system_ready)
3814 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3816 while (1) {
3817 if (cpu_can_run(env))
3818 qemu_cpu_exec(env);
3819 qemu_wait_io_event(env);
3822 return NULL;
3825 static void tcg_cpu_exec(void);
3827 static void *tcg_cpu_thread_fn(void *arg)
3829 CPUState *env = arg;
3831 block_io_signals();
3832 qemu_thread_self(env->thread);
3834 /* signal CPU creation */
3835 qemu_mutex_lock(&qemu_global_mutex);
3836 for (env = first_cpu; env != NULL; env = env->next_cpu)
3837 env->created = 1;
3838 qemu_cond_signal(&qemu_cpu_cond);
3840 /* and wait for machine initialization */
3841 while (!qemu_system_ready)
3842 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3844 while (1) {
3845 tcg_cpu_exec();
3846 qemu_wait_io_event(cur_cpu);
3849 return NULL;
3852 void qemu_cpu_kick(void *_env)
3854 CPUState *env = _env;
3855 qemu_cond_broadcast(env->halt_cond);
3856 if (kvm_enabled())
3857 qemu_thread_signal(env->thread, SIGUSR1);
3860 int qemu_cpu_self(void *env)
3862 return (cpu_single_env != NULL);
3865 static void cpu_signal(int sig)
3867 if (cpu_single_env)
3868 cpu_exit(cpu_single_env);
3871 static void block_io_signals(void)
3873 sigset_t set;
3874 struct sigaction sigact;
3876 sigemptyset(&set);
3877 sigaddset(&set, SIGUSR2);
3878 sigaddset(&set, SIGIO);
3879 sigaddset(&set, SIGALRM);
3880 pthread_sigmask(SIG_BLOCK, &set, NULL);
3882 sigemptyset(&set);
3883 sigaddset(&set, SIGUSR1);
3884 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3886 memset(&sigact, 0, sizeof(sigact));
3887 sigact.sa_handler = cpu_signal;
3888 sigaction(SIGUSR1, &sigact, NULL);
3891 static void unblock_io_signals(void)
3893 sigset_t set;
3895 sigemptyset(&set);
3896 sigaddset(&set, SIGUSR2);
3897 sigaddset(&set, SIGIO);
3898 sigaddset(&set, SIGALRM);
3899 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3901 sigemptyset(&set);
3902 sigaddset(&set, SIGUSR1);
3903 pthread_sigmask(SIG_BLOCK, &set, NULL);
3906 static void qemu_signal_lock(unsigned int msecs)
3908 qemu_mutex_lock(&qemu_fair_mutex);
3910 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3911 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3912 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3913 break;
3915 qemu_mutex_unlock(&qemu_fair_mutex);
3918 static void qemu_mutex_lock_iothread(void)
3920 if (kvm_enabled()) {
3921 qemu_mutex_lock(&qemu_fair_mutex);
3922 qemu_mutex_lock(&qemu_global_mutex);
3923 qemu_mutex_unlock(&qemu_fair_mutex);
3924 } else
3925 qemu_signal_lock(100);
3928 static void qemu_mutex_unlock_iothread(void)
3930 qemu_mutex_unlock(&qemu_global_mutex);
3933 static int all_vcpus_paused(void)
3935 CPUState *penv = first_cpu;
3937 while (penv) {
3938 if (!penv->stopped)
3939 return 0;
3940 penv = (CPUState *)penv->next_cpu;
3943 return 1;
3946 static void pause_all_vcpus(void)
3948 CPUState *penv = first_cpu;
3950 while (penv) {
3951 penv->stop = 1;
3952 qemu_thread_signal(penv->thread, SIGUSR1);
3953 qemu_cpu_kick(penv);
3954 penv = (CPUState *)penv->next_cpu;
3957 while (!all_vcpus_paused()) {
3958 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3959 penv = first_cpu;
3960 while (penv) {
3961 qemu_thread_signal(penv->thread, SIGUSR1);
3962 penv = (CPUState *)penv->next_cpu;
3967 static void resume_all_vcpus(void)
3969 CPUState *penv = first_cpu;
3971 while (penv) {
3972 penv->stop = 0;
3973 penv->stopped = 0;
3974 qemu_thread_signal(penv->thread, SIGUSR1);
3975 qemu_cpu_kick(penv);
3976 penv = (CPUState *)penv->next_cpu;
3980 static void tcg_init_vcpu(void *_env)
3982 CPUState *env = _env;
3983 /* share a single thread for all cpus with TCG */
3984 if (!tcg_cpu_thread) {
3985 env->thread = qemu_mallocz(sizeof(QemuThread));
3986 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3987 qemu_cond_init(env->halt_cond);
3988 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3989 while (env->created == 0)
3990 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3991 tcg_cpu_thread = env->thread;
3992 tcg_halt_cond = env->halt_cond;
3993 } else {
3994 env->thread = tcg_cpu_thread;
3995 env->halt_cond = tcg_halt_cond;
3999 static void kvm_start_vcpu(CPUState *env)
4001 kvm_init_vcpu(env);
4002 env->thread = qemu_mallocz(sizeof(QemuThread));
4003 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4004 qemu_cond_init(env->halt_cond);
4005 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4006 while (env->created == 0)
4007 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4010 void qemu_init_vcpu(void *_env)
4012 CPUState *env = _env;
4014 if (kvm_enabled())
4015 kvm_start_vcpu(env);
4016 else
4017 tcg_init_vcpu(env);
4020 void qemu_notify_event(void)
4022 qemu_event_increment();
4025 void vm_stop(int reason)
4027 QemuThread me;
4028 qemu_thread_self(&me);
4030 if (!qemu_thread_equal(&me, &io_thread)) {
4031 qemu_system_vmstop_request(reason);
4033 * FIXME: should not return to device code in case
4034 * vm_stop() has been requested.
4036 if (cpu_single_env) {
4037 cpu_exit(cpu_single_env);
4038 cpu_single_env->stop = 1;
4040 return;
4042 do_vm_stop(reason);
4045 #endif
4048 #ifdef _WIN32
4049 static void host_main_loop_wait(int *timeout)
4051 int ret, ret2, i;
4052 PollingEntry *pe;
4055 /* XXX: need to suppress polling by better using win32 events */
4056 ret = 0;
4057 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4058 ret |= pe->func(pe->opaque);
4060 if (ret == 0) {
4061 int err;
4062 WaitObjects *w = &wait_objects;
4064 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4065 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4066 if (w->func[ret - WAIT_OBJECT_0])
4067 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4069 /* Check for additional signaled events */
4070 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4072 /* Check if event is signaled */
4073 ret2 = WaitForSingleObject(w->events[i], 0);
4074 if(ret2 == WAIT_OBJECT_0) {
4075 if (w->func[i])
4076 w->func[i](w->opaque[i]);
4077 } else if (ret2 == WAIT_TIMEOUT) {
4078 } else {
4079 err = GetLastError();
4080 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4083 } else if (ret == WAIT_TIMEOUT) {
4084 } else {
4085 err = GetLastError();
4086 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4090 *timeout = 0;
4092 #else
4093 static void host_main_loop_wait(int *timeout)
4096 #endif
4098 void main_loop_wait(int timeout)
4100 IOHandlerRecord *ioh;
4101 fd_set rfds, wfds, xfds;
4102 int ret, nfds;
4103 struct timeval tv;
4105 qemu_bh_update_timeout(&timeout);
4107 host_main_loop_wait(&timeout);
4109 /* poll any events */
4110 /* XXX: separate device handlers from system ones */
4111 nfds = -1;
4112 FD_ZERO(&rfds);
4113 FD_ZERO(&wfds);
4114 FD_ZERO(&xfds);
4115 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4116 if (ioh->deleted)
4117 continue;
4118 if (ioh->fd_read &&
4119 (!ioh->fd_read_poll ||
4120 ioh->fd_read_poll(ioh->opaque) != 0)) {
4121 FD_SET(ioh->fd, &rfds);
4122 if (ioh->fd > nfds)
4123 nfds = ioh->fd;
4125 if (ioh->fd_write) {
4126 FD_SET(ioh->fd, &wfds);
4127 if (ioh->fd > nfds)
4128 nfds = ioh->fd;
4132 tv.tv_sec = timeout / 1000;
4133 tv.tv_usec = (timeout % 1000) * 1000;
4135 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4137 qemu_mutex_unlock_iothread();
4138 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4139 qemu_mutex_lock_iothread();
4140 if (ret > 0) {
4141 IOHandlerRecord **pioh;
4143 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4144 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4145 ioh->fd_read(ioh->opaque);
4146 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4147 FD_CLR(ioh->fd, &rfds);
4149 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4150 ioh->fd_write(ioh->opaque);
4154 /* remove deleted IO handlers */
4155 pioh = &first_io_handler;
4156 while (*pioh) {
4157 ioh = *pioh;
4158 if (ioh->deleted) {
4159 *pioh = ioh->next;
4160 qemu_free(ioh);
4161 } else
4162 pioh = &ioh->next;
4166 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4168 /* rearm timer, if not periodic */
4169 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4170 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4171 qemu_rearm_alarm_timer(alarm_timer);
4174 /* vm time timers */
4175 if (vm_running) {
4176 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4177 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4178 qemu_get_clock(vm_clock));
4181 /* real time timers */
4182 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4183 qemu_get_clock(rt_clock));
4185 /* Check bottom-halves last in case any of the earlier events triggered
4186 them. */
4187 qemu_bh_poll();
4191 static int qemu_cpu_exec(CPUState *env)
4193 int ret;
4194 #ifdef CONFIG_PROFILER
4195 int64_t ti;
4196 #endif
4198 #ifdef CONFIG_PROFILER
4199 ti = profile_getclock();
4200 #endif
4201 if (use_icount) {
4202 int64_t count;
4203 int decr;
4204 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4205 env->icount_decr.u16.low = 0;
4206 env->icount_extra = 0;
4207 count = qemu_next_deadline();
4208 count = (count + (1 << icount_time_shift) - 1)
4209 >> icount_time_shift;
4210 qemu_icount += count;
4211 decr = (count > 0xffff) ? 0xffff : count;
4212 count -= decr;
4213 env->icount_decr.u16.low = decr;
4214 env->icount_extra = count;
4216 ret = cpu_exec(env);
4217 #ifdef CONFIG_PROFILER
4218 qemu_time += profile_getclock() - ti;
4219 #endif
4220 if (use_icount) {
4221 /* Fold pending instructions back into the
4222 instruction counter, and clear the interrupt flag. */
4223 qemu_icount -= (env->icount_decr.u16.low
4224 + env->icount_extra);
4225 env->icount_decr.u32 = 0;
4226 env->icount_extra = 0;
4228 return ret;
4231 static void tcg_cpu_exec(void)
4233 int ret = 0;
4235 if (next_cpu == NULL)
4236 next_cpu = first_cpu;
4237 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4238 CPUState *env = cur_cpu = next_cpu;
4240 if (!vm_running)
4241 break;
4242 if (timer_alarm_pending) {
4243 timer_alarm_pending = 0;
4244 break;
4246 if (cpu_can_run(env))
4247 ret = qemu_cpu_exec(env);
4248 if (ret == EXCP_DEBUG) {
4249 gdb_set_stop_cpu(env);
4250 debug_requested = 1;
4251 break;
4256 static int cpu_has_work(CPUState *env)
4258 if (env->stop)
4259 return 1;
4260 if (env->stopped)
4261 return 0;
4262 if (!env->halted)
4263 return 1;
4264 if (qemu_cpu_has_work(env))
4265 return 1;
4266 return 0;
4269 static int tcg_has_work(void)
4271 CPUState *env;
4273 for (env = first_cpu; env != NULL; env = env->next_cpu)
4274 if (cpu_has_work(env))
4275 return 1;
4276 return 0;
4279 static int qemu_calculate_timeout(void)
4281 #ifndef CONFIG_IOTHREAD
4282 int timeout;
4284 if (!vm_running)
4285 timeout = 5000;
4286 else if (tcg_has_work())
4287 timeout = 0;
4288 else if (!use_icount)
4289 timeout = 5000;
4290 else {
4291 /* XXX: use timeout computed from timers */
4292 int64_t add;
4293 int64_t delta;
4294 /* Advance virtual time to the next event. */
4295 if (use_icount == 1) {
4296 /* When not using an adaptive execution frequency
4297 we tend to get badly out of sync with real time,
4298 so just delay for a reasonable amount of time. */
4299 delta = 0;
4300 } else {
4301 delta = cpu_get_icount() - cpu_get_clock();
4303 if (delta > 0) {
4304 /* If virtual time is ahead of real time then just
4305 wait for IO. */
4306 timeout = (delta / 1000000) + 1;
4307 } else {
4308 /* Wait for either IO to occur or the next
4309 timer event. */
4310 add = qemu_next_deadline();
4311 /* We advance the timer before checking for IO.
4312 Limit the amount we advance so that early IO
4313 activity won't get the guest too far ahead. */
4314 if (add > 10000000)
4315 add = 10000000;
4316 delta += add;
4317 add = (add + (1 << icount_time_shift) - 1)
4318 >> icount_time_shift;
4319 qemu_icount += add;
4320 timeout = delta / 1000000;
4321 if (timeout < 0)
4322 timeout = 0;
4326 return timeout;
4327 #else /* CONFIG_IOTHREAD */
4328 return 1000;
4329 #endif
4332 static int vm_can_run(void)
4334 if (powerdown_requested)
4335 return 0;
4336 if (reset_requested)
4337 return 0;
4338 if (shutdown_requested)
4339 return 0;
4340 if (debug_requested)
4341 return 0;
4342 return 1;
4345 static void main_loop(void)
4347 int r;
4349 if (kvm_enabled()) {
4350 kvm_main_loop();
4351 cpu_disable_ticks();
4352 return;
4355 #ifdef CONFIG_IOTHREAD
4356 qemu_system_ready = 1;
4357 qemu_cond_broadcast(&qemu_system_cond);
4358 #endif
4360 for (;;) {
4361 do {
4362 #ifdef CONFIG_PROFILER
4363 int64_t ti;
4364 #endif
4365 #ifndef CONFIG_IOTHREAD
4366 tcg_cpu_exec();
4367 #endif
4368 #ifdef CONFIG_PROFILER
4369 ti = profile_getclock();
4370 #endif
4371 main_loop_wait(qemu_calculate_timeout());
4372 #ifdef CONFIG_PROFILER
4373 dev_time += profile_getclock() - ti;
4374 #endif
4375 } while (vm_can_run());
4377 if (qemu_debug_requested())
4378 vm_stop(EXCP_DEBUG);
4379 if (qemu_shutdown_requested()) {
4380 if (no_shutdown) {
4381 vm_stop(0);
4382 no_shutdown = 0;
4383 } else
4384 break;
4386 if (qemu_reset_requested()) {
4387 pause_all_vcpus();
4388 qemu_system_reset();
4389 resume_all_vcpus();
4391 if (qemu_powerdown_requested())
4392 qemu_system_powerdown();
4393 if ((r = qemu_vmstop_requested()))
4394 vm_stop(r);
4396 pause_all_vcpus();
4399 static void version(void)
4401 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4404 static void help(int exitcode)
4406 version();
4407 printf("usage: %s [options] [disk_image]\n"
4408 "\n"
4409 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4410 "\n"
4411 #define DEF(option, opt_arg, opt_enum, opt_help) \
4412 opt_help
4413 #define DEFHEADING(text) stringify(text) "\n"
4414 #include "qemu-options.h"
4415 #undef DEF
4416 #undef DEFHEADING
4417 #undef GEN_DOCS
4418 "\n"
4419 "During emulation, the following keys are useful:\n"
4420 "ctrl-alt-f toggle full screen\n"
4421 "ctrl-alt-n switch to virtual console 'n'\n"
4422 "ctrl-alt toggle mouse and keyboard grab\n"
4423 "\n"
4424 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4426 "qemu",
4427 DEFAULT_RAM_SIZE,
4428 #ifndef _WIN32
4429 DEFAULT_NETWORK_SCRIPT,
4430 DEFAULT_NETWORK_DOWN_SCRIPT,
4431 #endif
4432 DEFAULT_GDBSTUB_PORT,
4433 "/tmp/qemu.log");
4434 exit(exitcode);
4437 #define HAS_ARG 0x0001
4439 enum {
4440 #define DEF(option, opt_arg, opt_enum, opt_help) \
4441 opt_enum,
4442 #define DEFHEADING(text)
4443 #include "qemu-options.h"
4444 #undef DEF
4445 #undef DEFHEADING
4446 #undef GEN_DOCS
4449 typedef struct QEMUOption {
4450 const char *name;
4451 int flags;
4452 int index;
4453 } QEMUOption;
4455 static const QEMUOption qemu_options[] = {
4456 { "h", 0, QEMU_OPTION_h },
4457 #define DEF(option, opt_arg, opt_enum, opt_help) \
4458 { option, opt_arg, opt_enum },
4459 #define DEFHEADING(text)
4460 #include "qemu-options.h"
4461 #undef DEF
4462 #undef DEFHEADING
4463 #undef GEN_DOCS
4464 { NULL },
4467 #ifdef HAS_AUDIO
4468 struct soundhw soundhw[] = {
4469 #ifdef HAS_AUDIO_CHOICE
4470 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4472 "pcspk",
4473 "PC speaker",
4476 { .init_isa = pcspk_audio_init }
4478 #endif
4480 #ifdef CONFIG_SB16
4482 "sb16",
4483 "Creative Sound Blaster 16",
4486 { .init_isa = SB16_init }
4488 #endif
4490 #ifdef CONFIG_CS4231A
4492 "cs4231a",
4493 "CS4231A",
4496 { .init_isa = cs4231a_init }
4498 #endif
4500 #ifdef CONFIG_ADLIB
4502 "adlib",
4503 #ifdef HAS_YMF262
4504 "Yamaha YMF262 (OPL3)",
4505 #else
4506 "Yamaha YM3812 (OPL2)",
4507 #endif
4510 { .init_isa = Adlib_init }
4512 #endif
4514 #ifdef CONFIG_GUS
4516 "gus",
4517 "Gravis Ultrasound GF1",
4520 { .init_isa = GUS_init }
4522 #endif
4524 #ifdef CONFIG_AC97
4526 "ac97",
4527 "Intel 82801AA AC97 Audio",
4530 { .init_pci = ac97_init }
4532 #endif
4534 #ifdef CONFIG_ES1370
4536 "es1370",
4537 "ENSONIQ AudioPCI ES1370",
4540 { .init_pci = es1370_init }
4542 #endif
4544 #endif /* HAS_AUDIO_CHOICE */
4546 { NULL, NULL, 0, 0, { NULL } }
4549 static void select_soundhw (const char *optarg)
4551 struct soundhw *c;
4553 if (*optarg == '?') {
4554 show_valid_cards:
4556 printf ("Valid sound card names (comma separated):\n");
4557 for (c = soundhw; c->name; ++c) {
4558 printf ("%-11s %s\n", c->name, c->descr);
4560 printf ("\n-soundhw all will enable all of the above\n");
4561 exit (*optarg != '?');
4563 else {
4564 size_t l;
4565 const char *p;
4566 char *e;
4567 int bad_card = 0;
4569 if (!strcmp (optarg, "all")) {
4570 for (c = soundhw; c->name; ++c) {
4571 c->enabled = 1;
4573 return;
4576 p = optarg;
4577 while (*p) {
4578 e = strchr (p, ',');
4579 l = !e ? strlen (p) : (size_t) (e - p);
4581 for (c = soundhw; c->name; ++c) {
4582 if (!strncmp (c->name, p, l)) {
4583 c->enabled = 1;
4584 break;
4588 if (!c->name) {
4589 if (l > 80) {
4590 fprintf (stderr,
4591 "Unknown sound card name (too big to show)\n");
4593 else {
4594 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4595 (int) l, p);
4597 bad_card = 1;
4599 p += l + (e != NULL);
4602 if (bad_card)
4603 goto show_valid_cards;
4606 #endif
4608 static void select_vgahw (const char *p)
4610 const char *opts;
4612 cirrus_vga_enabled = 0;
4613 std_vga_enabled = 0;
4614 vmsvga_enabled = 0;
4615 xenfb_enabled = 0;
4616 if (strstart(p, "std", &opts)) {
4617 std_vga_enabled = 1;
4618 } else if (strstart(p, "cirrus", &opts)) {
4619 cirrus_vga_enabled = 1;
4620 } else if (strstart(p, "vmware", &opts)) {
4621 vmsvga_enabled = 1;
4622 } else if (strstart(p, "xenfb", &opts)) {
4623 xenfb_enabled = 1;
4624 } else if (!strstart(p, "none", &opts)) {
4625 invalid_vga:
4626 fprintf(stderr, "Unknown vga type: %s\n", p);
4627 exit(1);
4629 while (*opts) {
4630 const char *nextopt;
4632 if (strstart(opts, ",retrace=", &nextopt)) {
4633 opts = nextopt;
4634 if (strstart(opts, "dumb", &nextopt))
4635 vga_retrace_method = VGA_RETRACE_DUMB;
4636 else if (strstart(opts, "precise", &nextopt))
4637 vga_retrace_method = VGA_RETRACE_PRECISE;
4638 else goto invalid_vga;
4639 } else goto invalid_vga;
4640 opts = nextopt;
4644 #ifdef TARGET_I386
4645 static int balloon_parse(const char *arg)
4647 char buf[128];
4648 const char *p;
4650 if (!strcmp(arg, "none")) {
4651 virtio_balloon = 0;
4652 } else if (!strncmp(arg, "virtio", 6)) {
4653 virtio_balloon = 1;
4654 if (arg[6] == ',') {
4655 p = arg + 7;
4656 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4657 virtio_balloon_devaddr = strdup(buf);
4660 } else {
4661 return -1;
4663 return 0;
4665 #endif
4667 #ifdef _WIN32
4668 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4670 exit(STATUS_CONTROL_C_EXIT);
4671 return TRUE;
4673 #endif
4675 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4677 int ret;
4679 if(strlen(str) != 36)
4680 return -1;
4682 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4683 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4684 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4686 if(ret != 16)
4687 return -1;
4689 #ifdef TARGET_I386
4690 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4691 #endif
4693 return 0;
4696 #define MAX_NET_CLIENTS 32
4698 #ifndef _WIN32
4700 static void termsig_handler(int signal)
4702 qemu_system_shutdown_request();
4705 static void sigchld_handler(int signal)
4707 waitpid(-1, NULL, WNOHANG);
4710 static void sighandler_setup(void)
4712 struct sigaction act;
4714 memset(&act, 0, sizeof(act));
4715 act.sa_handler = termsig_handler;
4716 sigaction(SIGINT, &act, NULL);
4717 sigaction(SIGHUP, &act, NULL);
4718 sigaction(SIGTERM, &act, NULL);
4720 act.sa_handler = sigchld_handler;
4721 act.sa_flags = SA_NOCLDSTOP;
4722 sigaction(SIGCHLD, &act, NULL);
4725 #endif
4727 #ifdef _WIN32
4728 /* Look for support files in the same directory as the executable. */
4729 static char *find_datadir(const char *argv0)
4731 char *p;
4732 char buf[MAX_PATH];
4733 DWORD len;
4735 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4736 if (len == 0) {
4737 return NULL;
4740 buf[len] = 0;
4741 p = buf + len - 1;
4742 while (p != buf && *p != '\\')
4743 p--;
4744 *p = 0;
4745 if (access(buf, R_OK) == 0) {
4746 return qemu_strdup(buf);
4748 return NULL;
4750 #else /* !_WIN32 */
4752 /* Find a likely location for support files using the location of the binary.
4753 For installed binaries this will be "$bindir/../share/qemu". When
4754 running from the build tree this will be "$bindir/../pc-bios". */
4755 #define SHARE_SUFFIX "/share/qemu"
4756 #define BUILD_SUFFIX "/pc-bios"
4757 static char *find_datadir(const char *argv0)
4759 char *dir;
4760 char *p = NULL;
4761 char *res;
4762 #ifdef PATH_MAX
4763 char buf[PATH_MAX];
4764 #endif
4765 size_t max_len;
4767 #if defined(__linux__)
4769 int len;
4770 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4771 if (len > 0) {
4772 buf[len] = 0;
4773 p = buf;
4776 #elif defined(__FreeBSD__)
4778 int len;
4779 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4780 if (len > 0) {
4781 buf[len] = 0;
4782 p = buf;
4785 #endif
4786 /* If we don't have any way of figuring out the actual executable
4787 location then try argv[0]. */
4788 if (!p) {
4789 #ifdef PATH_MAX
4790 p = buf;
4791 #endif
4792 p = realpath(argv0, p);
4793 if (!p) {
4794 return NULL;
4797 dir = dirname(p);
4798 dir = dirname(dir);
4800 max_len = strlen(dir) +
4801 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4802 res = qemu_mallocz(max_len);
4803 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4804 if (access(res, R_OK)) {
4805 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4806 if (access(res, R_OK)) {
4807 qemu_free(res);
4808 res = NULL;
4811 #ifndef PATH_MAX
4812 free(p);
4813 #endif
4814 return res;
4816 #undef SHARE_SUFFIX
4817 #undef BUILD_SUFFIX
4818 #endif
4820 char *qemu_find_file(int type, const char *name)
4822 int len;
4823 const char *subdir;
4824 char *buf;
4826 /* If name contains path separators then try it as a straight path. */
4827 if ((strchr(name, '/') || strchr(name, '\\'))
4828 && access(name, R_OK) == 0) {
4829 return strdup(name);
4831 switch (type) {
4832 case QEMU_FILE_TYPE_BIOS:
4833 subdir = "";
4834 break;
4835 case QEMU_FILE_TYPE_KEYMAP:
4836 subdir = "keymaps/";
4837 break;
4838 default:
4839 abort();
4841 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4842 buf = qemu_mallocz(len);
4843 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4844 if (access(buf, R_OK)) {
4845 qemu_free(buf);
4846 return NULL;
4848 return buf;
4851 struct device_config {
4852 enum {
4853 DEV_GENERIC, /* -device */
4854 DEV_USB, /* -usbdevice */
4855 DEV_BT, /* -bt */
4856 } type;
4857 const char *cmdline;
4858 TAILQ_ENTRY(device_config) next;
4860 TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4862 static void add_device_config(int type, const char *cmdline)
4864 struct device_config *conf;
4866 conf = qemu_mallocz(sizeof(*conf));
4867 conf->type = type;
4868 conf->cmdline = cmdline;
4869 TAILQ_INSERT_TAIL(&device_configs, conf, next);
4872 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4874 struct device_config *conf;
4875 int rc;
4877 TAILQ_FOREACH(conf, &device_configs, next) {
4878 if (conf->type != type)
4879 continue;
4880 rc = func(conf->cmdline);
4881 if (0 != rc)
4882 return rc;
4884 return 0;
4887 static int generic_parse(const char *cmdline)
4889 DeviceState *dev;
4891 dev = qdev_device_add(cmdline);
4892 if (!dev)
4893 return -1;
4894 return 0;
4897 int main(int argc, char **argv, char **envp)
4899 const char *gdbstub_dev = NULL;
4900 uint32_t boot_devices_bitmap = 0;
4901 int i;
4902 int snapshot, linux_boot, net_boot;
4903 const char *initrd_filename;
4904 const char *kernel_filename, *kernel_cmdline;
4905 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4906 DisplayState *ds;
4907 DisplayChangeListener *dcl;
4908 int cyls, heads, secs, translation;
4909 const char *net_clients[MAX_NET_CLIENTS];
4910 int nb_net_clients;
4911 QemuOpts *hda_opts = NULL;
4912 int optind;
4913 const char *r, *optarg;
4914 CharDriverState *monitor_hd = NULL;
4915 const char *monitor_device;
4916 const char *serial_devices[MAX_SERIAL_PORTS];
4917 int serial_device_index;
4918 const char *parallel_devices[MAX_PARALLEL_PORTS];
4919 int parallel_device_index;
4920 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4921 int virtio_console_index;
4922 const char *loadvm = NULL;
4923 QEMUMachine *machine;
4924 const char *cpu_model;
4925 #ifndef _WIN32
4926 int fds[2];
4927 #endif
4928 int tb_size;
4929 const char *pid_file = NULL;
4930 const char *incoming = NULL;
4931 #ifndef _WIN32
4932 int fd = 0;
4933 struct passwd *pwd = NULL;
4934 const char *chroot_dir = NULL;
4935 const char *run_as = NULL;
4936 #endif
4937 CPUState *env;
4938 int show_vnc_port = 0;
4940 qemu_cache_utils_init(envp);
4942 LIST_INIT (&vm_change_state_head);
4943 #ifndef _WIN32
4945 struct sigaction act;
4946 sigfillset(&act.sa_mask);
4947 act.sa_flags = 0;
4948 act.sa_handler = SIG_IGN;
4949 sigaction(SIGPIPE, &act, NULL);
4951 #else
4952 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4953 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4954 QEMU to run on a single CPU */
4956 HANDLE h;
4957 DWORD mask, smask;
4958 int i;
4959 h = GetCurrentProcess();
4960 if (GetProcessAffinityMask(h, &mask, &smask)) {
4961 for(i = 0; i < 32; i++) {
4962 if (mask & (1 << i))
4963 break;
4965 if (i != 32) {
4966 mask = 1 << i;
4967 SetProcessAffinityMask(h, mask);
4971 #endif
4973 module_call_init(MODULE_INIT_MACHINE);
4974 machine = find_default_machine();
4975 cpu_model = NULL;
4976 initrd_filename = NULL;
4977 ram_size = 0;
4978 snapshot = 0;
4979 kernel_filename = NULL;
4980 kernel_cmdline = "";
4981 cyls = heads = secs = 0;
4982 translation = BIOS_ATA_TRANSLATION_AUTO;
4983 monitor_device = "vc:80Cx24C";
4985 serial_devices[0] = "vc:80Cx24C";
4986 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4987 serial_devices[i] = NULL;
4988 serial_device_index = 0;
4990 parallel_devices[0] = "vc:80Cx24C";
4991 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4992 parallel_devices[i] = NULL;
4993 parallel_device_index = 0;
4995 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4996 virtio_consoles[i] = NULL;
4997 virtio_console_index = 0;
4999 for (i = 0; i < MAX_NODES; i++) {
5000 node_mem[i] = 0;
5001 node_cpumask[i] = 0;
5004 assigned_devices_index = 0;
5006 nb_net_clients = 0;
5007 nb_numa_nodes = 0;
5008 nb_nics = 0;
5010 tb_size = 0;
5011 autostart= 1;
5013 register_watchdogs();
5015 optind = 1;
5016 for(;;) {
5017 if (optind >= argc)
5018 break;
5019 r = argv[optind];
5020 if (r[0] != '-') {
5021 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
5022 } else {
5023 const QEMUOption *popt;
5025 optind++;
5026 /* Treat --foo the same as -foo. */
5027 if (r[1] == '-')
5028 r++;
5029 popt = qemu_options;
5030 for(;;) {
5031 if (!popt->name) {
5032 fprintf(stderr, "%s: invalid option -- '%s'\n",
5033 argv[0], r);
5034 exit(1);
5036 if (!strcmp(popt->name, r + 1))
5037 break;
5038 popt++;
5040 if (popt->flags & HAS_ARG) {
5041 if (optind >= argc) {
5042 fprintf(stderr, "%s: option '%s' requires an argument\n",
5043 argv[0], r);
5044 exit(1);
5046 optarg = argv[optind++];
5047 } else {
5048 optarg = NULL;
5051 switch(popt->index) {
5052 case QEMU_OPTION_M:
5053 machine = find_machine(optarg);
5054 if (!machine) {
5055 QEMUMachine *m;
5056 printf("Supported machines are:\n");
5057 for(m = first_machine; m != NULL; m = m->next) {
5058 if (m->alias)
5059 printf("%-10s %s (alias of %s)\n",
5060 m->alias, m->desc, m->name);
5061 printf("%-10s %s%s\n",
5062 m->name, m->desc,
5063 m->is_default ? " (default)" : "");
5065 exit(*optarg != '?');
5067 break;
5068 case QEMU_OPTION_cpu:
5069 /* hw initialization will check this */
5070 if (*optarg == '?') {
5071 /* XXX: implement xxx_cpu_list for targets that still miss it */
5072 #if defined(cpu_list)
5073 cpu_list(stdout, &fprintf);
5074 #endif
5075 exit(0);
5076 } else {
5077 cpu_model = optarg;
5079 break;
5080 case QEMU_OPTION_initrd:
5081 initrd_filename = optarg;
5082 break;
5083 case QEMU_OPTION_hda:
5084 if (cyls == 0)
5085 hda_opts = drive_add(optarg, HD_ALIAS, 0);
5086 else
5087 hda_opts = drive_add(optarg, HD_ALIAS
5088 ",cyls=%d,heads=%d,secs=%d%s",
5089 0, cyls, heads, secs,
5090 translation == BIOS_ATA_TRANSLATION_LBA ?
5091 ",trans=lba" :
5092 translation == BIOS_ATA_TRANSLATION_NONE ?
5093 ",trans=none" : "");
5094 break;
5095 case QEMU_OPTION_hdb:
5096 case QEMU_OPTION_hdc:
5097 case QEMU_OPTION_hdd:
5098 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5099 break;
5100 case QEMU_OPTION_drive:
5101 drive_add(NULL, "%s", optarg);
5102 break;
5103 case QEMU_OPTION_mtdblock:
5104 drive_add(optarg, MTD_ALIAS);
5105 break;
5106 case QEMU_OPTION_sd:
5107 drive_add(optarg, SD_ALIAS);
5108 break;
5109 case QEMU_OPTION_pflash:
5110 drive_add(optarg, PFLASH_ALIAS);
5111 break;
5112 case QEMU_OPTION_snapshot:
5113 snapshot = 1;
5114 break;
5115 case QEMU_OPTION_hdachs:
5117 const char *p;
5118 p = optarg;
5119 cyls = strtol(p, (char **)&p, 0);
5120 if (cyls < 1 || cyls > 16383)
5121 goto chs_fail;
5122 if (*p != ',')
5123 goto chs_fail;
5124 p++;
5125 heads = strtol(p, (char **)&p, 0);
5126 if (heads < 1 || heads > 16)
5127 goto chs_fail;
5128 if (*p != ',')
5129 goto chs_fail;
5130 p++;
5131 secs = strtol(p, (char **)&p, 0);
5132 if (secs < 1 || secs > 63)
5133 goto chs_fail;
5134 if (*p == ',') {
5135 p++;
5136 if (!strcmp(p, "none"))
5137 translation = BIOS_ATA_TRANSLATION_NONE;
5138 else if (!strcmp(p, "lba"))
5139 translation = BIOS_ATA_TRANSLATION_LBA;
5140 else if (!strcmp(p, "auto"))
5141 translation = BIOS_ATA_TRANSLATION_AUTO;
5142 else
5143 goto chs_fail;
5144 } else if (*p != '\0') {
5145 chs_fail:
5146 fprintf(stderr, "qemu: invalid physical CHS format\n");
5147 exit(1);
5149 if (hda_opts != NULL) {
5150 char num[16];
5151 snprintf(num, sizeof(num), "%d", cyls);
5152 qemu_opt_set(hda_opts, "cyls", num);
5153 snprintf(num, sizeof(num), "%d", heads);
5154 qemu_opt_set(hda_opts, "heads", num);
5155 snprintf(num, sizeof(num), "%d", secs);
5156 qemu_opt_set(hda_opts, "secs", num);
5157 if (translation == BIOS_ATA_TRANSLATION_LBA)
5158 qemu_opt_set(hda_opts, "trans", "lba");
5159 if (translation == BIOS_ATA_TRANSLATION_NONE)
5160 qemu_opt_set(hda_opts, "trans", "none");
5163 break;
5164 case QEMU_OPTION_numa:
5165 if (nb_numa_nodes >= MAX_NODES) {
5166 fprintf(stderr, "qemu: too many NUMA nodes\n");
5167 exit(1);
5169 numa_add(optarg);
5170 break;
5171 case QEMU_OPTION_nographic:
5172 display_type = DT_NOGRAPHIC;
5173 break;
5174 #ifdef CONFIG_CURSES
5175 case QEMU_OPTION_curses:
5176 display_type = DT_CURSES;
5177 break;
5178 #endif
5179 case QEMU_OPTION_portrait:
5180 graphic_rotate = 1;
5181 break;
5182 case QEMU_OPTION_kernel:
5183 kernel_filename = optarg;
5184 break;
5185 case QEMU_OPTION_append:
5186 kernel_cmdline = optarg;
5187 break;
5188 case QEMU_OPTION_cdrom:
5189 drive_add(optarg, CDROM_ALIAS);
5190 break;
5191 case QEMU_OPTION_boot:
5193 static const char * const params[] = {
5194 "order", "once", "menu", NULL
5196 char buf[sizeof(boot_devices)];
5197 char *standard_boot_devices;
5198 int legacy = 0;
5200 if (!strchr(optarg, '=')) {
5201 legacy = 1;
5202 pstrcpy(buf, sizeof(buf), optarg);
5203 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5204 fprintf(stderr,
5205 "qemu: unknown boot parameter '%s' in '%s'\n",
5206 buf, optarg);
5207 exit(1);
5210 if (legacy ||
5211 get_param_value(buf, sizeof(buf), "order", optarg)) {
5212 boot_devices_bitmap = parse_bootdevices(buf);
5213 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5215 if (!legacy) {
5216 if (get_param_value(buf, sizeof(buf),
5217 "once", optarg)) {
5218 boot_devices_bitmap |= parse_bootdevices(buf);
5219 standard_boot_devices = qemu_strdup(boot_devices);
5220 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5221 qemu_register_reset(restore_boot_devices,
5222 standard_boot_devices);
5224 if (get_param_value(buf, sizeof(buf),
5225 "menu", optarg)) {
5226 if (!strcmp(buf, "on")) {
5227 boot_menu = 1;
5228 } else if (!strcmp(buf, "off")) {
5229 boot_menu = 0;
5230 } else {
5231 fprintf(stderr,
5232 "qemu: invalid option value '%s'\n",
5233 buf);
5234 exit(1);
5239 break;
5240 case QEMU_OPTION_fda:
5241 case QEMU_OPTION_fdb:
5242 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5243 break;
5244 #ifdef TARGET_I386
5245 case QEMU_OPTION_no_fd_bootchk:
5246 fd_bootchk = 0;
5247 break;
5248 #endif
5249 case QEMU_OPTION_net:
5250 if (nb_net_clients >= MAX_NET_CLIENTS) {
5251 fprintf(stderr, "qemu: too many network clients\n");
5252 exit(1);
5254 net_clients[nb_net_clients] = optarg;
5255 nb_net_clients++;
5256 break;
5257 #ifdef CONFIG_SLIRP
5258 case QEMU_OPTION_tftp:
5259 legacy_tftp_prefix = optarg;
5260 break;
5261 case QEMU_OPTION_bootp:
5262 legacy_bootp_filename = optarg;
5263 break;
5264 #ifndef _WIN32
5265 case QEMU_OPTION_smb:
5266 net_slirp_smb(optarg);
5267 break;
5268 #endif
5269 case QEMU_OPTION_redir:
5270 net_slirp_redir(optarg);
5271 break;
5272 #endif
5273 case QEMU_OPTION_bt:
5274 add_device_config(DEV_BT, optarg);
5275 break;
5276 #ifdef HAS_AUDIO
5277 case QEMU_OPTION_audio_help:
5278 AUD_help ();
5279 exit (0);
5280 break;
5281 case QEMU_OPTION_soundhw:
5282 select_soundhw (optarg);
5283 break;
5284 #endif
5285 case QEMU_OPTION_h:
5286 help(0);
5287 break;
5288 case QEMU_OPTION_version:
5289 version();
5290 exit(0);
5291 break;
5292 case QEMU_OPTION_m: {
5293 uint64_t value;
5294 char *ptr;
5296 value = strtoul(optarg, &ptr, 10);
5297 switch (*ptr) {
5298 case 0: case 'M': case 'm':
5299 value <<= 20;
5300 break;
5301 case 'G': case 'g':
5302 value <<= 30;
5303 break;
5304 default:
5305 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5306 exit(1);
5309 /* On 32-bit hosts, QEMU is limited by virtual address space */
5310 if (value > (2047 << 20)
5311 #ifndef CONFIG_KQEMU
5312 && HOST_LONG_BITS == 32
5313 #endif
5315 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5316 exit(1);
5318 if (value != (uint64_t)(ram_addr_t)value) {
5319 fprintf(stderr, "qemu: ram size too large\n");
5320 exit(1);
5322 ram_size = value;
5323 break;
5325 case QEMU_OPTION_d:
5327 int mask;
5328 const CPULogItem *item;
5330 mask = cpu_str_to_log_mask(optarg);
5331 if (!mask) {
5332 printf("Log items (comma separated):\n");
5333 for(item = cpu_log_items; item->mask != 0; item++) {
5334 printf("%-10s %s\n", item->name, item->help);
5336 exit(1);
5338 cpu_set_log(mask);
5340 break;
5341 case QEMU_OPTION_s:
5342 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5343 break;
5344 case QEMU_OPTION_gdb:
5345 gdbstub_dev = optarg;
5346 break;
5347 case QEMU_OPTION_L:
5348 data_dir = optarg;
5349 break;
5350 case QEMU_OPTION_bios:
5351 bios_name = optarg;
5352 break;
5353 case QEMU_OPTION_singlestep:
5354 singlestep = 1;
5355 break;
5356 case QEMU_OPTION_S:
5357 autostart = 0;
5358 break;
5359 #ifndef _WIN32
5360 case QEMU_OPTION_k:
5361 keyboard_layout = optarg;
5362 break;
5363 #endif
5364 case QEMU_OPTION_localtime:
5365 rtc_utc = 0;
5366 break;
5367 case QEMU_OPTION_vga:
5368 select_vgahw (optarg);
5369 break;
5370 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5371 case QEMU_OPTION_g:
5373 const char *p;
5374 int w, h, depth;
5375 p = optarg;
5376 w = strtol(p, (char **)&p, 10);
5377 if (w <= 0) {
5378 graphic_error:
5379 fprintf(stderr, "qemu: invalid resolution or depth\n");
5380 exit(1);
5382 if (*p != 'x')
5383 goto graphic_error;
5384 p++;
5385 h = strtol(p, (char **)&p, 10);
5386 if (h <= 0)
5387 goto graphic_error;
5388 if (*p == 'x') {
5389 p++;
5390 depth = strtol(p, (char **)&p, 10);
5391 if (depth != 8 && depth != 15 && depth != 16 &&
5392 depth != 24 && depth != 32)
5393 goto graphic_error;
5394 } else if (*p == '\0') {
5395 depth = graphic_depth;
5396 } else {
5397 goto graphic_error;
5400 graphic_width = w;
5401 graphic_height = h;
5402 graphic_depth = depth;
5404 break;
5405 #endif
5406 case QEMU_OPTION_echr:
5408 char *r;
5409 term_escape_char = strtol(optarg, &r, 0);
5410 if (r == optarg)
5411 printf("Bad argument to echr\n");
5412 break;
5414 case QEMU_OPTION_monitor:
5415 monitor_device = optarg;
5416 break;
5417 case QEMU_OPTION_serial:
5418 if (serial_device_index >= MAX_SERIAL_PORTS) {
5419 fprintf(stderr, "qemu: too many serial ports\n");
5420 exit(1);
5422 serial_devices[serial_device_index] = optarg;
5423 serial_device_index++;
5424 break;
5425 case QEMU_OPTION_watchdog:
5426 i = select_watchdog(optarg);
5427 if (i > 0)
5428 exit (i == 1 ? 1 : 0);
5429 break;
5430 case QEMU_OPTION_watchdog_action:
5431 if (select_watchdog_action(optarg) == -1) {
5432 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5433 exit(1);
5435 break;
5436 case QEMU_OPTION_virtiocon:
5437 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5438 fprintf(stderr, "qemu: too many virtio consoles\n");
5439 exit(1);
5441 virtio_consoles[virtio_console_index] = optarg;
5442 virtio_console_index++;
5443 break;
5444 case QEMU_OPTION_parallel:
5445 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5446 fprintf(stderr, "qemu: too many parallel ports\n");
5447 exit(1);
5449 parallel_devices[parallel_device_index] = optarg;
5450 parallel_device_index++;
5451 break;
5452 case QEMU_OPTION_loadvm:
5453 loadvm = optarg;
5454 break;
5455 case QEMU_OPTION_full_screen:
5456 full_screen = 1;
5457 break;
5458 #ifdef CONFIG_SDL
5459 case QEMU_OPTION_no_frame:
5460 no_frame = 1;
5461 break;
5462 case QEMU_OPTION_alt_grab:
5463 alt_grab = 1;
5464 break;
5465 case QEMU_OPTION_no_quit:
5466 no_quit = 1;
5467 break;
5468 case QEMU_OPTION_sdl:
5469 display_type = DT_SDL;
5470 break;
5471 #endif
5472 case QEMU_OPTION_pidfile:
5473 pid_file = optarg;
5474 break;
5475 #ifdef TARGET_I386
5476 case QEMU_OPTION_win2k_hack:
5477 win2k_install_hack = 1;
5478 break;
5479 case QEMU_OPTION_rtc_td_hack:
5480 rtc_td_hack = 1;
5481 break;
5482 case QEMU_OPTION_acpitable:
5483 if(acpi_table_add(optarg) < 0) {
5484 fprintf(stderr, "Wrong acpi table provided\n");
5485 exit(1);
5487 break;
5488 case QEMU_OPTION_smbios:
5489 if(smbios_entry_add(optarg) < 0) {
5490 fprintf(stderr, "Wrong smbios provided\n");
5491 exit(1);
5493 break;
5494 #endif
5495 #ifdef CONFIG_KQEMU
5496 case QEMU_OPTION_enable_kqemu:
5497 kqemu_allowed = 1;
5498 break;
5499 case QEMU_OPTION_kernel_kqemu:
5500 kqemu_allowed = 2;
5501 break;
5502 #endif
5503 #ifdef CONFIG_KVM
5504 #ifdef KVM_UPSTREAM
5505 case QEMU_OPTION_enable_kvm:
5506 kvm_allowed = 1;
5507 #ifdef CONFIG_KQEMU
5508 kqemu_allowed = 0;
5509 #endif
5510 #endif
5511 break;
5512 case QEMU_OPTION_no_kvm:
5513 kvm_allowed = 0;
5514 break;
5515 case QEMU_OPTION_no_kvm_irqchip: {
5516 kvm_irqchip = 0;
5517 kvm_pit = 0;
5518 break;
5520 case QEMU_OPTION_no_kvm_pit: {
5521 kvm_pit = 0;
5522 break;
5524 case QEMU_OPTION_no_kvm_pit_reinjection: {
5525 kvm_pit_reinject = 0;
5526 break;
5528 case QEMU_OPTION_enable_nesting: {
5529 kvm_nested = 1;
5530 break;
5532 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5533 case QEMU_OPTION_pcidevice:
5534 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5535 fprintf(stderr, "Too many assigned devices\n");
5536 exit(1);
5538 assigned_devices[assigned_devices_index] = optarg;
5539 assigned_devices_index++;
5540 break;
5541 #endif
5542 #endif
5543 case QEMU_OPTION_usb:
5544 usb_enabled = 1;
5545 break;
5546 case QEMU_OPTION_usbdevice:
5547 usb_enabled = 1;
5548 add_device_config(DEV_USB, optarg);
5549 break;
5550 case QEMU_OPTION_device:
5551 add_device_config(DEV_GENERIC, optarg);
5552 break;
5553 case QEMU_OPTION_smp:
5555 char *p;
5556 char option[128];
5557 smp_cpus = strtol(optarg, &p, 10);
5558 if (smp_cpus < 1) {
5559 fprintf(stderr, "Invalid number of CPUs\n");
5560 exit(1);
5562 if (*p++ != ',')
5563 break;
5564 if (get_param_value(option, 128, "maxcpus", p))
5565 max_cpus = strtol(option, NULL, 0);
5566 if (max_cpus < smp_cpus) {
5567 fprintf(stderr, "maxcpus must be equal to or greater than "
5568 "smp\n");
5569 exit(1);
5571 if (max_cpus > 255) {
5572 fprintf(stderr, "Unsupported number of maxcpus\n");
5573 exit(1);
5575 break;
5577 case QEMU_OPTION_vnc:
5578 display_type = DT_VNC;
5579 vnc_display = optarg;
5580 break;
5581 #ifdef TARGET_I386
5582 case QEMU_OPTION_no_acpi:
5583 acpi_enabled = 0;
5584 break;
5585 case QEMU_OPTION_no_hpet:
5586 no_hpet = 1;
5587 break;
5588 case QEMU_OPTION_balloon:
5589 if (balloon_parse(optarg) < 0) {
5590 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5591 exit(1);
5593 break;
5594 #endif
5595 case QEMU_OPTION_no_reboot:
5596 no_reboot = 1;
5597 break;
5598 case QEMU_OPTION_no_shutdown:
5599 no_shutdown = 1;
5600 break;
5601 case QEMU_OPTION_show_cursor:
5602 cursor_hide = 0;
5603 break;
5604 case QEMU_OPTION_uuid:
5605 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5606 fprintf(stderr, "Fail to parse UUID string."
5607 " Wrong format.\n");
5608 exit(1);
5610 break;
5611 #ifndef _WIN32
5612 case QEMU_OPTION_daemonize:
5613 daemonize = 1;
5614 break;
5615 #endif
5616 case QEMU_OPTION_option_rom:
5617 if (nb_option_roms >= MAX_OPTION_ROMS) {
5618 fprintf(stderr, "Too many option ROMs\n");
5619 exit(1);
5621 option_rom[nb_option_roms] = optarg;
5622 nb_option_roms++;
5623 break;
5624 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5625 case QEMU_OPTION_semihosting:
5626 semihosting_enabled = 1;
5627 break;
5628 #endif
5629 case QEMU_OPTION_tdf:
5630 time_drift_fix = 1;
5631 break;
5632 case QEMU_OPTION_kvm_shadow_memory:
5633 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5634 break;
5635 case QEMU_OPTION_mempath:
5636 mem_path = optarg;
5637 break;
5638 #ifdef MAP_POPULATE
5639 case QEMU_OPTION_mem_prealloc:
5640 mem_prealloc = !mem_prealloc;
5641 break;
5642 #endif
5643 case QEMU_OPTION_name:
5644 qemu_name = qemu_strdup(optarg);
5646 char *p = strchr(qemu_name, ',');
5647 if (p != NULL) {
5648 *p++ = 0;
5649 if (strncmp(p, "process=", 8)) {
5650 fprintf(stderr, "Unknown subargument %s to -name", p);
5651 exit(1);
5653 p += 8;
5654 set_proc_name(p);
5657 break;
5658 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5659 case QEMU_OPTION_prom_env:
5660 if (nb_prom_envs >= MAX_PROM_ENVS) {
5661 fprintf(stderr, "Too many prom variables\n");
5662 exit(1);
5664 prom_envs[nb_prom_envs] = optarg;
5665 nb_prom_envs++;
5666 break;
5667 #endif
5668 #ifdef TARGET_ARM
5669 case QEMU_OPTION_old_param:
5670 old_param = 1;
5671 break;
5672 #endif
5673 case QEMU_OPTION_clock:
5674 configure_alarms(optarg);
5675 break;
5676 case QEMU_OPTION_startdate:
5678 struct tm tm;
5679 time_t rtc_start_date;
5680 if (!strcmp(optarg, "now")) {
5681 rtc_date_offset = -1;
5682 } else {
5683 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5684 &tm.tm_year,
5685 &tm.tm_mon,
5686 &tm.tm_mday,
5687 &tm.tm_hour,
5688 &tm.tm_min,
5689 &tm.tm_sec) == 6) {
5690 /* OK */
5691 } else if (sscanf(optarg, "%d-%d-%d",
5692 &tm.tm_year,
5693 &tm.tm_mon,
5694 &tm.tm_mday) == 3) {
5695 tm.tm_hour = 0;
5696 tm.tm_min = 0;
5697 tm.tm_sec = 0;
5698 } else {
5699 goto date_fail;
5701 tm.tm_year -= 1900;
5702 tm.tm_mon--;
5703 rtc_start_date = mktimegm(&tm);
5704 if (rtc_start_date == -1) {
5705 date_fail:
5706 fprintf(stderr, "Invalid date format. Valid format are:\n"
5707 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5708 exit(1);
5710 rtc_date_offset = time(NULL) - rtc_start_date;
5713 break;
5714 case QEMU_OPTION_tb_size:
5715 tb_size = strtol(optarg, NULL, 0);
5716 if (tb_size < 0)
5717 tb_size = 0;
5718 break;
5719 case QEMU_OPTION_icount:
5720 use_icount = 1;
5721 if (strcmp(optarg, "auto") == 0) {
5722 icount_time_shift = -1;
5723 } else {
5724 icount_time_shift = strtol(optarg, NULL, 0);
5726 break;
5727 case QEMU_OPTION_incoming:
5728 incoming = optarg;
5729 break;
5730 #ifndef _WIN32
5731 case QEMU_OPTION_chroot:
5732 chroot_dir = optarg;
5733 break;
5734 case QEMU_OPTION_runas:
5735 run_as = optarg;
5736 break;
5737 case QEMU_OPTION_nvram:
5738 nvram = optarg;
5739 break;
5740 #endif
5741 #ifdef CONFIG_XEN
5742 case QEMU_OPTION_xen_domid:
5743 xen_domid = atoi(optarg);
5744 break;
5745 case QEMU_OPTION_xen_create:
5746 xen_mode = XEN_CREATE;
5747 break;
5748 case QEMU_OPTION_xen_attach:
5749 xen_mode = XEN_ATTACH;
5750 break;
5751 #endif
5756 /* If no data_dir is specified then try to find it relative to the
5757 executable path. */
5758 if (!data_dir) {
5759 data_dir = find_datadir(argv[0]);
5761 /* If all else fails use the install patch specified when building. */
5762 if (!data_dir) {
5763 data_dir = CONFIG_QEMU_SHAREDIR;
5766 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5767 if (kvm_allowed && kqemu_allowed) {
5768 fprintf(stderr,
5769 "You can not enable both KVM and kqemu at the same time\n");
5770 exit(1);
5772 #endif
5775 * Default to max_cpus = smp_cpus, in case the user doesn't
5776 * specify a max_cpus value.
5778 if (!max_cpus)
5779 max_cpus = smp_cpus;
5781 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5782 if (smp_cpus > machine->max_cpus) {
5783 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5784 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5785 machine->max_cpus);
5786 exit(1);
5789 if (display_type == DT_NOGRAPHIC) {
5790 if (serial_device_index == 0)
5791 serial_devices[0] = "stdio";
5792 if (parallel_device_index == 0)
5793 parallel_devices[0] = "null";
5794 if (strncmp(monitor_device, "vc", 2) == 0)
5795 monitor_device = "stdio";
5798 #ifndef _WIN32
5799 if (daemonize) {
5800 pid_t pid;
5802 if (pipe(fds) == -1)
5803 exit(1);
5805 pid = fork();
5806 if (pid > 0) {
5807 uint8_t status;
5808 ssize_t len;
5810 close(fds[1]);
5812 again:
5813 len = read(fds[0], &status, 1);
5814 if (len == -1 && (errno == EINTR))
5815 goto again;
5817 if (len != 1)
5818 exit(1);
5819 else if (status == 1) {
5820 fprintf(stderr, "Could not acquire pidfile\n");
5821 exit(1);
5822 } else
5823 exit(0);
5824 } else if (pid < 0)
5825 exit(1);
5827 setsid();
5829 pid = fork();
5830 if (pid > 0)
5831 exit(0);
5832 else if (pid < 0)
5833 exit(1);
5835 umask(027);
5837 signal(SIGTSTP, SIG_IGN);
5838 signal(SIGTTOU, SIG_IGN);
5839 signal(SIGTTIN, SIG_IGN);
5842 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5843 if (daemonize) {
5844 uint8_t status = 1;
5845 write(fds[1], &status, 1);
5846 } else
5847 fprintf(stderr, "Could not acquire pid file\n");
5848 exit(1);
5850 #endif
5852 #ifdef CONFIG_KQEMU
5853 if (smp_cpus > 1)
5854 kqemu_allowed = 0;
5855 #endif
5856 if (qemu_init_main_loop()) {
5857 fprintf(stderr, "qemu_init_main_loop failed\n");
5858 exit(1);
5860 linux_boot = (kernel_filename != NULL);
5862 if (!linux_boot && *kernel_cmdline != '\0') {
5863 fprintf(stderr, "-append only allowed with -kernel option\n");
5864 exit(1);
5867 if (!linux_boot && initrd_filename != NULL) {
5868 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5869 exit(1);
5872 #ifndef _WIN32
5873 /* Win32 doesn't support line-buffering and requires size >= 2 */
5874 setvbuf(stdout, NULL, _IOLBF, 0);
5875 #endif
5877 init_timers();
5878 if (init_timer_alarm() < 0) {
5879 fprintf(stderr, "could not initialize alarm timer\n");
5880 exit(1);
5882 if (use_icount && icount_time_shift < 0) {
5883 use_icount = 2;
5884 /* 125MIPS seems a reasonable initial guess at the guest speed.
5885 It will be corrected fairly quickly anyway. */
5886 icount_time_shift = 3;
5887 init_icount_adjust();
5890 #ifdef _WIN32
5891 socket_init();
5892 #endif
5894 /* init network clients */
5895 if (nb_net_clients == 0) {
5896 /* if no clients, we use a default config */
5897 net_clients[nb_net_clients++] = "nic";
5898 #ifdef CONFIG_SLIRP
5899 net_clients[nb_net_clients++] = "user";
5900 #endif
5903 for(i = 0;i < nb_net_clients; i++) {
5904 if (net_client_parse(net_clients[i]) < 0)
5905 exit(1);
5908 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5909 net_set_boot_mask(net_boot);
5911 net_client_check();
5913 /* init the bluetooth world */
5914 if (foreach_device_config(DEV_BT, bt_parse))
5915 exit(1);
5917 /* init the memory */
5918 if (ram_size == 0)
5919 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5921 #ifdef CONFIG_KQEMU
5922 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5923 guest ram allocation. It needs to go away. */
5924 if (kqemu_allowed) {
5925 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5926 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5927 if (!kqemu_phys_ram_base) {
5928 fprintf(stderr, "Could not allocate physical memory\n");
5929 exit(1);
5932 #endif
5934 /* init the dynamic translator */
5935 cpu_exec_init_all(tb_size * 1024 * 1024);
5937 bdrv_init();
5939 /* we always create the cdrom drive, even if no disk is there */
5940 drive_add(NULL, CDROM_ALIAS);
5942 /* we always create at least one floppy */
5943 drive_add(NULL, FD_ALIAS, 0);
5945 /* we always create one sd slot, even if no card is in it */
5946 drive_add(NULL, SD_ALIAS);
5948 /* open the virtual block devices */
5949 if (snapshot)
5950 qemu_opts_foreach(&drive_opt_list, drive_enable_snapshot, NULL, 0);
5951 if (qemu_opts_foreach(&drive_opt_list, drive_init_func, machine, 1) != 0)
5952 exit(1);
5954 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5955 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5957 #ifndef _WIN32
5958 /* must be after terminal init, SDL library changes signal handlers */
5959 sighandler_setup();
5960 #endif
5962 /* Maintain compatibility with multiple stdio monitors */
5963 if (!strcmp(monitor_device,"stdio")) {
5964 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5965 const char *devname = serial_devices[i];
5966 if (devname && !strcmp(devname,"mon:stdio")) {
5967 monitor_device = NULL;
5968 break;
5969 } else if (devname && !strcmp(devname,"stdio")) {
5970 monitor_device = NULL;
5971 serial_devices[i] = "mon:stdio";
5972 break;
5977 if (nb_numa_nodes > 0) {
5978 int i;
5980 if (nb_numa_nodes > smp_cpus) {
5981 nb_numa_nodes = smp_cpus;
5984 /* If no memory size if given for any node, assume the default case
5985 * and distribute the available memory equally across all nodes
5987 for (i = 0; i < nb_numa_nodes; i++) {
5988 if (node_mem[i] != 0)
5989 break;
5991 if (i == nb_numa_nodes) {
5992 uint64_t usedmem = 0;
5994 /* On Linux, the each node's border has to be 8MB aligned,
5995 * the final node gets the rest.
5997 for (i = 0; i < nb_numa_nodes - 1; i++) {
5998 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5999 usedmem += node_mem[i];
6001 node_mem[i] = ram_size - usedmem;
6004 for (i = 0; i < nb_numa_nodes; i++) {
6005 if (node_cpumask[i] != 0)
6006 break;
6008 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6009 * must cope with this anyway, because there are BIOSes out there in
6010 * real machines which also use this scheme.
6012 if (i == nb_numa_nodes) {
6013 for (i = 0; i < smp_cpus; i++) {
6014 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6019 if (kvm_enabled()) {
6020 int ret;
6022 ret = kvm_init(smp_cpus);
6023 if (ret < 0) {
6024 #if defined(KVM_UPSTREAM) || defined(NO_CPU_EMULATION)
6025 fprintf(stderr, "failed to initialize KVM\n");
6026 exit(1);
6027 #endif
6028 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
6029 kvm_allowed = 0;
6033 if (monitor_device) {
6034 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6035 if (!monitor_hd) {
6036 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6037 exit(1);
6041 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6042 const char *devname = serial_devices[i];
6043 if (devname && strcmp(devname, "none")) {
6044 char label[32];
6045 snprintf(label, sizeof(label), "serial%d", i);
6046 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6047 if (!serial_hds[i]) {
6048 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6049 devname);
6050 exit(1);
6055 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6056 const char *devname = parallel_devices[i];
6057 if (devname && strcmp(devname, "none")) {
6058 char label[32];
6059 snprintf(label, sizeof(label), "parallel%d", i);
6060 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6061 if (!parallel_hds[i]) {
6062 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6063 devname);
6064 exit(1);
6069 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6070 const char *devname = virtio_consoles[i];
6071 if (devname && strcmp(devname, "none")) {
6072 char label[32];
6073 snprintf(label, sizeof(label), "virtcon%d", i);
6074 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6075 if (!virtcon_hds[i]) {
6076 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6077 devname);
6078 exit(1);
6083 module_call_init(MODULE_INIT_DEVICE);
6085 if (machine->compat_props) {
6086 qdev_prop_register_compat(machine->compat_props);
6088 machine->init(ram_size, boot_devices,
6089 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6092 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6093 for (i = 0; i < nb_numa_nodes; i++) {
6094 if (node_cpumask[i] & (1 << env->cpu_index)) {
6095 env->numa_node = i;
6100 current_machine = machine;
6102 /* init USB devices */
6103 if (usb_enabled) {
6104 foreach_device_config(DEV_USB, usb_parse);
6107 /* init generic devices */
6108 if (foreach_device_config(DEV_GENERIC, generic_parse))
6109 exit(1);
6111 if (!display_state)
6112 dumb_display_init();
6113 /* just use the first displaystate for the moment */
6114 ds = display_state;
6116 if (display_type == DT_DEFAULT) {
6117 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6118 display_type = DT_SDL;
6119 #else
6120 display_type = DT_VNC;
6121 vnc_display = "localhost:0,to=99";
6122 show_vnc_port = 1;
6123 #endif
6127 switch (display_type) {
6128 case DT_NOGRAPHIC:
6129 break;
6130 #if defined(CONFIG_CURSES)
6131 case DT_CURSES:
6132 curses_display_init(ds, full_screen);
6133 break;
6134 #endif
6135 #if defined(CONFIG_SDL)
6136 case DT_SDL:
6137 sdl_display_init(ds, full_screen, no_frame);
6138 break;
6139 #elif defined(CONFIG_COCOA)
6140 case DT_SDL:
6141 cocoa_display_init(ds, full_screen);
6142 break;
6143 #endif
6144 case DT_VNC:
6145 vnc_display_init(ds);
6146 if (vnc_display_open(ds, vnc_display) < 0)
6147 exit(1);
6149 if (show_vnc_port) {
6150 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6152 break;
6153 default:
6154 break;
6156 dpy_resize(ds);
6158 dcl = ds->listeners;
6159 while (dcl != NULL) {
6160 if (dcl->dpy_refresh != NULL) {
6161 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6162 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6164 dcl = dcl->next;
6167 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6168 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6169 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6172 text_consoles_set_display(display_state);
6173 qemu_chr_initial_reset();
6175 if (monitor_device && monitor_hd)
6176 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6178 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6179 const char *devname = serial_devices[i];
6180 if (devname && strcmp(devname, "none")) {
6181 if (strstart(devname, "vc", 0))
6182 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6186 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6187 const char *devname = parallel_devices[i];
6188 if (devname && strcmp(devname, "none")) {
6189 if (strstart(devname, "vc", 0))
6190 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6194 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6195 const char *devname = virtio_consoles[i];
6196 if (virtcon_hds[i] && devname) {
6197 if (strstart(devname, "vc", 0))
6198 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6202 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6203 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6204 gdbstub_dev);
6205 exit(1);
6208 if (loadvm)
6209 do_loadvm(cur_mon, loadvm);
6211 if (incoming) {
6212 autostart = 0;
6213 qemu_start_incoming_migration(incoming);
6216 else if (autostart)
6217 vm_start();
6219 #ifndef _WIN32
6220 if (daemonize) {
6221 uint8_t status = 0;
6222 ssize_t len;
6224 again1:
6225 len = write(fds[1], &status, 1);
6226 if (len == -1 && (errno == EINTR))
6227 goto again1;
6229 if (len != 1)
6230 exit(1);
6232 chdir("/");
6233 TFR(fd = open("/dev/null", O_RDWR));
6234 if (fd == -1)
6235 exit(1);
6238 if (run_as) {
6239 pwd = getpwnam(run_as);
6240 if (!pwd) {
6241 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6242 exit(1);
6246 if (chroot_dir) {
6247 if (chroot(chroot_dir) < 0) {
6248 fprintf(stderr, "chroot failed\n");
6249 exit(1);
6251 chdir("/");
6254 if (run_as) {
6255 if (setgid(pwd->pw_gid) < 0) {
6256 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6257 exit(1);
6259 if (setuid(pwd->pw_uid) < 0) {
6260 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6261 exit(1);
6263 if (setuid(0) != -1) {
6264 fprintf(stderr, "Dropping privileges failed\n");
6265 exit(1);
6269 if (daemonize) {
6270 dup2(fd, 0);
6271 dup2(fd, 1);
6272 dup2(fd, 2);
6274 close(fd);
6276 #endif
6278 main_loop();
6279 quit_timers();
6280 net_cleanup();
6282 return 0;