make qemu-kvm option handling target-independent
[qemu-kvm.git] / kvm-all.c
blob4c8aebde76f07186a40a8d15e45f5065fe19bbd8
1 /*
2 * QEMU KVM support
4 * Copyright IBM, Corp. 2008
5 * Red Hat, Inc. 2008
7 * Authors:
8 * Anthony Liguori <aliguori@us.ibm.com>
9 * Glauber Costa <gcosta@redhat.com>
11 * This work is licensed under the terms of the GNU GPL, version 2 or later.
12 * See the COPYING file in the top-level directory.
16 #include <sys/types.h>
17 #include <sys/ioctl.h>
18 #include <sys/mman.h>
19 #include <stdarg.h>
21 #include <linux/kvm.h>
23 #include "qemu-common.h"
24 #include "qemu-barrier.h"
25 #include "sysemu.h"
26 #include "hw/hw.h"
27 #include "gdbstub.h"
28 #include "kvm.h"
29 #include "bswap.h"
31 /* This check must be after config-host.h is included */
32 #ifdef CONFIG_EVENTFD
33 #include <sys/eventfd.h>
34 #endif
36 /* KVM uses PAGE_SIZE in it's definition of COALESCED_MMIO_MAX */
37 #define PAGE_SIZE TARGET_PAGE_SIZE
39 //#define DEBUG_KVM
41 #ifdef DEBUG_KVM
42 #define DPRINTF(fmt, ...) \
43 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
44 #else
45 #define DPRINTF(fmt, ...) \
46 do { } while (0)
47 #endif
49 typedef struct KVMSlot
51 target_phys_addr_t start_addr;
52 ram_addr_t memory_size;
53 ram_addr_t phys_offset;
54 int slot;
55 int flags;
56 } KVMSlot;
58 typedef struct kvm_dirty_log KVMDirtyLog;
60 struct KVMState
62 KVMSlot slots[32];
63 int fd;
64 int vmfd;
65 int coalesced_mmio;
66 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
67 bool coalesced_flush_in_progress;
68 int broken_set_mem_region;
69 int migration_log;
70 int vcpu_events;
71 int robust_singlestep;
72 int debugregs;
73 #ifdef KVM_CAP_SET_GUEST_DEBUG
74 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
75 #endif
76 int irqchip_in_kernel;
77 int pit_in_kernel;
78 int xsave, xcrs;
79 int many_ioeventfds;
80 int pit_state2;
82 int irqchip_inject_ioctl;
83 #ifdef KVM_CAP_IRQ_ROUTING
84 struct kvm_irq_routing *irq_routes;
85 int nr_allocated_irq_routes;
86 #endif
87 void *used_gsi_bitmap;
88 int max_gsi;
91 KVMState *kvm_state;
93 static const KVMCapabilityInfo kvm_required_capabilites[] = {
94 KVM_CAP_INFO(USER_MEMORY),
95 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
96 KVM_CAP_LAST_INFO
99 static KVMSlot *kvm_alloc_slot(KVMState *s)
101 int i;
103 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
104 if (s->slots[i].memory_size == 0) {
105 return &s->slots[i];
109 fprintf(stderr, "%s: no free slot available\n", __func__);
110 abort();
113 static KVMSlot *kvm_lookup_matching_slot(KVMState *s,
114 target_phys_addr_t start_addr,
115 target_phys_addr_t end_addr)
117 int i;
119 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
120 KVMSlot *mem = &s->slots[i];
122 if (start_addr == mem->start_addr &&
123 end_addr == mem->start_addr + mem->memory_size) {
124 return mem;
128 return NULL;
132 * Find overlapping slot with lowest start address
134 static KVMSlot *kvm_lookup_overlapping_slot(KVMState *s,
135 target_phys_addr_t start_addr,
136 target_phys_addr_t end_addr)
138 KVMSlot *found = NULL;
139 int i;
141 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
142 KVMSlot *mem = &s->slots[i];
144 if (mem->memory_size == 0 ||
145 (found && found->start_addr < mem->start_addr)) {
146 continue;
149 if (end_addr > mem->start_addr &&
150 start_addr < mem->start_addr + mem->memory_size) {
151 found = mem;
155 return found;
158 int kvm_physical_memory_addr_from_ram(KVMState *s, ram_addr_t ram_addr,
159 target_phys_addr_t *phys_addr)
161 int i;
163 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
164 KVMSlot *mem = &s->slots[i];
166 if (ram_addr >= mem->phys_offset &&
167 ram_addr < mem->phys_offset + mem->memory_size) {
168 *phys_addr = mem->start_addr + (ram_addr - mem->phys_offset);
169 return 1;
173 return 0;
176 static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)
178 struct kvm_userspace_memory_region mem;
180 mem.slot = slot->slot;
181 mem.guest_phys_addr = slot->start_addr;
182 mem.memory_size = slot->memory_size;
183 mem.userspace_addr = (unsigned long)qemu_safe_ram_ptr(slot->phys_offset);
184 mem.flags = slot->flags;
185 if (s->migration_log) {
186 mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;
188 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
191 static void kvm_reset_vcpu(void *opaque)
193 CPUState *env = opaque;
195 kvm_arch_reset_vcpu(env);
198 int kvm_irqchip_in_kernel(void)
200 return kvm_state->irqchip_in_kernel;
203 int kvm_pit_in_kernel(void)
205 return kvm_state->pit_in_kernel;
208 int kvm_init_vcpu(CPUState *env)
210 KVMState *s = kvm_state;
211 long mmap_size;
212 int ret;
214 DPRINTF("kvm_init_vcpu\n");
216 ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, env->cpu_index);
217 if (ret < 0) {
218 DPRINTF("kvm_create_vcpu failed\n");
219 goto err;
222 env->kvm_fd = ret;
223 env->kvm_state = s;
224 env->kvm_vcpu_dirty = 1;
226 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
227 if (mmap_size < 0) {
228 ret = mmap_size;
229 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
230 goto err;
233 env->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
234 env->kvm_fd, 0);
235 if (env->kvm_run == MAP_FAILED) {
236 ret = -errno;
237 DPRINTF("mmap'ing vcpu state failed\n");
238 goto err;
241 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
242 s->coalesced_mmio_ring =
243 (void *)env->kvm_run + s->coalesced_mmio * PAGE_SIZE;
246 ret = kvm_arch_init_vcpu(env);
247 if (ret == 0) {
248 qemu_register_reset(kvm_reset_vcpu, env);
249 kvm_arch_reset_vcpu(env);
251 err:
252 return ret;
256 * dirty pages logging control
259 static int kvm_mem_flags(KVMState *s, bool log_dirty)
261 return log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
264 static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
266 KVMState *s = kvm_state;
267 int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
268 int old_flags;
270 old_flags = mem->flags;
272 flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty);
273 mem->flags = flags;
275 /* If nothing changed effectively, no need to issue ioctl */
276 if (s->migration_log) {
277 flags |= KVM_MEM_LOG_DIRTY_PAGES;
280 if (flags == old_flags) {
281 return 0;
284 return kvm_set_user_memory_region(s, mem);
287 static int kvm_dirty_pages_log_change(target_phys_addr_t phys_addr,
288 ram_addr_t size, bool log_dirty)
290 KVMState *s = kvm_state;
291 KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
293 if (mem == NULL) {
294 fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
295 TARGET_FMT_plx "\n", __func__, phys_addr,
296 (target_phys_addr_t)(phys_addr + size - 1));
297 return -EINVAL;
299 return kvm_slot_dirty_pages_log_change(mem, log_dirty);
302 static int kvm_log_start(CPUPhysMemoryClient *client,
303 target_phys_addr_t phys_addr, ram_addr_t size)
305 return kvm_dirty_pages_log_change(phys_addr, size, true);
308 static int kvm_log_stop(CPUPhysMemoryClient *client,
309 target_phys_addr_t phys_addr, ram_addr_t size)
311 return kvm_dirty_pages_log_change(phys_addr, size, false);
314 static int kvm_set_migration_log(int enable)
316 KVMState *s = kvm_state;
317 KVMSlot *mem;
318 int i, err;
320 s->migration_log = enable;
322 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
323 mem = &s->slots[i];
325 if (!mem->memory_size) {
326 continue;
328 if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
329 continue;
331 err = kvm_set_user_memory_region(s, mem);
332 if (err) {
333 return err;
336 return 0;
339 /* get kvm's dirty pages bitmap and update qemu's */
340 static int kvm_get_dirty_pages_log_range(unsigned long start_addr,
341 unsigned long *bitmap,
342 unsigned long offset,
343 unsigned long mem_size)
345 unsigned int i, j;
346 unsigned long page_number, addr, addr1, c;
347 ram_addr_t ram_addr;
348 unsigned int len = ((mem_size / TARGET_PAGE_SIZE) + HOST_LONG_BITS - 1) /
349 HOST_LONG_BITS;
352 * bitmap-traveling is faster than memory-traveling (for addr...)
353 * especially when most of the memory is not dirty.
355 for (i = 0; i < len; i++) {
356 if (bitmap[i] != 0) {
357 c = leul_to_cpu(bitmap[i]);
358 do {
359 j = ffsl(c) - 1;
360 c &= ~(1ul << j);
361 page_number = i * HOST_LONG_BITS + j;
362 addr1 = page_number * TARGET_PAGE_SIZE;
363 addr = offset + addr1;
364 ram_addr = cpu_get_physical_page_desc(addr);
365 cpu_physical_memory_set_dirty(ram_addr);
366 } while (c != 0);
369 return 0;
372 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
375 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
376 * This function updates qemu's dirty bitmap using cpu_physical_memory_set_dirty().
377 * This means all bits are set to dirty.
379 * @start_add: start of logged region.
380 * @end_addr: end of logged region.
382 static int kvm_physical_sync_dirty_bitmap(target_phys_addr_t start_addr,
383 target_phys_addr_t end_addr)
385 KVMState *s = kvm_state;
386 unsigned long size, allocated_size = 0;
387 KVMDirtyLog d;
388 KVMSlot *mem;
389 int ret = 0;
391 d.dirty_bitmap = NULL;
392 while (start_addr < end_addr) {
393 mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
394 if (mem == NULL) {
395 break;
398 /* XXX bad kernel interface alert
399 * For dirty bitmap, kernel allocates array of size aligned to
400 * bits-per-long. But for case when the kernel is 64bits and
401 * the userspace is 32bits, userspace can't align to the same
402 * bits-per-long, since sizeof(long) is different between kernel
403 * and user space. This way, userspace will provide buffer which
404 * may be 4 bytes less than the kernel will use, resulting in
405 * userspace memory corruption (which is not detectable by valgrind
406 * too, in most cases).
407 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
408 * a hope that sizeof(long) wont become >8 any time soon.
410 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
411 /*HOST_LONG_BITS*/ 64) / 8;
412 if (!d.dirty_bitmap) {
413 d.dirty_bitmap = g_malloc(size);
414 } else if (size > allocated_size) {
415 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
417 allocated_size = size;
418 memset(d.dirty_bitmap, 0, allocated_size);
420 d.slot = mem->slot;
422 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
423 DPRINTF("ioctl failed %d\n", errno);
424 ret = -1;
425 break;
428 kvm_get_dirty_pages_log_range(mem->start_addr, d.dirty_bitmap,
429 mem->start_addr, mem->memory_size);
430 start_addr = mem->start_addr + mem->memory_size;
432 g_free(d.dirty_bitmap);
434 return ret;
437 int kvm_coalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
439 int ret = -ENOSYS;
440 KVMState *s = kvm_state;
442 if (s->coalesced_mmio) {
443 struct kvm_coalesced_mmio_zone zone;
445 zone.addr = start;
446 zone.size = size;
448 ret = kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
451 return ret;
454 int kvm_uncoalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
456 int ret = -ENOSYS;
457 KVMState *s = kvm_state;
459 if (s->coalesced_mmio) {
460 struct kvm_coalesced_mmio_zone zone;
462 zone.addr = start;
463 zone.size = size;
465 ret = kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
468 return ret;
471 int kvm_check_extension(KVMState *s, unsigned int extension)
473 int ret;
475 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
476 if (ret < 0) {
477 ret = 0;
480 return ret;
483 static int kvm_check_many_ioeventfds(void)
485 /* Userspace can use ioeventfd for io notification. This requires a host
486 * that supports eventfd(2) and an I/O thread; since eventfd does not
487 * support SIGIO it cannot interrupt the vcpu.
489 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
490 * can avoid creating too many ioeventfds.
492 #if defined(CONFIG_EVENTFD)
493 int ioeventfds[7];
494 int i, ret = 0;
495 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
496 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
497 if (ioeventfds[i] < 0) {
498 break;
500 ret = kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, true);
501 if (ret < 0) {
502 close(ioeventfds[i]);
503 break;
507 /* Decide whether many devices are supported or not */
508 ret = i == ARRAY_SIZE(ioeventfds);
510 while (i-- > 0) {
511 kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, false);
512 close(ioeventfds[i]);
514 return ret;
515 #else
516 return 0;
517 #endif
520 static const KVMCapabilityInfo *
521 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
523 while (list->name) {
524 if (!kvm_check_extension(s, list->value)) {
525 return list;
527 list++;
529 return NULL;
532 static void kvm_set_phys_mem(target_phys_addr_t start_addr, ram_addr_t size,
533 ram_addr_t phys_offset, bool log_dirty)
535 KVMState *s = kvm_state;
536 ram_addr_t flags = phys_offset & ~TARGET_PAGE_MASK;
537 KVMSlot *mem, old;
538 int err;
540 /* kvm works in page size chunks, but the function may be called
541 with sub-page size and unaligned start address. */
542 size = TARGET_PAGE_ALIGN(size);
543 start_addr = TARGET_PAGE_ALIGN(start_addr);
545 /* KVM does not support read-only slots */
546 phys_offset &= ~IO_MEM_ROM;
548 while (1) {
549 mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
550 if (!mem) {
551 break;
554 if (flags < IO_MEM_UNASSIGNED && start_addr >= mem->start_addr &&
555 (start_addr + size <= mem->start_addr + mem->memory_size) &&
556 (phys_offset - start_addr == mem->phys_offset - mem->start_addr)) {
557 /* The new slot fits into the existing one and comes with
558 * identical parameters - update flags and done. */
559 kvm_slot_dirty_pages_log_change(mem, log_dirty);
560 return;
563 old = *mem;
565 /* unregister the overlapping slot */
566 mem->memory_size = 0;
567 err = kvm_set_user_memory_region(s, mem);
568 if (err) {
569 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
570 __func__, strerror(-err));
571 abort();
574 /* Workaround for older KVM versions: we can't join slots, even not by
575 * unregistering the previous ones and then registering the larger
576 * slot. We have to maintain the existing fragmentation. Sigh.
578 * This workaround assumes that the new slot starts at the same
579 * address as the first existing one. If not or if some overlapping
580 * slot comes around later, we will fail (not seen in practice so far)
581 * - and actually require a recent KVM version. */
582 if (s->broken_set_mem_region &&
583 old.start_addr == start_addr && old.memory_size < size &&
584 flags < IO_MEM_UNASSIGNED) {
585 mem = kvm_alloc_slot(s);
586 mem->memory_size = old.memory_size;
587 mem->start_addr = old.start_addr;
588 mem->phys_offset = old.phys_offset;
589 mem->flags = kvm_mem_flags(s, log_dirty);
591 err = kvm_set_user_memory_region(s, mem);
592 if (err) {
593 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
594 strerror(-err));
595 abort();
598 start_addr += old.memory_size;
599 phys_offset += old.memory_size;
600 size -= old.memory_size;
601 continue;
604 /* register prefix slot */
605 if (old.start_addr < start_addr) {
606 mem = kvm_alloc_slot(s);
607 mem->memory_size = start_addr - old.start_addr;
608 mem->start_addr = old.start_addr;
609 mem->phys_offset = old.phys_offset;
610 mem->flags = kvm_mem_flags(s, log_dirty);
612 err = kvm_set_user_memory_region(s, mem);
613 if (err) {
614 fprintf(stderr, "%s: error registering prefix slot: %s\n",
615 __func__, strerror(-err));
616 #ifdef TARGET_PPC
617 fprintf(stderr, "%s: This is probably because your kernel's " \
618 "PAGE_SIZE is too big. Please try to use 4k " \
619 "PAGE_SIZE!\n", __func__);
620 #endif
621 abort();
625 /* register suffix slot */
626 if (old.start_addr + old.memory_size > start_addr + size) {
627 ram_addr_t size_delta;
629 mem = kvm_alloc_slot(s);
630 mem->start_addr = start_addr + size;
631 size_delta = mem->start_addr - old.start_addr;
632 mem->memory_size = old.memory_size - size_delta;
633 mem->phys_offset = old.phys_offset + size_delta;
634 mem->flags = kvm_mem_flags(s, log_dirty);
636 err = kvm_set_user_memory_region(s, mem);
637 if (err) {
638 fprintf(stderr, "%s: error registering suffix slot: %s\n",
639 __func__, strerror(-err));
640 abort();
645 /* in case the KVM bug workaround already "consumed" the new slot */
646 if (!size) {
647 return;
649 /* KVM does not need to know about this memory */
650 if (flags >= IO_MEM_UNASSIGNED) {
651 return;
653 mem = kvm_alloc_slot(s);
654 mem->memory_size = size;
655 mem->start_addr = start_addr;
656 mem->phys_offset = phys_offset;
657 mem->flags = kvm_mem_flags(s, log_dirty);
659 err = kvm_set_user_memory_region(s, mem);
660 if (err) {
661 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
662 strerror(-err));
663 abort();
667 static void kvm_client_set_memory(struct CPUPhysMemoryClient *client,
668 target_phys_addr_t start_addr,
669 ram_addr_t size, ram_addr_t phys_offset,
670 bool log_dirty)
672 kvm_set_phys_mem(start_addr, size, phys_offset, log_dirty);
675 static int kvm_client_sync_dirty_bitmap(struct CPUPhysMemoryClient *client,
676 target_phys_addr_t start_addr,
677 target_phys_addr_t end_addr)
679 return kvm_physical_sync_dirty_bitmap(start_addr, end_addr);
682 static int kvm_client_migration_log(struct CPUPhysMemoryClient *client,
683 int enable)
685 return kvm_set_migration_log(enable);
688 static CPUPhysMemoryClient kvm_cpu_phys_memory_client = {
689 .set_memory = kvm_client_set_memory,
690 .sync_dirty_bitmap = kvm_client_sync_dirty_bitmap,
691 .migration_log = kvm_client_migration_log,
692 .log_start = kvm_log_start,
693 .log_stop = kvm_log_stop,
696 static void kvm_handle_interrupt(CPUState *env, int mask)
698 env->interrupt_request |= mask;
700 if (!qemu_cpu_is_self(env)) {
701 qemu_cpu_kick(env);
705 int kvm_init(void)
707 static const char upgrade_note[] =
708 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
709 "(see http://sourceforge.net/projects/kvm).\n";
710 KVMState *s;
711 const KVMCapabilityInfo *missing_cap;
712 int ret;
713 int i;
715 s = g_malloc0(sizeof(KVMState));
717 #ifdef KVM_CAP_SET_GUEST_DEBUG
718 QTAILQ_INIT(&s->kvm_sw_breakpoints);
719 #endif
720 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
721 s->slots[i].slot = i;
723 s->vmfd = -1;
724 s->fd = qemu_open("/dev/kvm", O_RDWR);
725 if (s->fd == -1) {
726 fprintf(stderr, "Could not access KVM kernel module: %m\n");
727 ret = -errno;
728 goto err;
731 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
732 if (ret < KVM_API_VERSION) {
733 if (ret > 0) {
734 ret = -EINVAL;
736 fprintf(stderr, "kvm version too old\n");
737 goto err;
740 if (ret > KVM_API_VERSION) {
741 ret = -EINVAL;
742 fprintf(stderr, "kvm version not supported\n");
743 goto err;
746 s->vmfd = kvm_ioctl(s, KVM_CREATE_VM, 0);
747 if (s->vmfd < 0) {
748 #ifdef TARGET_S390X
749 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
750 "your host kernel command line\n");
751 #endif
752 goto err;
755 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
756 if (!missing_cap) {
757 missing_cap =
758 kvm_check_extension_list(s, kvm_arch_required_capabilities);
760 if (missing_cap) {
761 ret = -EINVAL;
762 fprintf(stderr, "kvm does not support %s\n%s",
763 missing_cap->name, upgrade_note);
764 goto err;
767 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
769 s->broken_set_mem_region = 1;
770 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
771 if (ret > 0) {
772 s->broken_set_mem_region = 0;
775 #ifdef KVM_CAP_VCPU_EVENTS
776 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
777 #endif
779 s->robust_singlestep =
780 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
782 #ifdef KVM_CAP_DEBUGREGS
783 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
784 #endif
786 #ifdef KVM_CAP_XSAVE
787 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
788 #endif
790 #ifdef KVM_CAP_XCRS
791 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
792 #endif
794 s->pit_state2 = 0;
795 #ifdef KVM_CAP_PIT_STATE2
796 s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
797 #endif
799 s->pit_in_kernel = kvm_pit;
801 ret = kvm_arch_init(s);
802 if (ret < 0) {
803 goto err;
806 kvm_state = s;
807 cpu_register_phys_memory_client(&kvm_cpu_phys_memory_client);
809 s->many_ioeventfds = kvm_check_many_ioeventfds();
811 ret = kvm_create_irqchip(s);
812 if (ret < 0) {
813 return ret;
816 cpu_interrupt_handler = kvm_handle_interrupt;
818 return 0;
820 err:
821 if (s) {
822 if (s->vmfd != -1) {
823 close(s->vmfd);
825 if (s->fd != -1) {
826 close(s->fd);
829 g_free(s);
831 return ret;
834 static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
835 uint32_t count)
837 int i;
838 uint8_t *ptr = data;
840 for (i = 0; i < count; i++) {
841 if (direction == KVM_EXIT_IO_IN) {
842 switch (size) {
843 case 1:
844 stb_p(ptr, cpu_inb(port));
845 break;
846 case 2:
847 stw_p(ptr, cpu_inw(port));
848 break;
849 case 4:
850 stl_p(ptr, cpu_inl(port));
851 break;
853 } else {
854 switch (size) {
855 case 1:
856 cpu_outb(port, ldub_p(ptr));
857 break;
858 case 2:
859 cpu_outw(port, lduw_p(ptr));
860 break;
861 case 4:
862 cpu_outl(port, ldl_p(ptr));
863 break;
867 ptr += size;
871 static int kvm_handle_internal_error(CPUState *env, struct kvm_run *run)
873 fprintf(stderr, "KVM internal error.");
874 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
875 int i;
877 fprintf(stderr, " Suberror: %d\n", run->internal.suberror);
878 for (i = 0; i < run->internal.ndata; ++i) {
879 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
880 i, (uint64_t)run->internal.data[i]);
882 } else {
883 fprintf(stderr, "\n");
885 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
886 fprintf(stderr, "emulation failure\n");
887 if (!kvm_arch_stop_on_emulation_error(env)) {
888 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
889 return EXCP_INTERRUPT;
892 /* FIXME: Should trigger a qmp message to let management know
893 * something went wrong.
895 return -1;
898 void kvm_flush_coalesced_mmio_buffer(void)
900 KVMState *s = kvm_state;
902 if (s->coalesced_flush_in_progress) {
903 return;
906 s->coalesced_flush_in_progress = true;
908 if (s->coalesced_mmio_ring) {
909 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
910 while (ring->first != ring->last) {
911 struct kvm_coalesced_mmio *ent;
913 ent = &ring->coalesced_mmio[ring->first];
915 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
916 smp_wmb();
917 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
921 s->coalesced_flush_in_progress = false;
924 static void do_kvm_cpu_synchronize_state(void *_env)
926 CPUState *env = _env;
928 if (!env->kvm_vcpu_dirty) {
929 kvm_arch_get_registers(env);
930 env->kvm_vcpu_dirty = 1;
934 void kvm_cpu_synchronize_state(CPUState *env)
936 if (!env->kvm_vcpu_dirty) {
937 run_on_cpu(env, do_kvm_cpu_synchronize_state, env);
941 void kvm_cpu_synchronize_post_reset(CPUState *env)
943 kvm_arch_put_registers(env, KVM_PUT_RESET_STATE);
944 env->kvm_vcpu_dirty = 0;
947 void kvm_cpu_synchronize_post_init(CPUState *env)
949 kvm_arch_put_registers(env, KVM_PUT_FULL_STATE);
950 env->kvm_vcpu_dirty = 0;
953 int kvm_cpu_exec(CPUState *env)
955 struct kvm_run *run = env->kvm_run;
956 int ret, run_ret;
958 DPRINTF("kvm_cpu_exec()\n");
960 if (kvm_arch_process_async_events(env)) {
961 env->exit_request = 0;
962 return EXCP_HLT;
965 cpu_single_env = env;
967 do {
968 if (env->kvm_vcpu_dirty) {
969 kvm_arch_put_registers(env, KVM_PUT_RUNTIME_STATE);
970 env->kvm_vcpu_dirty = 0;
973 kvm_arch_pre_run(env, run);
974 if (env->exit_request) {
975 DPRINTF("interrupt exit requested\n");
977 * KVM requires us to reenter the kernel after IO exits to complete
978 * instruction emulation. This self-signal will ensure that we
979 * leave ASAP again.
981 qemu_cpu_kick_self();
983 cpu_single_env = NULL;
984 qemu_mutex_unlock_iothread();
986 run_ret = kvm_vcpu_ioctl(env, KVM_RUN, 0);
988 qemu_mutex_lock_iothread();
989 cpu_single_env = env;
990 kvm_arch_post_run(env, run);
992 kvm_flush_coalesced_mmio_buffer();
994 if (run_ret < 0) {
995 if (run_ret == -EINTR || run_ret == -EAGAIN) {
996 DPRINTF("io window exit\n");
997 ret = EXCP_INTERRUPT;
998 break;
1000 DPRINTF("kvm run failed %s\n", strerror(-run_ret));
1001 abort();
1004 switch (run->exit_reason) {
1005 case KVM_EXIT_IO:
1006 DPRINTF("handle_io\n");
1007 kvm_handle_io(run->io.port,
1008 (uint8_t *)run + run->io.data_offset,
1009 run->io.direction,
1010 run->io.size,
1011 run->io.count);
1012 ret = 0;
1013 break;
1014 case KVM_EXIT_MMIO:
1015 DPRINTF("handle_mmio\n");
1016 cpu_physical_memory_rw(run->mmio.phys_addr,
1017 run->mmio.data,
1018 run->mmio.len,
1019 run->mmio.is_write);
1020 ret = 0;
1021 break;
1022 case KVM_EXIT_IRQ_WINDOW_OPEN:
1023 DPRINTF("irq_window_open\n");
1024 ret = EXCP_INTERRUPT;
1025 break;
1026 case KVM_EXIT_SHUTDOWN:
1027 DPRINTF("shutdown\n");
1028 qemu_system_reset_request();
1029 ret = EXCP_INTERRUPT;
1030 break;
1031 case KVM_EXIT_UNKNOWN:
1032 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1033 (uint64_t)run->hw.hardware_exit_reason);
1034 ret = -1;
1035 break;
1036 case KVM_EXIT_INTERNAL_ERROR:
1037 ret = kvm_handle_internal_error(env, run);
1038 break;
1039 default:
1040 DPRINTF("kvm_arch_handle_exit\n");
1041 ret = kvm_arch_handle_exit(env, run);
1042 break;
1044 } while (ret == 0);
1046 if (ret < 0) {
1047 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1048 vm_stop(RUN_STATE_INTERNAL_ERROR);
1051 env->exit_request = 0;
1052 cpu_single_env = NULL;
1053 return ret;
1056 int kvm_ioctl(KVMState *s, int type, ...)
1058 int ret;
1059 void *arg;
1060 va_list ap;
1062 va_start(ap, type);
1063 arg = va_arg(ap, void *);
1064 va_end(ap);
1066 ret = ioctl(s->fd, type, arg);
1067 if (ret == -1) {
1068 ret = -errno;
1070 return ret;
1073 int kvm_vm_ioctl(KVMState *s, int type, ...)
1075 int ret;
1076 void *arg;
1077 va_list ap;
1079 va_start(ap, type);
1080 arg = va_arg(ap, void *);
1081 va_end(ap);
1083 ret = ioctl(s->vmfd, type, arg);
1084 if (ret == -1) {
1085 ret = -errno;
1087 return ret;
1090 int kvm_vcpu_ioctl(CPUState *env, int type, ...)
1092 int ret;
1093 void *arg;
1094 va_list ap;
1096 va_start(ap, type);
1097 arg = va_arg(ap, void *);
1098 va_end(ap);
1100 ret = ioctl(env->kvm_fd, type, arg);
1101 if (ret == -1) {
1102 ret = -errno;
1104 return ret;
1107 int kvm_has_sync_mmu(void)
1109 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1112 int kvm_has_vcpu_events(void)
1114 return kvm_state->vcpu_events;
1117 int kvm_has_robust_singlestep(void)
1119 return kvm_state->robust_singlestep;
1122 int kvm_has_debugregs(void)
1124 return kvm_state->debugregs;
1127 int kvm_has_xsave(void)
1129 return kvm_state->xsave;
1132 int kvm_has_xcrs(void)
1134 return kvm_state->xcrs;
1137 int kvm_has_pit_state2(void)
1139 return kvm_state->pit_state2;
1142 int kvm_has_many_ioeventfds(void)
1144 if (!kvm_enabled()) {
1145 return 0;
1147 return kvm_state->many_ioeventfds;
1150 int kvm_allows_irq0_override(void)
1152 return !kvm_enabled() || !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
1155 void kvm_setup_guest_memory(void *start, size_t size)
1157 if (!kvm_has_sync_mmu()) {
1158 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1160 if (ret) {
1161 perror("qemu_madvise");
1162 fprintf(stderr,
1163 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1164 exit(1);
1169 #ifdef KVM_CAP_SET_GUEST_DEBUG
1170 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *env,
1171 target_ulong pc)
1173 struct kvm_sw_breakpoint *bp;
1175 QTAILQ_FOREACH(bp, &env->kvm_state->kvm_sw_breakpoints, entry) {
1176 if (bp->pc == pc) {
1177 return bp;
1180 return NULL;
1183 int kvm_sw_breakpoints_active(CPUState *env)
1185 return !QTAILQ_EMPTY(&env->kvm_state->kvm_sw_breakpoints);
1188 struct kvm_set_guest_debug_data {
1189 struct kvm_guest_debug dbg;
1190 CPUState *env;
1191 int err;
1194 static void kvm_invoke_set_guest_debug(void *data)
1196 struct kvm_set_guest_debug_data *dbg_data = data;
1197 CPUState *env = dbg_data->env;
1199 dbg_data->err = kvm_vcpu_ioctl(env, KVM_SET_GUEST_DEBUG, &dbg_data->dbg);
1202 int kvm_update_guest_debug(CPUState *env, unsigned long reinject_trap)
1204 struct kvm_set_guest_debug_data data;
1206 data.dbg.control = reinject_trap;
1208 if (env->singlestep_enabled) {
1209 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
1211 kvm_arch_update_guest_debug(env, &data.dbg);
1212 data.env = env;
1214 run_on_cpu(env, kvm_invoke_set_guest_debug, &data);
1215 return data.err;
1218 int kvm_insert_breakpoint(CPUState *current_env, target_ulong addr,
1219 target_ulong len, int type)
1221 struct kvm_sw_breakpoint *bp;
1222 CPUState *env;
1223 int err;
1225 if (type == GDB_BREAKPOINT_SW) {
1226 bp = kvm_find_sw_breakpoint(current_env, addr);
1227 if (bp) {
1228 bp->use_count++;
1229 return 0;
1232 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
1233 if (!bp) {
1234 return -ENOMEM;
1237 bp->pc = addr;
1238 bp->use_count = 1;
1239 err = kvm_arch_insert_sw_breakpoint(current_env, bp);
1240 if (err) {
1241 g_free(bp);
1242 return err;
1245 QTAILQ_INSERT_HEAD(&current_env->kvm_state->kvm_sw_breakpoints,
1246 bp, entry);
1247 } else {
1248 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
1249 if (err) {
1250 return err;
1254 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1255 err = kvm_update_guest_debug(env, 0);
1256 if (err) {
1257 return err;
1260 return 0;
1263 int kvm_remove_breakpoint(CPUState *current_env, target_ulong addr,
1264 target_ulong len, int type)
1266 struct kvm_sw_breakpoint *bp;
1267 CPUState *env;
1268 int err;
1270 if (type == GDB_BREAKPOINT_SW) {
1271 bp = kvm_find_sw_breakpoint(current_env, addr);
1272 if (!bp) {
1273 return -ENOENT;
1276 if (bp->use_count > 1) {
1277 bp->use_count--;
1278 return 0;
1281 err = kvm_arch_remove_sw_breakpoint(current_env, bp);
1282 if (err) {
1283 return err;
1286 QTAILQ_REMOVE(&current_env->kvm_state->kvm_sw_breakpoints, bp, entry);
1287 g_free(bp);
1288 } else {
1289 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
1290 if (err) {
1291 return err;
1295 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1296 err = kvm_update_guest_debug(env, 0);
1297 if (err) {
1298 return err;
1301 return 0;
1304 void kvm_remove_all_breakpoints(CPUState *current_env)
1306 struct kvm_sw_breakpoint *bp, *next;
1307 KVMState *s = current_env->kvm_state;
1308 CPUState *env;
1310 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
1311 if (kvm_arch_remove_sw_breakpoint(current_env, bp) != 0) {
1312 /* Try harder to find a CPU that currently sees the breakpoint. */
1313 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1314 if (kvm_arch_remove_sw_breakpoint(env, bp) == 0) {
1315 break;
1320 kvm_arch_remove_all_hw_breakpoints();
1322 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1323 kvm_update_guest_debug(env, 0);
1327 #else /* !KVM_CAP_SET_GUEST_DEBUG */
1329 int kvm_update_guest_debug(CPUState *env, unsigned long reinject_trap)
1331 return -EINVAL;
1334 int kvm_insert_breakpoint(CPUState *current_env, target_ulong addr,
1335 target_ulong len, int type)
1337 return -EINVAL;
1340 int kvm_remove_breakpoint(CPUState *current_env, target_ulong addr,
1341 target_ulong len, int type)
1343 return -EINVAL;
1346 void kvm_remove_all_breakpoints(CPUState *current_env)
1349 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
1351 int kvm_set_signal_mask(CPUState *env, const sigset_t *sigset)
1353 struct kvm_signal_mask *sigmask;
1354 int r;
1356 if (!sigset) {
1357 return kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, NULL);
1360 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
1362 sigmask->len = 8;
1363 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
1364 r = kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, sigmask);
1365 g_free(sigmask);
1367 return r;
1370 int kvm_set_ioeventfd_mmio_long(int fd, uint32_t addr, uint32_t val, bool assign)
1372 int ret;
1373 struct kvm_ioeventfd iofd;
1375 iofd.datamatch = val;
1376 iofd.addr = addr;
1377 iofd.len = 4;
1378 iofd.flags = KVM_IOEVENTFD_FLAG_DATAMATCH;
1379 iofd.fd = fd;
1381 if (!kvm_enabled()) {
1382 return -ENOSYS;
1385 if (!assign) {
1386 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1389 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
1391 if (ret < 0) {
1392 return -errno;
1395 return 0;
1398 int kvm_set_ioeventfd_pio_word(int fd, uint16_t addr, uint16_t val, bool assign)
1400 struct kvm_ioeventfd kick = {
1401 .datamatch = val,
1402 .addr = addr,
1403 .len = 2,
1404 .flags = KVM_IOEVENTFD_FLAG_DATAMATCH | KVM_IOEVENTFD_FLAG_PIO,
1405 .fd = fd,
1407 int r;
1408 if (!kvm_enabled()) {
1409 return -ENOSYS;
1411 if (!assign) {
1412 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1414 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
1415 if (r < 0) {
1416 return r;
1418 return 0;
1421 int kvm_set_irqfd(int gsi, int fd, bool assigned)
1423 struct kvm_irqfd irqfd = {
1424 .fd = fd,
1425 .gsi = gsi,
1426 .flags = assigned ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1428 int r;
1429 if (!kvm_enabled() || !kvm_irqchip_in_kernel())
1430 return -ENOSYS;
1432 r = kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd);
1433 if (r < 0)
1434 return r;
1435 return 0;
1438 int kvm_on_sigbus_vcpu(CPUState *env, int code, void *addr)
1440 return kvm_arch_on_sigbus_vcpu(env, code, addr);
1443 int kvm_on_sigbus(int code, void *addr)
1445 return kvm_arch_on_sigbus(code, addr);
1448 #undef PAGE_SIZE
1449 #include "qemu-kvm.c"