prep_pci: Update I/O to MemoryRegion ops
[qemu/kevin.git] / kvm-all.c
blob2cc45629212f1f12c69703b96aeca9b5dca40437
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"
30 #include "memory.h"
32 /* This check must be after config-host.h is included */
33 #ifdef CONFIG_EVENTFD
34 #include <sys/eventfd.h>
35 #endif
37 /* KVM uses PAGE_SIZE in it's definition of COALESCED_MMIO_MAX */
38 #define PAGE_SIZE TARGET_PAGE_SIZE
40 //#define DEBUG_KVM
42 #ifdef DEBUG_KVM
43 #define DPRINTF(fmt, ...) \
44 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
45 #else
46 #define DPRINTF(fmt, ...) \
47 do { } while (0)
48 #endif
50 typedef struct KVMSlot
52 target_phys_addr_t start_addr;
53 ram_addr_t memory_size;
54 void *ram;
55 int slot;
56 int flags;
57 } KVMSlot;
59 typedef struct kvm_dirty_log KVMDirtyLog;
61 struct KVMState
63 KVMSlot slots[32];
64 int fd;
65 int vmfd;
66 int coalesced_mmio;
67 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
68 bool coalesced_flush_in_progress;
69 int broken_set_mem_region;
70 int migration_log;
71 int vcpu_events;
72 int robust_singlestep;
73 int debugregs;
74 #ifdef KVM_CAP_SET_GUEST_DEBUG
75 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
76 #endif
77 int irqchip_in_kernel;
78 int pit_in_kernel;
79 int xsave, xcrs;
80 int many_ioeventfds;
83 KVMState *kvm_state;
85 static const KVMCapabilityInfo kvm_required_capabilites[] = {
86 KVM_CAP_INFO(USER_MEMORY),
87 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
88 KVM_CAP_LAST_INFO
91 static KVMSlot *kvm_alloc_slot(KVMState *s)
93 int i;
95 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
96 if (s->slots[i].memory_size == 0) {
97 return &s->slots[i];
101 fprintf(stderr, "%s: no free slot available\n", __func__);
102 abort();
105 static KVMSlot *kvm_lookup_matching_slot(KVMState *s,
106 target_phys_addr_t start_addr,
107 target_phys_addr_t end_addr)
109 int i;
111 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
112 KVMSlot *mem = &s->slots[i];
114 if (start_addr == mem->start_addr &&
115 end_addr == mem->start_addr + mem->memory_size) {
116 return mem;
120 return NULL;
124 * Find overlapping slot with lowest start address
126 static KVMSlot *kvm_lookup_overlapping_slot(KVMState *s,
127 target_phys_addr_t start_addr,
128 target_phys_addr_t end_addr)
130 KVMSlot *found = NULL;
131 int i;
133 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
134 KVMSlot *mem = &s->slots[i];
136 if (mem->memory_size == 0 ||
137 (found && found->start_addr < mem->start_addr)) {
138 continue;
141 if (end_addr > mem->start_addr &&
142 start_addr < mem->start_addr + mem->memory_size) {
143 found = mem;
147 return found;
150 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
151 target_phys_addr_t *phys_addr)
153 int i;
155 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
156 KVMSlot *mem = &s->slots[i];
158 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
159 *phys_addr = mem->start_addr + (ram - mem->ram);
160 return 1;
164 return 0;
167 static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)
169 struct kvm_userspace_memory_region mem;
171 mem.slot = slot->slot;
172 mem.guest_phys_addr = slot->start_addr;
173 mem.memory_size = slot->memory_size;
174 mem.userspace_addr = (unsigned long)slot->ram;
175 mem.flags = slot->flags;
176 if (s->migration_log) {
177 mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;
179 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
182 static void kvm_reset_vcpu(void *opaque)
184 CPUState *env = opaque;
186 kvm_arch_reset_vcpu(env);
189 int kvm_irqchip_in_kernel(void)
191 return kvm_state->irqchip_in_kernel;
194 int kvm_pit_in_kernel(void)
196 return kvm_state->pit_in_kernel;
199 int kvm_init_vcpu(CPUState *env)
201 KVMState *s = kvm_state;
202 long mmap_size;
203 int ret;
205 DPRINTF("kvm_init_vcpu\n");
207 ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, env->cpu_index);
208 if (ret < 0) {
209 DPRINTF("kvm_create_vcpu failed\n");
210 goto err;
213 env->kvm_fd = ret;
214 env->kvm_state = s;
215 env->kvm_vcpu_dirty = 1;
217 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
218 if (mmap_size < 0) {
219 ret = mmap_size;
220 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
221 goto err;
224 env->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
225 env->kvm_fd, 0);
226 if (env->kvm_run == MAP_FAILED) {
227 ret = -errno;
228 DPRINTF("mmap'ing vcpu state failed\n");
229 goto err;
232 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
233 s->coalesced_mmio_ring =
234 (void *)env->kvm_run + s->coalesced_mmio * PAGE_SIZE;
237 ret = kvm_arch_init_vcpu(env);
238 if (ret == 0) {
239 qemu_register_reset(kvm_reset_vcpu, env);
240 kvm_arch_reset_vcpu(env);
242 err:
243 return ret;
247 * dirty pages logging control
250 static int kvm_mem_flags(KVMState *s, bool log_dirty)
252 return log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
255 static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
257 KVMState *s = kvm_state;
258 int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
259 int old_flags;
261 old_flags = mem->flags;
263 flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty);
264 mem->flags = flags;
266 /* If nothing changed effectively, no need to issue ioctl */
267 if (s->migration_log) {
268 flags |= KVM_MEM_LOG_DIRTY_PAGES;
271 if (flags == old_flags) {
272 return 0;
275 return kvm_set_user_memory_region(s, mem);
278 static int kvm_dirty_pages_log_change(target_phys_addr_t phys_addr,
279 ram_addr_t size, bool log_dirty)
281 KVMState *s = kvm_state;
282 KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
284 if (mem == NULL) {
285 fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
286 TARGET_FMT_plx "\n", __func__, phys_addr,
287 (target_phys_addr_t)(phys_addr + size - 1));
288 return -EINVAL;
290 return kvm_slot_dirty_pages_log_change(mem, log_dirty);
293 static void kvm_log_start(MemoryListener *listener,
294 MemoryRegionSection *section)
296 int r;
298 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
299 section->size, true);
300 if (r < 0) {
301 abort();
305 static void kvm_log_stop(MemoryListener *listener,
306 MemoryRegionSection *section)
308 int r;
310 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
311 section->size, false);
312 if (r < 0) {
313 abort();
317 static int kvm_set_migration_log(int enable)
319 KVMState *s = kvm_state;
320 KVMSlot *mem;
321 int i, err;
323 s->migration_log = enable;
325 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
326 mem = &s->slots[i];
328 if (!mem->memory_size) {
329 continue;
331 if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
332 continue;
334 err = kvm_set_user_memory_region(s, mem);
335 if (err) {
336 return err;
339 return 0;
342 /* get kvm's dirty pages bitmap and update qemu's */
343 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
344 unsigned long *bitmap)
346 unsigned int i, j;
347 unsigned long page_number, addr, addr1, c;
348 unsigned int len = ((section->size / TARGET_PAGE_SIZE) + HOST_LONG_BITS - 1) / HOST_LONG_BITS;
351 * bitmap-traveling is faster than memory-traveling (for addr...)
352 * especially when most of the memory is not dirty.
354 for (i = 0; i < len; i++) {
355 if (bitmap[i] != 0) {
356 c = leul_to_cpu(bitmap[i]);
357 do {
358 j = ffsl(c) - 1;
359 c &= ~(1ul << j);
360 page_number = i * HOST_LONG_BITS + j;
361 addr1 = page_number * TARGET_PAGE_SIZE;
362 addr = section->offset_within_region + addr1;
363 memory_region_set_dirty(section->mr, addr);
364 } while (c != 0);
367 return 0;
370 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
373 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
374 * This function updates qemu's dirty bitmap using cpu_physical_memory_set_dirty().
375 * This means all bits are set to dirty.
377 * @start_add: start of logged region.
378 * @end_addr: end of logged region.
380 static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)
382 KVMState *s = kvm_state;
383 unsigned long size, allocated_size = 0;
384 KVMDirtyLog d;
385 KVMSlot *mem;
386 int ret = 0;
387 target_phys_addr_t start_addr = section->offset_within_address_space;
388 target_phys_addr_t end_addr = start_addr + section->size;
390 d.dirty_bitmap = NULL;
391 while (start_addr < end_addr) {
392 mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
393 if (mem == NULL) {
394 break;
397 /* XXX bad kernel interface alert
398 * For dirty bitmap, kernel allocates array of size aligned to
399 * bits-per-long. But for case when the kernel is 64bits and
400 * the userspace is 32bits, userspace can't align to the same
401 * bits-per-long, since sizeof(long) is different between kernel
402 * and user space. This way, userspace will provide buffer which
403 * may be 4 bytes less than the kernel will use, resulting in
404 * userspace memory corruption (which is not detectable by valgrind
405 * too, in most cases).
406 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
407 * a hope that sizeof(long) wont become >8 any time soon.
409 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
410 /*HOST_LONG_BITS*/ 64) / 8;
411 if (!d.dirty_bitmap) {
412 d.dirty_bitmap = g_malloc(size);
413 } else if (size > allocated_size) {
414 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
416 allocated_size = size;
417 memset(d.dirty_bitmap, 0, allocated_size);
419 d.slot = mem->slot;
421 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
422 DPRINTF("ioctl failed %d\n", errno);
423 ret = -1;
424 break;
427 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
428 start_addr = mem->start_addr + mem->memory_size;
430 g_free(d.dirty_bitmap);
432 return ret;
435 int kvm_coalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
437 int ret = -ENOSYS;
438 KVMState *s = kvm_state;
440 if (s->coalesced_mmio) {
441 struct kvm_coalesced_mmio_zone zone;
443 zone.addr = start;
444 zone.size = size;
446 ret = kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
449 return ret;
452 int kvm_uncoalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
454 int ret = -ENOSYS;
455 KVMState *s = kvm_state;
457 if (s->coalesced_mmio) {
458 struct kvm_coalesced_mmio_zone zone;
460 zone.addr = start;
461 zone.size = size;
463 ret = kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
466 return ret;
469 int kvm_check_extension(KVMState *s, unsigned int extension)
471 int ret;
473 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
474 if (ret < 0) {
475 ret = 0;
478 return ret;
481 static int kvm_check_many_ioeventfds(void)
483 /* Userspace can use ioeventfd for io notification. This requires a host
484 * that supports eventfd(2) and an I/O thread; since eventfd does not
485 * support SIGIO it cannot interrupt the vcpu.
487 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
488 * can avoid creating too many ioeventfds.
490 #if defined(CONFIG_EVENTFD)
491 int ioeventfds[7];
492 int i, ret = 0;
493 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
494 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
495 if (ioeventfds[i] < 0) {
496 break;
498 ret = kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, true);
499 if (ret < 0) {
500 close(ioeventfds[i]);
501 break;
505 /* Decide whether many devices are supported or not */
506 ret = i == ARRAY_SIZE(ioeventfds);
508 while (i-- > 0) {
509 kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, false);
510 close(ioeventfds[i]);
512 return ret;
513 #else
514 return 0;
515 #endif
518 static const KVMCapabilityInfo *
519 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
521 while (list->name) {
522 if (!kvm_check_extension(s, list->value)) {
523 return list;
525 list++;
527 return NULL;
530 static void kvm_set_phys_mem(MemoryRegionSection *section, bool add)
532 KVMState *s = kvm_state;
533 KVMSlot *mem, old;
534 int err;
535 MemoryRegion *mr = section->mr;
536 bool log_dirty = memory_region_is_logging(mr);
537 target_phys_addr_t start_addr = section->offset_within_address_space;
538 ram_addr_t size = section->size;
539 void *ram = NULL;
541 /* kvm works in page size chunks, but the function may be called
542 with sub-page size and unaligned start address. */
543 size = TARGET_PAGE_ALIGN(size);
544 start_addr = TARGET_PAGE_ALIGN(start_addr);
546 if (!memory_region_is_ram(mr)) {
547 return;
550 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region;
552 while (1) {
553 mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
554 if (!mem) {
555 break;
558 if (add && start_addr >= mem->start_addr &&
559 (start_addr + size <= mem->start_addr + mem->memory_size) &&
560 (ram - start_addr == mem->ram - mem->start_addr)) {
561 /* The new slot fits into the existing one and comes with
562 * identical parameters - update flags and done. */
563 kvm_slot_dirty_pages_log_change(mem, log_dirty);
564 return;
567 old = *mem;
569 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
570 kvm_physical_sync_dirty_bitmap(section);
573 /* unregister the overlapping slot */
574 mem->memory_size = 0;
575 err = kvm_set_user_memory_region(s, mem);
576 if (err) {
577 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
578 __func__, strerror(-err));
579 abort();
582 /* Workaround for older KVM versions: we can't join slots, even not by
583 * unregistering the previous ones and then registering the larger
584 * slot. We have to maintain the existing fragmentation. Sigh.
586 * This workaround assumes that the new slot starts at the same
587 * address as the first existing one. If not or if some overlapping
588 * slot comes around later, we will fail (not seen in practice so far)
589 * - and actually require a recent KVM version. */
590 if (s->broken_set_mem_region &&
591 old.start_addr == start_addr && old.memory_size < size && add) {
592 mem = kvm_alloc_slot(s);
593 mem->memory_size = old.memory_size;
594 mem->start_addr = old.start_addr;
595 mem->ram = old.ram;
596 mem->flags = kvm_mem_flags(s, log_dirty);
598 err = kvm_set_user_memory_region(s, mem);
599 if (err) {
600 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
601 strerror(-err));
602 abort();
605 start_addr += old.memory_size;
606 ram += old.memory_size;
607 size -= old.memory_size;
608 continue;
611 /* register prefix slot */
612 if (old.start_addr < start_addr) {
613 mem = kvm_alloc_slot(s);
614 mem->memory_size = start_addr - old.start_addr;
615 mem->start_addr = old.start_addr;
616 mem->ram = old.ram;
617 mem->flags = kvm_mem_flags(s, log_dirty);
619 err = kvm_set_user_memory_region(s, mem);
620 if (err) {
621 fprintf(stderr, "%s: error registering prefix slot: %s\n",
622 __func__, strerror(-err));
623 #ifdef TARGET_PPC
624 fprintf(stderr, "%s: This is probably because your kernel's " \
625 "PAGE_SIZE is too big. Please try to use 4k " \
626 "PAGE_SIZE!\n", __func__);
627 #endif
628 abort();
632 /* register suffix slot */
633 if (old.start_addr + old.memory_size > start_addr + size) {
634 ram_addr_t size_delta;
636 mem = kvm_alloc_slot(s);
637 mem->start_addr = start_addr + size;
638 size_delta = mem->start_addr - old.start_addr;
639 mem->memory_size = old.memory_size - size_delta;
640 mem->ram = old.ram + size_delta;
641 mem->flags = kvm_mem_flags(s, log_dirty);
643 err = kvm_set_user_memory_region(s, mem);
644 if (err) {
645 fprintf(stderr, "%s: error registering suffix slot: %s\n",
646 __func__, strerror(-err));
647 abort();
652 /* in case the KVM bug workaround already "consumed" the new slot */
653 if (!size) {
654 return;
656 if (!add) {
657 return;
659 mem = kvm_alloc_slot(s);
660 mem->memory_size = size;
661 mem->start_addr = start_addr;
662 mem->ram = ram;
663 mem->flags = kvm_mem_flags(s, log_dirty);
665 err = kvm_set_user_memory_region(s, mem);
666 if (err) {
667 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
668 strerror(-err));
669 abort();
673 static void kvm_region_add(MemoryListener *listener,
674 MemoryRegionSection *section)
676 kvm_set_phys_mem(section, true);
679 static void kvm_region_del(MemoryListener *listener,
680 MemoryRegionSection *section)
682 kvm_set_phys_mem(section, false);
685 static void kvm_log_sync(MemoryListener *listener,
686 MemoryRegionSection *section)
688 int r;
690 r = kvm_physical_sync_dirty_bitmap(section);
691 if (r < 0) {
692 abort();
696 static void kvm_log_global_start(struct MemoryListener *listener)
698 int r;
700 r = kvm_set_migration_log(1);
701 assert(r >= 0);
704 static void kvm_log_global_stop(struct MemoryListener *listener)
706 int r;
708 r = kvm_set_migration_log(0);
709 assert(r >= 0);
712 static MemoryListener kvm_memory_listener = {
713 .region_add = kvm_region_add,
714 .region_del = kvm_region_del,
715 .log_start = kvm_log_start,
716 .log_stop = kvm_log_stop,
717 .log_sync = kvm_log_sync,
718 .log_global_start = kvm_log_global_start,
719 .log_global_stop = kvm_log_global_stop,
722 static void kvm_handle_interrupt(CPUState *env, int mask)
724 env->interrupt_request |= mask;
726 if (!qemu_cpu_is_self(env)) {
727 qemu_cpu_kick(env);
731 int kvm_init(void)
733 static const char upgrade_note[] =
734 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
735 "(see http://sourceforge.net/projects/kvm).\n";
736 KVMState *s;
737 const KVMCapabilityInfo *missing_cap;
738 int ret;
739 int i;
741 s = g_malloc0(sizeof(KVMState));
743 #ifdef KVM_CAP_SET_GUEST_DEBUG
744 QTAILQ_INIT(&s->kvm_sw_breakpoints);
745 #endif
746 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
747 s->slots[i].slot = i;
749 s->vmfd = -1;
750 s->fd = qemu_open("/dev/kvm", O_RDWR);
751 if (s->fd == -1) {
752 fprintf(stderr, "Could not access KVM kernel module: %m\n");
753 ret = -errno;
754 goto err;
757 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
758 if (ret < KVM_API_VERSION) {
759 if (ret > 0) {
760 ret = -EINVAL;
762 fprintf(stderr, "kvm version too old\n");
763 goto err;
766 if (ret > KVM_API_VERSION) {
767 ret = -EINVAL;
768 fprintf(stderr, "kvm version not supported\n");
769 goto err;
772 s->vmfd = kvm_ioctl(s, KVM_CREATE_VM, 0);
773 if (s->vmfd < 0) {
774 #ifdef TARGET_S390X
775 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
776 "your host kernel command line\n");
777 #endif
778 ret = s->vmfd;
779 goto err;
782 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
783 if (!missing_cap) {
784 missing_cap =
785 kvm_check_extension_list(s, kvm_arch_required_capabilities);
787 if (missing_cap) {
788 ret = -EINVAL;
789 fprintf(stderr, "kvm does not support %s\n%s",
790 missing_cap->name, upgrade_note);
791 goto err;
794 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
796 s->broken_set_mem_region = 1;
797 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
798 if (ret > 0) {
799 s->broken_set_mem_region = 0;
802 #ifdef KVM_CAP_VCPU_EVENTS
803 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
804 #endif
806 s->robust_singlestep =
807 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
809 #ifdef KVM_CAP_DEBUGREGS
810 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
811 #endif
813 #ifdef KVM_CAP_XSAVE
814 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
815 #endif
817 #ifdef KVM_CAP_XCRS
818 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
819 #endif
821 ret = kvm_arch_init(s);
822 if (ret < 0) {
823 goto err;
826 kvm_state = s;
827 memory_listener_register(&kvm_memory_listener);
829 s->many_ioeventfds = kvm_check_many_ioeventfds();
831 cpu_interrupt_handler = kvm_handle_interrupt;
833 return 0;
835 err:
836 if (s) {
837 if (s->vmfd >= 0) {
838 close(s->vmfd);
840 if (s->fd != -1) {
841 close(s->fd);
844 g_free(s);
846 return ret;
849 static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
850 uint32_t count)
852 int i;
853 uint8_t *ptr = data;
855 for (i = 0; i < count; i++) {
856 if (direction == KVM_EXIT_IO_IN) {
857 switch (size) {
858 case 1:
859 stb_p(ptr, cpu_inb(port));
860 break;
861 case 2:
862 stw_p(ptr, cpu_inw(port));
863 break;
864 case 4:
865 stl_p(ptr, cpu_inl(port));
866 break;
868 } else {
869 switch (size) {
870 case 1:
871 cpu_outb(port, ldub_p(ptr));
872 break;
873 case 2:
874 cpu_outw(port, lduw_p(ptr));
875 break;
876 case 4:
877 cpu_outl(port, ldl_p(ptr));
878 break;
882 ptr += size;
886 static int kvm_handle_internal_error(CPUState *env, struct kvm_run *run)
888 fprintf(stderr, "KVM internal error.");
889 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
890 int i;
892 fprintf(stderr, " Suberror: %d\n", run->internal.suberror);
893 for (i = 0; i < run->internal.ndata; ++i) {
894 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
895 i, (uint64_t)run->internal.data[i]);
897 } else {
898 fprintf(stderr, "\n");
900 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
901 fprintf(stderr, "emulation failure\n");
902 if (!kvm_arch_stop_on_emulation_error(env)) {
903 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
904 return EXCP_INTERRUPT;
907 /* FIXME: Should trigger a qmp message to let management know
908 * something went wrong.
910 return -1;
913 void kvm_flush_coalesced_mmio_buffer(void)
915 KVMState *s = kvm_state;
917 if (s->coalesced_flush_in_progress) {
918 return;
921 s->coalesced_flush_in_progress = true;
923 if (s->coalesced_mmio_ring) {
924 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
925 while (ring->first != ring->last) {
926 struct kvm_coalesced_mmio *ent;
928 ent = &ring->coalesced_mmio[ring->first];
930 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
931 smp_wmb();
932 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
936 s->coalesced_flush_in_progress = false;
939 static void do_kvm_cpu_synchronize_state(void *_env)
941 CPUState *env = _env;
943 if (!env->kvm_vcpu_dirty) {
944 kvm_arch_get_registers(env);
945 env->kvm_vcpu_dirty = 1;
949 void kvm_cpu_synchronize_state(CPUState *env)
951 if (!env->kvm_vcpu_dirty) {
952 run_on_cpu(env, do_kvm_cpu_synchronize_state, env);
956 void kvm_cpu_synchronize_post_reset(CPUState *env)
958 kvm_arch_put_registers(env, KVM_PUT_RESET_STATE);
959 env->kvm_vcpu_dirty = 0;
962 void kvm_cpu_synchronize_post_init(CPUState *env)
964 kvm_arch_put_registers(env, KVM_PUT_FULL_STATE);
965 env->kvm_vcpu_dirty = 0;
968 int kvm_cpu_exec(CPUState *env)
970 struct kvm_run *run = env->kvm_run;
971 int ret, run_ret;
973 DPRINTF("kvm_cpu_exec()\n");
975 if (kvm_arch_process_async_events(env)) {
976 env->exit_request = 0;
977 return EXCP_HLT;
980 cpu_single_env = env;
982 do {
983 if (env->kvm_vcpu_dirty) {
984 kvm_arch_put_registers(env, KVM_PUT_RUNTIME_STATE);
985 env->kvm_vcpu_dirty = 0;
988 kvm_arch_pre_run(env, run);
989 if (env->exit_request) {
990 DPRINTF("interrupt exit requested\n");
992 * KVM requires us to reenter the kernel after IO exits to complete
993 * instruction emulation. This self-signal will ensure that we
994 * leave ASAP again.
996 qemu_cpu_kick_self();
998 cpu_single_env = NULL;
999 qemu_mutex_unlock_iothread();
1001 run_ret = kvm_vcpu_ioctl(env, KVM_RUN, 0);
1003 qemu_mutex_lock_iothread();
1004 cpu_single_env = env;
1005 kvm_arch_post_run(env, run);
1007 kvm_flush_coalesced_mmio_buffer();
1009 if (run_ret < 0) {
1010 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1011 DPRINTF("io window exit\n");
1012 ret = EXCP_INTERRUPT;
1013 break;
1015 fprintf(stderr, "error: kvm run failed %s\n",
1016 strerror(-run_ret));
1017 abort();
1020 switch (run->exit_reason) {
1021 case KVM_EXIT_IO:
1022 DPRINTF("handle_io\n");
1023 kvm_handle_io(run->io.port,
1024 (uint8_t *)run + run->io.data_offset,
1025 run->io.direction,
1026 run->io.size,
1027 run->io.count);
1028 ret = 0;
1029 break;
1030 case KVM_EXIT_MMIO:
1031 DPRINTF("handle_mmio\n");
1032 cpu_physical_memory_rw(run->mmio.phys_addr,
1033 run->mmio.data,
1034 run->mmio.len,
1035 run->mmio.is_write);
1036 ret = 0;
1037 break;
1038 case KVM_EXIT_IRQ_WINDOW_OPEN:
1039 DPRINTF("irq_window_open\n");
1040 ret = EXCP_INTERRUPT;
1041 break;
1042 case KVM_EXIT_SHUTDOWN:
1043 DPRINTF("shutdown\n");
1044 qemu_system_reset_request();
1045 ret = EXCP_INTERRUPT;
1046 break;
1047 case KVM_EXIT_UNKNOWN:
1048 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1049 (uint64_t)run->hw.hardware_exit_reason);
1050 ret = -1;
1051 break;
1052 case KVM_EXIT_INTERNAL_ERROR:
1053 ret = kvm_handle_internal_error(env, run);
1054 break;
1055 default:
1056 DPRINTF("kvm_arch_handle_exit\n");
1057 ret = kvm_arch_handle_exit(env, run);
1058 break;
1060 } while (ret == 0);
1062 if (ret < 0) {
1063 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1064 vm_stop(RUN_STATE_INTERNAL_ERROR);
1067 env->exit_request = 0;
1068 cpu_single_env = NULL;
1069 return ret;
1072 int kvm_ioctl(KVMState *s, int type, ...)
1074 int ret;
1075 void *arg;
1076 va_list ap;
1078 va_start(ap, type);
1079 arg = va_arg(ap, void *);
1080 va_end(ap);
1082 ret = ioctl(s->fd, type, arg);
1083 if (ret == -1) {
1084 ret = -errno;
1086 return ret;
1089 int kvm_vm_ioctl(KVMState *s, int type, ...)
1091 int ret;
1092 void *arg;
1093 va_list ap;
1095 va_start(ap, type);
1096 arg = va_arg(ap, void *);
1097 va_end(ap);
1099 ret = ioctl(s->vmfd, type, arg);
1100 if (ret == -1) {
1101 ret = -errno;
1103 return ret;
1106 int kvm_vcpu_ioctl(CPUState *env, int type, ...)
1108 int ret;
1109 void *arg;
1110 va_list ap;
1112 va_start(ap, type);
1113 arg = va_arg(ap, void *);
1114 va_end(ap);
1116 ret = ioctl(env->kvm_fd, type, arg);
1117 if (ret == -1) {
1118 ret = -errno;
1120 return ret;
1123 int kvm_has_sync_mmu(void)
1125 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1128 int kvm_has_vcpu_events(void)
1130 return kvm_state->vcpu_events;
1133 int kvm_has_robust_singlestep(void)
1135 return kvm_state->robust_singlestep;
1138 int kvm_has_debugregs(void)
1140 return kvm_state->debugregs;
1143 int kvm_has_xsave(void)
1145 return kvm_state->xsave;
1148 int kvm_has_xcrs(void)
1150 return kvm_state->xcrs;
1153 int kvm_has_many_ioeventfds(void)
1155 if (!kvm_enabled()) {
1156 return 0;
1158 return kvm_state->many_ioeventfds;
1161 void kvm_setup_guest_memory(void *start, size_t size)
1163 if (!kvm_has_sync_mmu()) {
1164 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1166 if (ret) {
1167 perror("qemu_madvise");
1168 fprintf(stderr,
1169 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1170 exit(1);
1175 #ifdef KVM_CAP_SET_GUEST_DEBUG
1176 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *env,
1177 target_ulong pc)
1179 struct kvm_sw_breakpoint *bp;
1181 QTAILQ_FOREACH(bp, &env->kvm_state->kvm_sw_breakpoints, entry) {
1182 if (bp->pc == pc) {
1183 return bp;
1186 return NULL;
1189 int kvm_sw_breakpoints_active(CPUState *env)
1191 return !QTAILQ_EMPTY(&env->kvm_state->kvm_sw_breakpoints);
1194 struct kvm_set_guest_debug_data {
1195 struct kvm_guest_debug dbg;
1196 CPUState *env;
1197 int err;
1200 static void kvm_invoke_set_guest_debug(void *data)
1202 struct kvm_set_guest_debug_data *dbg_data = data;
1203 CPUState *env = dbg_data->env;
1205 dbg_data->err = kvm_vcpu_ioctl(env, KVM_SET_GUEST_DEBUG, &dbg_data->dbg);
1208 int kvm_update_guest_debug(CPUState *env, unsigned long reinject_trap)
1210 struct kvm_set_guest_debug_data data;
1212 data.dbg.control = reinject_trap;
1214 if (env->singlestep_enabled) {
1215 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
1217 kvm_arch_update_guest_debug(env, &data.dbg);
1218 data.env = env;
1220 run_on_cpu(env, kvm_invoke_set_guest_debug, &data);
1221 return data.err;
1224 int kvm_insert_breakpoint(CPUState *current_env, target_ulong addr,
1225 target_ulong len, int type)
1227 struct kvm_sw_breakpoint *bp;
1228 CPUState *env;
1229 int err;
1231 if (type == GDB_BREAKPOINT_SW) {
1232 bp = kvm_find_sw_breakpoint(current_env, addr);
1233 if (bp) {
1234 bp->use_count++;
1235 return 0;
1238 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
1239 if (!bp) {
1240 return -ENOMEM;
1243 bp->pc = addr;
1244 bp->use_count = 1;
1245 err = kvm_arch_insert_sw_breakpoint(current_env, bp);
1246 if (err) {
1247 g_free(bp);
1248 return err;
1251 QTAILQ_INSERT_HEAD(&current_env->kvm_state->kvm_sw_breakpoints,
1252 bp, entry);
1253 } else {
1254 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
1255 if (err) {
1256 return err;
1260 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1261 err = kvm_update_guest_debug(env, 0);
1262 if (err) {
1263 return err;
1266 return 0;
1269 int kvm_remove_breakpoint(CPUState *current_env, target_ulong addr,
1270 target_ulong len, int type)
1272 struct kvm_sw_breakpoint *bp;
1273 CPUState *env;
1274 int err;
1276 if (type == GDB_BREAKPOINT_SW) {
1277 bp = kvm_find_sw_breakpoint(current_env, addr);
1278 if (!bp) {
1279 return -ENOENT;
1282 if (bp->use_count > 1) {
1283 bp->use_count--;
1284 return 0;
1287 err = kvm_arch_remove_sw_breakpoint(current_env, bp);
1288 if (err) {
1289 return err;
1292 QTAILQ_REMOVE(&current_env->kvm_state->kvm_sw_breakpoints, bp, entry);
1293 g_free(bp);
1294 } else {
1295 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
1296 if (err) {
1297 return err;
1301 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1302 err = kvm_update_guest_debug(env, 0);
1303 if (err) {
1304 return err;
1307 return 0;
1310 void kvm_remove_all_breakpoints(CPUState *current_env)
1312 struct kvm_sw_breakpoint *bp, *next;
1313 KVMState *s = current_env->kvm_state;
1314 CPUState *env;
1316 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
1317 if (kvm_arch_remove_sw_breakpoint(current_env, bp) != 0) {
1318 /* Try harder to find a CPU that currently sees the breakpoint. */
1319 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1320 if (kvm_arch_remove_sw_breakpoint(env, bp) == 0) {
1321 break;
1326 kvm_arch_remove_all_hw_breakpoints();
1328 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1329 kvm_update_guest_debug(env, 0);
1333 #else /* !KVM_CAP_SET_GUEST_DEBUG */
1335 int kvm_update_guest_debug(CPUState *env, unsigned long reinject_trap)
1337 return -EINVAL;
1340 int kvm_insert_breakpoint(CPUState *current_env, target_ulong addr,
1341 target_ulong len, int type)
1343 return -EINVAL;
1346 int kvm_remove_breakpoint(CPUState *current_env, target_ulong addr,
1347 target_ulong len, int type)
1349 return -EINVAL;
1352 void kvm_remove_all_breakpoints(CPUState *current_env)
1355 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
1357 int kvm_set_signal_mask(CPUState *env, const sigset_t *sigset)
1359 struct kvm_signal_mask *sigmask;
1360 int r;
1362 if (!sigset) {
1363 return kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, NULL);
1366 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
1368 sigmask->len = 8;
1369 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
1370 r = kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, sigmask);
1371 g_free(sigmask);
1373 return r;
1376 int kvm_set_ioeventfd_mmio_long(int fd, uint32_t addr, uint32_t val, bool assign)
1378 int ret;
1379 struct kvm_ioeventfd iofd;
1381 iofd.datamatch = val;
1382 iofd.addr = addr;
1383 iofd.len = 4;
1384 iofd.flags = KVM_IOEVENTFD_FLAG_DATAMATCH;
1385 iofd.fd = fd;
1387 if (!kvm_enabled()) {
1388 return -ENOSYS;
1391 if (!assign) {
1392 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1395 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
1397 if (ret < 0) {
1398 return -errno;
1401 return 0;
1404 int kvm_set_ioeventfd_pio_word(int fd, uint16_t addr, uint16_t val, bool assign)
1406 struct kvm_ioeventfd kick = {
1407 .datamatch = val,
1408 .addr = addr,
1409 .len = 2,
1410 .flags = KVM_IOEVENTFD_FLAG_DATAMATCH | KVM_IOEVENTFD_FLAG_PIO,
1411 .fd = fd,
1413 int r;
1414 if (!kvm_enabled()) {
1415 return -ENOSYS;
1417 if (!assign) {
1418 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1420 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
1421 if (r < 0) {
1422 return r;
1424 return 0;
1427 int kvm_on_sigbus_vcpu(CPUState *env, int code, void *addr)
1429 return kvm_arch_on_sigbus_vcpu(env, code, addr);
1432 int kvm_on_sigbus(int code, void *addr)
1434 return kvm_arch_on_sigbus(code, addr);