block/rbd: fix memory leak
[qemu/ar7.git] / kvm-all.c
blob937bc9d9035a420a58351f87fa44ce98a3723d4b
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/atomic.h"
25 #include "qemu/option.h"
26 #include "qemu/config-file.h"
27 #include "sysemu/sysemu.h"
28 #include "sysemu/accel.h"
29 #include "hw/hw.h"
30 #include "hw/pci/msi.h"
31 #include "hw/s390x/adapter.h"
32 #include "exec/gdbstub.h"
33 #include "sysemu/kvm.h"
34 #include "qemu/bswap.h"
35 #include "exec/memory.h"
36 #include "exec/ram_addr.h"
37 #include "exec/address-spaces.h"
38 #include "qemu/event_notifier.h"
39 #include "trace.h"
41 #include "hw/boards.h"
43 /* This check must be after config-host.h is included */
44 #ifdef CONFIG_EVENTFD
45 #include <sys/eventfd.h>
46 #endif
48 /* KVM uses PAGE_SIZE in its definition of COALESCED_MMIO_MAX */
49 #define PAGE_SIZE TARGET_PAGE_SIZE
51 //#define DEBUG_KVM
53 #ifdef DEBUG_KVM
54 #define DPRINTF(fmt, ...) \
55 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
56 #else
57 #define DPRINTF(fmt, ...) \
58 do { } while (0)
59 #endif
61 #define KVM_MSI_HASHTAB_SIZE 256
63 typedef struct KVMSlot
65 hwaddr start_addr;
66 ram_addr_t memory_size;
67 void *ram;
68 int slot;
69 int flags;
70 } KVMSlot;
72 typedef struct kvm_dirty_log KVMDirtyLog;
74 struct KVMState
76 AccelState parent_obj;
78 KVMSlot *slots;
79 int nr_slots;
80 int fd;
81 int vmfd;
82 int coalesced_mmio;
83 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
84 bool coalesced_flush_in_progress;
85 int broken_set_mem_region;
86 int migration_log;
87 int vcpu_events;
88 int robust_singlestep;
89 int debugregs;
90 #ifdef KVM_CAP_SET_GUEST_DEBUG
91 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
92 #endif
93 int pit_state2;
94 int xsave, xcrs;
95 int many_ioeventfds;
96 int intx_set_mask;
97 /* The man page (and posix) say ioctl numbers are signed int, but
98 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
99 * unsigned, and treating them as signed here can break things */
100 unsigned irq_set_ioctl;
101 unsigned int sigmask_len;
102 #ifdef KVM_CAP_IRQ_ROUTING
103 struct kvm_irq_routing *irq_routes;
104 int nr_allocated_irq_routes;
105 uint32_t *used_gsi_bitmap;
106 unsigned int gsi_count;
107 QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
108 bool direct_msi;
109 #endif
112 #define TYPE_KVM_ACCEL ACCEL_CLASS_NAME("kvm")
114 #define KVM_STATE(obj) \
115 OBJECT_CHECK(KVMState, (obj), TYPE_KVM_ACCEL)
117 KVMState *kvm_state;
118 bool kvm_kernel_irqchip;
119 bool kvm_async_interrupts_allowed;
120 bool kvm_halt_in_kernel_allowed;
121 bool kvm_eventfds_allowed;
122 bool kvm_irqfds_allowed;
123 bool kvm_msi_via_irqfd_allowed;
124 bool kvm_gsi_routing_allowed;
125 bool kvm_gsi_direct_mapping;
126 bool kvm_allowed;
127 bool kvm_readonly_mem_allowed;
129 static const KVMCapabilityInfo kvm_required_capabilites[] = {
130 KVM_CAP_INFO(USER_MEMORY),
131 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
132 KVM_CAP_LAST_INFO
135 static KVMSlot *kvm_get_free_slot(KVMState *s)
137 int i;
139 for (i = 0; i < s->nr_slots; i++) {
140 if (s->slots[i].memory_size == 0) {
141 return &s->slots[i];
145 return NULL;
148 bool kvm_has_free_slot(MachineState *ms)
150 return kvm_get_free_slot(KVM_STATE(ms->accelerator));
153 static KVMSlot *kvm_alloc_slot(KVMState *s)
155 KVMSlot *slot = kvm_get_free_slot(s);
157 if (slot) {
158 return slot;
161 fprintf(stderr, "%s: no free slot available\n", __func__);
162 abort();
165 static KVMSlot *kvm_lookup_matching_slot(KVMState *s,
166 hwaddr start_addr,
167 hwaddr end_addr)
169 int i;
171 for (i = 0; i < s->nr_slots; i++) {
172 KVMSlot *mem = &s->slots[i];
174 if (start_addr == mem->start_addr &&
175 end_addr == mem->start_addr + mem->memory_size) {
176 return mem;
180 return NULL;
184 * Find overlapping slot with lowest start address
186 static KVMSlot *kvm_lookup_overlapping_slot(KVMState *s,
187 hwaddr start_addr,
188 hwaddr end_addr)
190 KVMSlot *found = NULL;
191 int i;
193 for (i = 0; i < s->nr_slots; i++) {
194 KVMSlot *mem = &s->slots[i];
196 if (mem->memory_size == 0 ||
197 (found && found->start_addr < mem->start_addr)) {
198 continue;
201 if (end_addr > mem->start_addr &&
202 start_addr < mem->start_addr + mem->memory_size) {
203 found = mem;
207 return found;
210 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
211 hwaddr *phys_addr)
213 int i;
215 for (i = 0; i < s->nr_slots; i++) {
216 KVMSlot *mem = &s->slots[i];
218 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
219 *phys_addr = mem->start_addr + (ram - mem->ram);
220 return 1;
224 return 0;
227 static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)
229 struct kvm_userspace_memory_region mem;
231 mem.slot = slot->slot;
232 mem.guest_phys_addr = slot->start_addr;
233 mem.userspace_addr = (unsigned long)slot->ram;
234 mem.flags = slot->flags;
235 if (s->migration_log) {
236 mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;
239 if (slot->memory_size && mem.flags & KVM_MEM_READONLY) {
240 /* Set the slot size to 0 before setting the slot to the desired
241 * value. This is needed based on KVM commit 75d61fbc. */
242 mem.memory_size = 0;
243 kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
245 mem.memory_size = slot->memory_size;
246 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
249 int kvm_init_vcpu(CPUState *cpu)
251 KVMState *s = kvm_state;
252 long mmap_size;
253 int ret;
255 DPRINTF("kvm_init_vcpu\n");
257 ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)kvm_arch_vcpu_id(cpu));
258 if (ret < 0) {
259 DPRINTF("kvm_create_vcpu failed\n");
260 goto err;
263 cpu->kvm_fd = ret;
264 cpu->kvm_state = s;
265 cpu->kvm_vcpu_dirty = true;
267 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
268 if (mmap_size < 0) {
269 ret = mmap_size;
270 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
271 goto err;
274 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
275 cpu->kvm_fd, 0);
276 if (cpu->kvm_run == MAP_FAILED) {
277 ret = -errno;
278 DPRINTF("mmap'ing vcpu state failed\n");
279 goto err;
282 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
283 s->coalesced_mmio_ring =
284 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
287 ret = kvm_arch_init_vcpu(cpu);
288 err:
289 return ret;
293 * dirty pages logging control
296 static int kvm_mem_flags(KVMState *s, bool log_dirty, bool readonly)
298 int flags = 0;
299 flags = log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
300 if (readonly && kvm_readonly_mem_allowed) {
301 flags |= KVM_MEM_READONLY;
303 return flags;
306 static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
308 KVMState *s = kvm_state;
309 int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
310 int old_flags;
312 old_flags = mem->flags;
314 flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty, false);
315 mem->flags = flags;
317 /* If nothing changed effectively, no need to issue ioctl */
318 if (s->migration_log) {
319 flags |= KVM_MEM_LOG_DIRTY_PAGES;
322 if (flags == old_flags) {
323 return 0;
326 return kvm_set_user_memory_region(s, mem);
329 static int kvm_dirty_pages_log_change(hwaddr phys_addr,
330 ram_addr_t size, bool log_dirty)
332 KVMState *s = kvm_state;
333 KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
335 if (mem == NULL) {
336 fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
337 TARGET_FMT_plx "\n", __func__, phys_addr,
338 (hwaddr)(phys_addr + size - 1));
339 return -EINVAL;
341 return kvm_slot_dirty_pages_log_change(mem, log_dirty);
344 static void kvm_log_start(MemoryListener *listener,
345 MemoryRegionSection *section)
347 int r;
349 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
350 int128_get64(section->size), true);
351 if (r < 0) {
352 abort();
356 static void kvm_log_stop(MemoryListener *listener,
357 MemoryRegionSection *section)
359 int r;
361 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
362 int128_get64(section->size), false);
363 if (r < 0) {
364 abort();
368 static int kvm_set_migration_log(int enable)
370 KVMState *s = kvm_state;
371 KVMSlot *mem;
372 int i, err;
374 s->migration_log = enable;
376 for (i = 0; i < s->nr_slots; i++) {
377 mem = &s->slots[i];
379 if (!mem->memory_size) {
380 continue;
382 if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
383 continue;
385 err = kvm_set_user_memory_region(s, mem);
386 if (err) {
387 return err;
390 return 0;
393 /* get kvm's dirty pages bitmap and update qemu's */
394 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
395 unsigned long *bitmap)
397 ram_addr_t start = section->offset_within_region + section->mr->ram_addr;
398 ram_addr_t pages = int128_get64(section->size) / getpagesize();
400 cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
401 return 0;
404 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
407 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
408 * This function updates qemu's dirty bitmap using
409 * memory_region_set_dirty(). This means all bits are set
410 * to dirty.
412 * @start_add: start of logged region.
413 * @end_addr: end of logged region.
415 static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)
417 KVMState *s = kvm_state;
418 unsigned long size, allocated_size = 0;
419 KVMDirtyLog d;
420 KVMSlot *mem;
421 int ret = 0;
422 hwaddr start_addr = section->offset_within_address_space;
423 hwaddr end_addr = start_addr + int128_get64(section->size);
425 d.dirty_bitmap = NULL;
426 while (start_addr < end_addr) {
427 mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
428 if (mem == NULL) {
429 break;
432 /* XXX bad kernel interface alert
433 * For dirty bitmap, kernel allocates array of size aligned to
434 * bits-per-long. But for case when the kernel is 64bits and
435 * the userspace is 32bits, userspace can't align to the same
436 * bits-per-long, since sizeof(long) is different between kernel
437 * and user space. This way, userspace will provide buffer which
438 * may be 4 bytes less than the kernel will use, resulting in
439 * userspace memory corruption (which is not detectable by valgrind
440 * too, in most cases).
441 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
442 * a hope that sizeof(long) wont become >8 any time soon.
444 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
445 /*HOST_LONG_BITS*/ 64) / 8;
446 if (!d.dirty_bitmap) {
447 d.dirty_bitmap = g_malloc(size);
448 } else if (size > allocated_size) {
449 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
451 allocated_size = size;
452 memset(d.dirty_bitmap, 0, allocated_size);
454 d.slot = mem->slot;
456 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
457 DPRINTF("ioctl failed %d\n", errno);
458 ret = -1;
459 break;
462 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
463 start_addr = mem->start_addr + mem->memory_size;
465 g_free(d.dirty_bitmap);
467 return ret;
470 static void kvm_coalesce_mmio_region(MemoryListener *listener,
471 MemoryRegionSection *secion,
472 hwaddr start, hwaddr size)
474 KVMState *s = kvm_state;
476 if (s->coalesced_mmio) {
477 struct kvm_coalesced_mmio_zone zone;
479 zone.addr = start;
480 zone.size = size;
481 zone.pad = 0;
483 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
487 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
488 MemoryRegionSection *secion,
489 hwaddr start, hwaddr size)
491 KVMState *s = kvm_state;
493 if (s->coalesced_mmio) {
494 struct kvm_coalesced_mmio_zone zone;
496 zone.addr = start;
497 zone.size = size;
498 zone.pad = 0;
500 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
504 int kvm_check_extension(KVMState *s, unsigned int extension)
506 int ret;
508 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
509 if (ret < 0) {
510 ret = 0;
513 return ret;
516 int kvm_vm_check_extension(KVMState *s, unsigned int extension)
518 int ret;
520 ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
521 if (ret < 0) {
522 /* VM wide version not implemented, use global one instead */
523 ret = kvm_check_extension(s, extension);
526 return ret;
529 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
530 bool assign, uint32_t size, bool datamatch)
532 int ret;
533 struct kvm_ioeventfd iofd;
535 iofd.datamatch = datamatch ? val : 0;
536 iofd.addr = addr;
537 iofd.len = size;
538 iofd.flags = 0;
539 iofd.fd = fd;
541 if (!kvm_enabled()) {
542 return -ENOSYS;
545 if (datamatch) {
546 iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
548 if (!assign) {
549 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
552 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
554 if (ret < 0) {
555 return -errno;
558 return 0;
561 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
562 bool assign, uint32_t size, bool datamatch)
564 struct kvm_ioeventfd kick = {
565 .datamatch = datamatch ? val : 0,
566 .addr = addr,
567 .flags = KVM_IOEVENTFD_FLAG_PIO,
568 .len = size,
569 .fd = fd,
571 int r;
572 if (!kvm_enabled()) {
573 return -ENOSYS;
575 if (datamatch) {
576 kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
578 if (!assign) {
579 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
581 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
582 if (r < 0) {
583 return r;
585 return 0;
589 static int kvm_check_many_ioeventfds(void)
591 /* Userspace can use ioeventfd for io notification. This requires a host
592 * that supports eventfd(2) and an I/O thread; since eventfd does not
593 * support SIGIO it cannot interrupt the vcpu.
595 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
596 * can avoid creating too many ioeventfds.
598 #if defined(CONFIG_EVENTFD)
599 int ioeventfds[7];
600 int i, ret = 0;
601 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
602 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
603 if (ioeventfds[i] < 0) {
604 break;
606 ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
607 if (ret < 0) {
608 close(ioeventfds[i]);
609 break;
613 /* Decide whether many devices are supported or not */
614 ret = i == ARRAY_SIZE(ioeventfds);
616 while (i-- > 0) {
617 kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
618 close(ioeventfds[i]);
620 return ret;
621 #else
622 return 0;
623 #endif
626 static const KVMCapabilityInfo *
627 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
629 while (list->name) {
630 if (!kvm_check_extension(s, list->value)) {
631 return list;
633 list++;
635 return NULL;
638 static void kvm_set_phys_mem(MemoryRegionSection *section, bool add)
640 KVMState *s = kvm_state;
641 KVMSlot *mem, old;
642 int err;
643 MemoryRegion *mr = section->mr;
644 bool log_dirty = memory_region_is_logging(mr);
645 bool writeable = !mr->readonly && !mr->rom_device;
646 bool readonly_flag = mr->readonly || memory_region_is_romd(mr);
647 hwaddr start_addr = section->offset_within_address_space;
648 ram_addr_t size = int128_get64(section->size);
649 void *ram = NULL;
650 unsigned delta;
652 /* kvm works in page size chunks, but the function may be called
653 with sub-page size and unaligned start address. Pad the start
654 address to next and truncate size to previous page boundary. */
655 delta = (TARGET_PAGE_SIZE - (start_addr & ~TARGET_PAGE_MASK));
656 delta &= ~TARGET_PAGE_MASK;
657 if (delta > size) {
658 return;
660 start_addr += delta;
661 size -= delta;
662 size &= TARGET_PAGE_MASK;
663 if (!size || (start_addr & ~TARGET_PAGE_MASK)) {
664 return;
667 if (!memory_region_is_ram(mr)) {
668 if (writeable || !kvm_readonly_mem_allowed) {
669 return;
670 } else if (!mr->romd_mode) {
671 /* If the memory device is not in romd_mode, then we actually want
672 * to remove the kvm memory slot so all accesses will trap. */
673 add = false;
677 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
679 while (1) {
680 mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
681 if (!mem) {
682 break;
685 if (add && start_addr >= mem->start_addr &&
686 (start_addr + size <= mem->start_addr + mem->memory_size) &&
687 (ram - start_addr == mem->ram - mem->start_addr)) {
688 /* The new slot fits into the existing one and comes with
689 * identical parameters - update flags and done. */
690 kvm_slot_dirty_pages_log_change(mem, log_dirty);
691 return;
694 old = *mem;
696 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
697 kvm_physical_sync_dirty_bitmap(section);
700 /* unregister the overlapping slot */
701 mem->memory_size = 0;
702 err = kvm_set_user_memory_region(s, mem);
703 if (err) {
704 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
705 __func__, strerror(-err));
706 abort();
709 /* Workaround for older KVM versions: we can't join slots, even not by
710 * unregistering the previous ones and then registering the larger
711 * slot. We have to maintain the existing fragmentation. Sigh.
713 * This workaround assumes that the new slot starts at the same
714 * address as the first existing one. If not or if some overlapping
715 * slot comes around later, we will fail (not seen in practice so far)
716 * - and actually require a recent KVM version. */
717 if (s->broken_set_mem_region &&
718 old.start_addr == start_addr && old.memory_size < size && add) {
719 mem = kvm_alloc_slot(s);
720 mem->memory_size = old.memory_size;
721 mem->start_addr = old.start_addr;
722 mem->ram = old.ram;
723 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
725 err = kvm_set_user_memory_region(s, mem);
726 if (err) {
727 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
728 strerror(-err));
729 abort();
732 start_addr += old.memory_size;
733 ram += old.memory_size;
734 size -= old.memory_size;
735 continue;
738 /* register prefix slot */
739 if (old.start_addr < start_addr) {
740 mem = kvm_alloc_slot(s);
741 mem->memory_size = start_addr - old.start_addr;
742 mem->start_addr = old.start_addr;
743 mem->ram = old.ram;
744 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
746 err = kvm_set_user_memory_region(s, mem);
747 if (err) {
748 fprintf(stderr, "%s: error registering prefix slot: %s\n",
749 __func__, strerror(-err));
750 #ifdef TARGET_PPC
751 fprintf(stderr, "%s: This is probably because your kernel's " \
752 "PAGE_SIZE is too big. Please try to use 4k " \
753 "PAGE_SIZE!\n", __func__);
754 #endif
755 abort();
759 /* register suffix slot */
760 if (old.start_addr + old.memory_size > start_addr + size) {
761 ram_addr_t size_delta;
763 mem = kvm_alloc_slot(s);
764 mem->start_addr = start_addr + size;
765 size_delta = mem->start_addr - old.start_addr;
766 mem->memory_size = old.memory_size - size_delta;
767 mem->ram = old.ram + size_delta;
768 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
770 err = kvm_set_user_memory_region(s, mem);
771 if (err) {
772 fprintf(stderr, "%s: error registering suffix slot: %s\n",
773 __func__, strerror(-err));
774 abort();
779 /* in case the KVM bug workaround already "consumed" the new slot */
780 if (!size) {
781 return;
783 if (!add) {
784 return;
786 mem = kvm_alloc_slot(s);
787 mem->memory_size = size;
788 mem->start_addr = start_addr;
789 mem->ram = ram;
790 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
792 err = kvm_set_user_memory_region(s, mem);
793 if (err) {
794 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
795 strerror(-err));
796 abort();
800 static void kvm_region_add(MemoryListener *listener,
801 MemoryRegionSection *section)
803 memory_region_ref(section->mr);
804 kvm_set_phys_mem(section, true);
807 static void kvm_region_del(MemoryListener *listener,
808 MemoryRegionSection *section)
810 kvm_set_phys_mem(section, false);
811 memory_region_unref(section->mr);
814 static void kvm_log_sync(MemoryListener *listener,
815 MemoryRegionSection *section)
817 int r;
819 r = kvm_physical_sync_dirty_bitmap(section);
820 if (r < 0) {
821 abort();
825 static void kvm_log_global_start(struct MemoryListener *listener)
827 int r;
829 r = kvm_set_migration_log(1);
830 assert(r >= 0);
833 static void kvm_log_global_stop(struct MemoryListener *listener)
835 int r;
837 r = kvm_set_migration_log(0);
838 assert(r >= 0);
841 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
842 MemoryRegionSection *section,
843 bool match_data, uint64_t data,
844 EventNotifier *e)
846 int fd = event_notifier_get_fd(e);
847 int r;
849 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
850 data, true, int128_get64(section->size),
851 match_data);
852 if (r < 0) {
853 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
854 __func__, strerror(-r));
855 abort();
859 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
860 MemoryRegionSection *section,
861 bool match_data, uint64_t data,
862 EventNotifier *e)
864 int fd = event_notifier_get_fd(e);
865 int r;
867 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
868 data, false, int128_get64(section->size),
869 match_data);
870 if (r < 0) {
871 abort();
875 static void kvm_io_ioeventfd_add(MemoryListener *listener,
876 MemoryRegionSection *section,
877 bool match_data, uint64_t data,
878 EventNotifier *e)
880 int fd = event_notifier_get_fd(e);
881 int r;
883 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
884 data, true, int128_get64(section->size),
885 match_data);
886 if (r < 0) {
887 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
888 __func__, strerror(-r));
889 abort();
893 static void kvm_io_ioeventfd_del(MemoryListener *listener,
894 MemoryRegionSection *section,
895 bool match_data, uint64_t data,
896 EventNotifier *e)
899 int fd = event_notifier_get_fd(e);
900 int r;
902 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
903 data, false, int128_get64(section->size),
904 match_data);
905 if (r < 0) {
906 abort();
910 static MemoryListener kvm_memory_listener = {
911 .region_add = kvm_region_add,
912 .region_del = kvm_region_del,
913 .log_start = kvm_log_start,
914 .log_stop = kvm_log_stop,
915 .log_sync = kvm_log_sync,
916 .log_global_start = kvm_log_global_start,
917 .log_global_stop = kvm_log_global_stop,
918 .eventfd_add = kvm_mem_ioeventfd_add,
919 .eventfd_del = kvm_mem_ioeventfd_del,
920 .coalesced_mmio_add = kvm_coalesce_mmio_region,
921 .coalesced_mmio_del = kvm_uncoalesce_mmio_region,
922 .priority = 10,
925 static MemoryListener kvm_io_listener = {
926 .eventfd_add = kvm_io_ioeventfd_add,
927 .eventfd_del = kvm_io_ioeventfd_del,
928 .priority = 10,
931 static void kvm_handle_interrupt(CPUState *cpu, int mask)
933 cpu->interrupt_request |= mask;
935 if (!qemu_cpu_is_self(cpu)) {
936 qemu_cpu_kick(cpu);
940 int kvm_set_irq(KVMState *s, int irq, int level)
942 struct kvm_irq_level event;
943 int ret;
945 assert(kvm_async_interrupts_enabled());
947 event.level = level;
948 event.irq = irq;
949 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
950 if (ret < 0) {
951 perror("kvm_set_irq");
952 abort();
955 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
958 #ifdef KVM_CAP_IRQ_ROUTING
959 typedef struct KVMMSIRoute {
960 struct kvm_irq_routing_entry kroute;
961 QTAILQ_ENTRY(KVMMSIRoute) entry;
962 } KVMMSIRoute;
964 static void set_gsi(KVMState *s, unsigned int gsi)
966 s->used_gsi_bitmap[gsi / 32] |= 1U << (gsi % 32);
969 static void clear_gsi(KVMState *s, unsigned int gsi)
971 s->used_gsi_bitmap[gsi / 32] &= ~(1U << (gsi % 32));
974 void kvm_init_irq_routing(KVMState *s)
976 int gsi_count, i;
978 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
979 if (gsi_count > 0) {
980 unsigned int gsi_bits, i;
982 /* Round up so we can search ints using ffs */
983 gsi_bits = ALIGN(gsi_count, 32);
984 s->used_gsi_bitmap = g_malloc0(gsi_bits / 8);
985 s->gsi_count = gsi_count;
987 /* Mark any over-allocated bits as already in use */
988 for (i = gsi_count; i < gsi_bits; i++) {
989 set_gsi(s, i);
993 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
994 s->nr_allocated_irq_routes = 0;
996 if (!s->direct_msi) {
997 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
998 QTAILQ_INIT(&s->msi_hashtab[i]);
1002 kvm_arch_init_irq_routing(s);
1005 void kvm_irqchip_commit_routes(KVMState *s)
1007 int ret;
1009 s->irq_routes->flags = 0;
1010 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1011 assert(ret == 0);
1014 static void kvm_add_routing_entry(KVMState *s,
1015 struct kvm_irq_routing_entry *entry)
1017 struct kvm_irq_routing_entry *new;
1018 int n, size;
1020 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1021 n = s->nr_allocated_irq_routes * 2;
1022 if (n < 64) {
1023 n = 64;
1025 size = sizeof(struct kvm_irq_routing);
1026 size += n * sizeof(*new);
1027 s->irq_routes = g_realloc(s->irq_routes, size);
1028 s->nr_allocated_irq_routes = n;
1030 n = s->irq_routes->nr++;
1031 new = &s->irq_routes->entries[n];
1033 *new = *entry;
1035 set_gsi(s, entry->gsi);
1038 static int kvm_update_routing_entry(KVMState *s,
1039 struct kvm_irq_routing_entry *new_entry)
1041 struct kvm_irq_routing_entry *entry;
1042 int n;
1044 for (n = 0; n < s->irq_routes->nr; n++) {
1045 entry = &s->irq_routes->entries[n];
1046 if (entry->gsi != new_entry->gsi) {
1047 continue;
1050 if(!memcmp(entry, new_entry, sizeof *entry)) {
1051 return 0;
1054 *entry = *new_entry;
1056 kvm_irqchip_commit_routes(s);
1058 return 0;
1061 return -ESRCH;
1064 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1066 struct kvm_irq_routing_entry e = {};
1068 assert(pin < s->gsi_count);
1070 e.gsi = irq;
1071 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1072 e.flags = 0;
1073 e.u.irqchip.irqchip = irqchip;
1074 e.u.irqchip.pin = pin;
1075 kvm_add_routing_entry(s, &e);
1078 void kvm_irqchip_release_virq(KVMState *s, int virq)
1080 struct kvm_irq_routing_entry *e;
1081 int i;
1083 if (kvm_gsi_direct_mapping()) {
1084 return;
1087 for (i = 0; i < s->irq_routes->nr; i++) {
1088 e = &s->irq_routes->entries[i];
1089 if (e->gsi == virq) {
1090 s->irq_routes->nr--;
1091 *e = s->irq_routes->entries[s->irq_routes->nr];
1094 clear_gsi(s, virq);
1097 static unsigned int kvm_hash_msi(uint32_t data)
1099 /* This is optimized for IA32 MSI layout. However, no other arch shall
1100 * repeat the mistake of not providing a direct MSI injection API. */
1101 return data & 0xff;
1104 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1106 KVMMSIRoute *route, *next;
1107 unsigned int hash;
1109 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1110 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1111 kvm_irqchip_release_virq(s, route->kroute.gsi);
1112 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1113 g_free(route);
1118 static int kvm_irqchip_get_virq(KVMState *s)
1120 uint32_t *word = s->used_gsi_bitmap;
1121 int max_words = ALIGN(s->gsi_count, 32) / 32;
1122 int i, bit;
1123 bool retry = true;
1125 again:
1126 /* Return the lowest unused GSI in the bitmap */
1127 for (i = 0; i < max_words; i++) {
1128 bit = ffs(~word[i]);
1129 if (!bit) {
1130 continue;
1133 return bit - 1 + i * 32;
1135 if (!s->direct_msi && retry) {
1136 retry = false;
1137 kvm_flush_dynamic_msi_routes(s);
1138 goto again;
1140 return -ENOSPC;
1144 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1146 unsigned int hash = kvm_hash_msi(msg.data);
1147 KVMMSIRoute *route;
1149 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1150 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1151 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1152 route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1153 return route;
1156 return NULL;
1159 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1161 struct kvm_msi msi;
1162 KVMMSIRoute *route;
1164 if (s->direct_msi) {
1165 msi.address_lo = (uint32_t)msg.address;
1166 msi.address_hi = msg.address >> 32;
1167 msi.data = le32_to_cpu(msg.data);
1168 msi.flags = 0;
1169 memset(msi.pad, 0, sizeof(msi.pad));
1171 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1174 route = kvm_lookup_msi_route(s, msg);
1175 if (!route) {
1176 int virq;
1178 virq = kvm_irqchip_get_virq(s);
1179 if (virq < 0) {
1180 return virq;
1183 route = g_malloc0(sizeof(KVMMSIRoute));
1184 route->kroute.gsi = virq;
1185 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1186 route->kroute.flags = 0;
1187 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1188 route->kroute.u.msi.address_hi = msg.address >> 32;
1189 route->kroute.u.msi.data = le32_to_cpu(msg.data);
1191 kvm_add_routing_entry(s, &route->kroute);
1192 kvm_irqchip_commit_routes(s);
1194 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1195 entry);
1198 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1200 return kvm_set_irq(s, route->kroute.gsi, 1);
1203 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1205 struct kvm_irq_routing_entry kroute = {};
1206 int virq;
1208 if (kvm_gsi_direct_mapping()) {
1209 return msg.data & 0xffff;
1212 if (!kvm_gsi_routing_enabled()) {
1213 return -ENOSYS;
1216 virq = kvm_irqchip_get_virq(s);
1217 if (virq < 0) {
1218 return virq;
1221 kroute.gsi = virq;
1222 kroute.type = KVM_IRQ_ROUTING_MSI;
1223 kroute.flags = 0;
1224 kroute.u.msi.address_lo = (uint32_t)msg.address;
1225 kroute.u.msi.address_hi = msg.address >> 32;
1226 kroute.u.msi.data = le32_to_cpu(msg.data);
1228 kvm_add_routing_entry(s, &kroute);
1229 kvm_irqchip_commit_routes(s);
1231 return virq;
1234 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1236 struct kvm_irq_routing_entry kroute = {};
1238 if (kvm_gsi_direct_mapping()) {
1239 return 0;
1242 if (!kvm_irqchip_in_kernel()) {
1243 return -ENOSYS;
1246 kroute.gsi = virq;
1247 kroute.type = KVM_IRQ_ROUTING_MSI;
1248 kroute.flags = 0;
1249 kroute.u.msi.address_lo = (uint32_t)msg.address;
1250 kroute.u.msi.address_hi = msg.address >> 32;
1251 kroute.u.msi.data = le32_to_cpu(msg.data);
1253 return kvm_update_routing_entry(s, &kroute);
1256 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int rfd, int virq,
1257 bool assign)
1259 struct kvm_irqfd irqfd = {
1260 .fd = fd,
1261 .gsi = virq,
1262 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1265 if (rfd != -1) {
1266 irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1267 irqfd.resamplefd = rfd;
1270 if (!kvm_irqfds_enabled()) {
1271 return -ENOSYS;
1274 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1277 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1279 struct kvm_irq_routing_entry kroute;
1280 int virq;
1282 if (!kvm_gsi_routing_enabled()) {
1283 return -ENOSYS;
1286 virq = kvm_irqchip_get_virq(s);
1287 if (virq < 0) {
1288 return virq;
1291 kroute.gsi = virq;
1292 kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1293 kroute.flags = 0;
1294 kroute.u.adapter.summary_addr = adapter->summary_addr;
1295 kroute.u.adapter.ind_addr = adapter->ind_addr;
1296 kroute.u.adapter.summary_offset = adapter->summary_offset;
1297 kroute.u.adapter.ind_offset = adapter->ind_offset;
1298 kroute.u.adapter.adapter_id = adapter->adapter_id;
1300 kvm_add_routing_entry(s, &kroute);
1301 kvm_irqchip_commit_routes(s);
1303 return virq;
1306 #else /* !KVM_CAP_IRQ_ROUTING */
1308 void kvm_init_irq_routing(KVMState *s)
1312 void kvm_irqchip_release_virq(KVMState *s, int virq)
1316 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1318 abort();
1321 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1323 return -ENOSYS;
1326 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1328 return -ENOSYS;
1331 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1333 abort();
1336 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1338 return -ENOSYS;
1340 #endif /* !KVM_CAP_IRQ_ROUTING */
1342 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1343 EventNotifier *rn, int virq)
1345 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n),
1346 rn ? event_notifier_get_fd(rn) : -1, virq, true);
1349 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n, int virq)
1351 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), -1, virq,
1352 false);
1355 static int kvm_irqchip_create(KVMState *s)
1357 int ret;
1359 if (!qemu_opt_get_bool(qemu_get_machine_opts(), "kernel_irqchip", true) ||
1360 (!kvm_check_extension(s, KVM_CAP_IRQCHIP) &&
1361 (kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0) < 0))) {
1362 return 0;
1365 /* First probe and see if there's a arch-specific hook to create the
1366 * in-kernel irqchip for us */
1367 ret = kvm_arch_irqchip_create(s);
1368 if (ret < 0) {
1369 return ret;
1370 } else if (ret == 0) {
1371 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1372 if (ret < 0) {
1373 fprintf(stderr, "Create kernel irqchip failed\n");
1374 return ret;
1378 kvm_kernel_irqchip = true;
1379 /* If we have an in-kernel IRQ chip then we must have asynchronous
1380 * interrupt delivery (though the reverse is not necessarily true)
1382 kvm_async_interrupts_allowed = true;
1383 kvm_halt_in_kernel_allowed = true;
1385 kvm_init_irq_routing(s);
1387 return 0;
1390 /* Find number of supported CPUs using the recommended
1391 * procedure from the kernel API documentation to cope with
1392 * older kernels that may be missing capabilities.
1394 static int kvm_recommended_vcpus(KVMState *s)
1396 int ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
1397 return (ret) ? ret : 4;
1400 static int kvm_max_vcpus(KVMState *s)
1402 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1403 return (ret) ? ret : kvm_recommended_vcpus(s);
1406 static int kvm_init(MachineState *ms)
1408 MachineClass *mc = MACHINE_GET_CLASS(ms);
1409 static const char upgrade_note[] =
1410 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1411 "(see http://sourceforge.net/projects/kvm).\n";
1412 struct {
1413 const char *name;
1414 int num;
1415 } num_cpus[] = {
1416 { "SMP", smp_cpus },
1417 { "hotpluggable", max_cpus },
1418 { NULL, }
1419 }, *nc = num_cpus;
1420 int soft_vcpus_limit, hard_vcpus_limit;
1421 KVMState *s;
1422 const KVMCapabilityInfo *missing_cap;
1423 int ret;
1424 int i, type = 0;
1425 const char *kvm_type;
1427 s = KVM_STATE(ms->accelerator);
1430 * On systems where the kernel can support different base page
1431 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1432 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1433 * page size for the system though.
1435 assert(TARGET_PAGE_SIZE <= getpagesize());
1436 page_size_init();
1438 s->sigmask_len = 8;
1440 #ifdef KVM_CAP_SET_GUEST_DEBUG
1441 QTAILQ_INIT(&s->kvm_sw_breakpoints);
1442 #endif
1443 s->vmfd = -1;
1444 s->fd = qemu_open("/dev/kvm", O_RDWR);
1445 if (s->fd == -1) {
1446 fprintf(stderr, "Could not access KVM kernel module: %m\n");
1447 ret = -errno;
1448 goto err;
1451 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1452 if (ret < KVM_API_VERSION) {
1453 if (ret >= 0) {
1454 ret = -EINVAL;
1456 fprintf(stderr, "kvm version too old\n");
1457 goto err;
1460 if (ret > KVM_API_VERSION) {
1461 ret = -EINVAL;
1462 fprintf(stderr, "kvm version not supported\n");
1463 goto err;
1466 s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
1468 /* If unspecified, use the default value */
1469 if (!s->nr_slots) {
1470 s->nr_slots = 32;
1473 s->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
1475 for (i = 0; i < s->nr_slots; i++) {
1476 s->slots[i].slot = i;
1479 /* check the vcpu limits */
1480 soft_vcpus_limit = kvm_recommended_vcpus(s);
1481 hard_vcpus_limit = kvm_max_vcpus(s);
1483 while (nc->name) {
1484 if (nc->num > soft_vcpus_limit) {
1485 fprintf(stderr,
1486 "Warning: Number of %s cpus requested (%d) exceeds "
1487 "the recommended cpus supported by KVM (%d)\n",
1488 nc->name, nc->num, soft_vcpus_limit);
1490 if (nc->num > hard_vcpus_limit) {
1491 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
1492 "the maximum cpus supported by KVM (%d)\n",
1493 nc->name, nc->num, hard_vcpus_limit);
1494 exit(1);
1497 nc++;
1500 kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1501 if (mc->kvm_type) {
1502 type = mc->kvm_type(kvm_type);
1503 } else if (kvm_type) {
1504 ret = -EINVAL;
1505 fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1506 goto err;
1509 do {
1510 ret = kvm_ioctl(s, KVM_CREATE_VM, type);
1511 } while (ret == -EINTR);
1513 if (ret < 0) {
1514 fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
1515 strerror(-ret));
1517 #ifdef TARGET_S390X
1518 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
1519 "your host kernel command line\n");
1520 #endif
1521 goto err;
1524 s->vmfd = ret;
1525 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1526 if (!missing_cap) {
1527 missing_cap =
1528 kvm_check_extension_list(s, kvm_arch_required_capabilities);
1530 if (missing_cap) {
1531 ret = -EINVAL;
1532 fprintf(stderr, "kvm does not support %s\n%s",
1533 missing_cap->name, upgrade_note);
1534 goto err;
1537 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1539 s->broken_set_mem_region = 1;
1540 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
1541 if (ret > 0) {
1542 s->broken_set_mem_region = 0;
1545 #ifdef KVM_CAP_VCPU_EVENTS
1546 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1547 #endif
1549 s->robust_singlestep =
1550 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1552 #ifdef KVM_CAP_DEBUGREGS
1553 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1554 #endif
1556 #ifdef KVM_CAP_XSAVE
1557 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1558 #endif
1560 #ifdef KVM_CAP_XCRS
1561 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1562 #endif
1564 #ifdef KVM_CAP_PIT_STATE2
1565 s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1566 #endif
1568 #ifdef KVM_CAP_IRQ_ROUTING
1569 s->direct_msi = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1570 #endif
1572 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1574 s->irq_set_ioctl = KVM_IRQ_LINE;
1575 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1576 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1579 #ifdef KVM_CAP_READONLY_MEM
1580 kvm_readonly_mem_allowed =
1581 (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1582 #endif
1584 kvm_eventfds_allowed =
1585 (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
1587 ret = kvm_arch_init(s);
1588 if (ret < 0) {
1589 goto err;
1592 ret = kvm_irqchip_create(s);
1593 if (ret < 0) {
1594 goto err;
1597 kvm_state = s;
1598 memory_listener_register(&kvm_memory_listener, &address_space_memory);
1599 memory_listener_register(&kvm_io_listener, &address_space_io);
1601 s->many_ioeventfds = kvm_check_many_ioeventfds();
1603 cpu_interrupt_handler = kvm_handle_interrupt;
1605 return 0;
1607 err:
1608 assert(ret < 0);
1609 if (s->vmfd >= 0) {
1610 close(s->vmfd);
1612 if (s->fd != -1) {
1613 close(s->fd);
1615 g_free(s->slots);
1617 return ret;
1620 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
1622 s->sigmask_len = sigmask_len;
1625 static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
1626 uint32_t count)
1628 int i;
1629 uint8_t *ptr = data;
1631 for (i = 0; i < count; i++) {
1632 address_space_rw(&address_space_io, port, ptr, size,
1633 direction == KVM_EXIT_IO_OUT);
1634 ptr += size;
1638 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
1640 fprintf(stderr, "KVM internal error. Suberror: %d\n",
1641 run->internal.suberror);
1643 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1644 int i;
1646 for (i = 0; i < run->internal.ndata; ++i) {
1647 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1648 i, (uint64_t)run->internal.data[i]);
1651 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1652 fprintf(stderr, "emulation failure\n");
1653 if (!kvm_arch_stop_on_emulation_error(cpu)) {
1654 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1655 return EXCP_INTERRUPT;
1658 /* FIXME: Should trigger a qmp message to let management know
1659 * something went wrong.
1661 return -1;
1664 void kvm_flush_coalesced_mmio_buffer(void)
1666 KVMState *s = kvm_state;
1668 if (s->coalesced_flush_in_progress) {
1669 return;
1672 s->coalesced_flush_in_progress = true;
1674 if (s->coalesced_mmio_ring) {
1675 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1676 while (ring->first != ring->last) {
1677 struct kvm_coalesced_mmio *ent;
1679 ent = &ring->coalesced_mmio[ring->first];
1681 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1682 smp_wmb();
1683 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1687 s->coalesced_flush_in_progress = false;
1690 static void do_kvm_cpu_synchronize_state(void *arg)
1692 CPUState *cpu = arg;
1694 if (!cpu->kvm_vcpu_dirty) {
1695 kvm_arch_get_registers(cpu);
1696 cpu->kvm_vcpu_dirty = true;
1700 void kvm_cpu_synchronize_state(CPUState *cpu)
1702 if (!cpu->kvm_vcpu_dirty) {
1703 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, cpu);
1707 static void do_kvm_cpu_synchronize_post_reset(void *arg)
1709 CPUState *cpu = arg;
1711 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1712 cpu->kvm_vcpu_dirty = false;
1715 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
1717 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, cpu);
1720 static void do_kvm_cpu_synchronize_post_init(void *arg)
1722 CPUState *cpu = arg;
1724 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1725 cpu->kvm_vcpu_dirty = false;
1728 void kvm_cpu_synchronize_post_init(CPUState *cpu)
1730 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, cpu);
1733 void kvm_cpu_clean_state(CPUState *cpu)
1735 cpu->kvm_vcpu_dirty = false;
1738 int kvm_cpu_exec(CPUState *cpu)
1740 struct kvm_run *run = cpu->kvm_run;
1741 int ret, run_ret;
1743 DPRINTF("kvm_cpu_exec()\n");
1745 if (kvm_arch_process_async_events(cpu)) {
1746 cpu->exit_request = 0;
1747 return EXCP_HLT;
1750 do {
1751 if (cpu->kvm_vcpu_dirty) {
1752 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1753 cpu->kvm_vcpu_dirty = false;
1756 kvm_arch_pre_run(cpu, run);
1757 if (cpu->exit_request) {
1758 DPRINTF("interrupt exit requested\n");
1760 * KVM requires us to reenter the kernel after IO exits to complete
1761 * instruction emulation. This self-signal will ensure that we
1762 * leave ASAP again.
1764 qemu_cpu_kick_self();
1766 qemu_mutex_unlock_iothread();
1768 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
1770 qemu_mutex_lock_iothread();
1771 kvm_arch_post_run(cpu, run);
1773 if (run_ret < 0) {
1774 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1775 DPRINTF("io window exit\n");
1776 ret = EXCP_INTERRUPT;
1777 break;
1779 fprintf(stderr, "error: kvm run failed %s\n",
1780 strerror(-run_ret));
1781 ret = -1;
1782 break;
1785 trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
1786 switch (run->exit_reason) {
1787 case KVM_EXIT_IO:
1788 DPRINTF("handle_io\n");
1789 kvm_handle_io(run->io.port,
1790 (uint8_t *)run + run->io.data_offset,
1791 run->io.direction,
1792 run->io.size,
1793 run->io.count);
1794 ret = 0;
1795 break;
1796 case KVM_EXIT_MMIO:
1797 DPRINTF("handle_mmio\n");
1798 cpu_physical_memory_rw(run->mmio.phys_addr,
1799 run->mmio.data,
1800 run->mmio.len,
1801 run->mmio.is_write);
1802 ret = 0;
1803 break;
1804 case KVM_EXIT_IRQ_WINDOW_OPEN:
1805 DPRINTF("irq_window_open\n");
1806 ret = EXCP_INTERRUPT;
1807 break;
1808 case KVM_EXIT_SHUTDOWN:
1809 DPRINTF("shutdown\n");
1810 qemu_system_reset_request();
1811 ret = EXCP_INTERRUPT;
1812 break;
1813 case KVM_EXIT_UNKNOWN:
1814 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1815 (uint64_t)run->hw.hardware_exit_reason);
1816 ret = -1;
1817 break;
1818 case KVM_EXIT_INTERNAL_ERROR:
1819 ret = kvm_handle_internal_error(cpu, run);
1820 break;
1821 case KVM_EXIT_SYSTEM_EVENT:
1822 switch (run->system_event.type) {
1823 case KVM_SYSTEM_EVENT_SHUTDOWN:
1824 qemu_system_shutdown_request();
1825 ret = EXCP_INTERRUPT;
1826 break;
1827 case KVM_SYSTEM_EVENT_RESET:
1828 qemu_system_reset_request();
1829 ret = EXCP_INTERRUPT;
1830 break;
1831 default:
1832 DPRINTF("kvm_arch_handle_exit\n");
1833 ret = kvm_arch_handle_exit(cpu, run);
1834 break;
1836 break;
1837 default:
1838 DPRINTF("kvm_arch_handle_exit\n");
1839 ret = kvm_arch_handle_exit(cpu, run);
1840 break;
1842 } while (ret == 0);
1844 if (ret < 0) {
1845 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1846 vm_stop(RUN_STATE_INTERNAL_ERROR);
1849 cpu->exit_request = 0;
1850 return ret;
1853 int kvm_ioctl(KVMState *s, int type, ...)
1855 int ret;
1856 void *arg;
1857 va_list ap;
1859 va_start(ap, type);
1860 arg = va_arg(ap, void *);
1861 va_end(ap);
1863 trace_kvm_ioctl(type, arg);
1864 ret = ioctl(s->fd, type, arg);
1865 if (ret == -1) {
1866 ret = -errno;
1868 return ret;
1871 int kvm_vm_ioctl(KVMState *s, int type, ...)
1873 int ret;
1874 void *arg;
1875 va_list ap;
1877 va_start(ap, type);
1878 arg = va_arg(ap, void *);
1879 va_end(ap);
1881 trace_kvm_vm_ioctl(type, arg);
1882 ret = ioctl(s->vmfd, type, arg);
1883 if (ret == -1) {
1884 ret = -errno;
1886 return ret;
1889 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
1891 int ret;
1892 void *arg;
1893 va_list ap;
1895 va_start(ap, type);
1896 arg = va_arg(ap, void *);
1897 va_end(ap);
1899 trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
1900 ret = ioctl(cpu->kvm_fd, type, arg);
1901 if (ret == -1) {
1902 ret = -errno;
1904 return ret;
1907 int kvm_device_ioctl(int fd, int type, ...)
1909 int ret;
1910 void *arg;
1911 va_list ap;
1913 va_start(ap, type);
1914 arg = va_arg(ap, void *);
1915 va_end(ap);
1917 trace_kvm_device_ioctl(fd, type, arg);
1918 ret = ioctl(fd, type, arg);
1919 if (ret == -1) {
1920 ret = -errno;
1922 return ret;
1925 int kvm_has_sync_mmu(void)
1927 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1930 int kvm_has_vcpu_events(void)
1932 return kvm_state->vcpu_events;
1935 int kvm_has_robust_singlestep(void)
1937 return kvm_state->robust_singlestep;
1940 int kvm_has_debugregs(void)
1942 return kvm_state->debugregs;
1945 int kvm_has_xsave(void)
1947 return kvm_state->xsave;
1950 int kvm_has_xcrs(void)
1952 return kvm_state->xcrs;
1955 int kvm_has_pit_state2(void)
1957 return kvm_state->pit_state2;
1960 int kvm_has_many_ioeventfds(void)
1962 if (!kvm_enabled()) {
1963 return 0;
1965 return kvm_state->many_ioeventfds;
1968 int kvm_has_gsi_routing(void)
1970 #ifdef KVM_CAP_IRQ_ROUTING
1971 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
1972 #else
1973 return false;
1974 #endif
1977 int kvm_has_intx_set_mask(void)
1979 return kvm_state->intx_set_mask;
1982 void kvm_setup_guest_memory(void *start, size_t size)
1984 if (!kvm_has_sync_mmu()) {
1985 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1987 if (ret) {
1988 perror("qemu_madvise");
1989 fprintf(stderr,
1990 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1991 exit(1);
1996 #ifdef KVM_CAP_SET_GUEST_DEBUG
1997 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
1998 target_ulong pc)
2000 struct kvm_sw_breakpoint *bp;
2002 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
2003 if (bp->pc == pc) {
2004 return bp;
2007 return NULL;
2010 int kvm_sw_breakpoints_active(CPUState *cpu)
2012 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
2015 struct kvm_set_guest_debug_data {
2016 struct kvm_guest_debug dbg;
2017 CPUState *cpu;
2018 int err;
2021 static void kvm_invoke_set_guest_debug(void *data)
2023 struct kvm_set_guest_debug_data *dbg_data = data;
2025 dbg_data->err = kvm_vcpu_ioctl(dbg_data->cpu, KVM_SET_GUEST_DEBUG,
2026 &dbg_data->dbg);
2029 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2031 struct kvm_set_guest_debug_data data;
2033 data.dbg.control = reinject_trap;
2035 if (cpu->singlestep_enabled) {
2036 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2038 kvm_arch_update_guest_debug(cpu, &data.dbg);
2039 data.cpu = cpu;
2041 run_on_cpu(cpu, kvm_invoke_set_guest_debug, &data);
2042 return data.err;
2045 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2046 target_ulong len, int type)
2048 struct kvm_sw_breakpoint *bp;
2049 int err;
2051 if (type == GDB_BREAKPOINT_SW) {
2052 bp = kvm_find_sw_breakpoint(cpu, addr);
2053 if (bp) {
2054 bp->use_count++;
2055 return 0;
2058 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2059 if (!bp) {
2060 return -ENOMEM;
2063 bp->pc = addr;
2064 bp->use_count = 1;
2065 err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2066 if (err) {
2067 g_free(bp);
2068 return err;
2071 QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2072 } else {
2073 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2074 if (err) {
2075 return err;
2079 CPU_FOREACH(cpu) {
2080 err = kvm_update_guest_debug(cpu, 0);
2081 if (err) {
2082 return err;
2085 return 0;
2088 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2089 target_ulong len, int type)
2091 struct kvm_sw_breakpoint *bp;
2092 int err;
2094 if (type == GDB_BREAKPOINT_SW) {
2095 bp = kvm_find_sw_breakpoint(cpu, addr);
2096 if (!bp) {
2097 return -ENOENT;
2100 if (bp->use_count > 1) {
2101 bp->use_count--;
2102 return 0;
2105 err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2106 if (err) {
2107 return err;
2110 QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2111 g_free(bp);
2112 } else {
2113 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2114 if (err) {
2115 return err;
2119 CPU_FOREACH(cpu) {
2120 err = kvm_update_guest_debug(cpu, 0);
2121 if (err) {
2122 return err;
2125 return 0;
2128 void kvm_remove_all_breakpoints(CPUState *cpu)
2130 struct kvm_sw_breakpoint *bp, *next;
2131 KVMState *s = cpu->kvm_state;
2132 CPUState *tmpcpu;
2134 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2135 if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2136 /* Try harder to find a CPU that currently sees the breakpoint. */
2137 CPU_FOREACH(tmpcpu) {
2138 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2139 break;
2143 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2144 g_free(bp);
2146 kvm_arch_remove_all_hw_breakpoints();
2148 CPU_FOREACH(cpu) {
2149 kvm_update_guest_debug(cpu, 0);
2153 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2155 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2157 return -EINVAL;
2160 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2161 target_ulong len, int type)
2163 return -EINVAL;
2166 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2167 target_ulong len, int type)
2169 return -EINVAL;
2172 void kvm_remove_all_breakpoints(CPUState *cpu)
2175 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2177 int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2179 KVMState *s = kvm_state;
2180 struct kvm_signal_mask *sigmask;
2181 int r;
2183 if (!sigset) {
2184 return kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, NULL);
2187 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2189 sigmask->len = s->sigmask_len;
2190 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2191 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2192 g_free(sigmask);
2194 return r;
2196 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2198 return kvm_arch_on_sigbus_vcpu(cpu, code, addr);
2201 int kvm_on_sigbus(int code, void *addr)
2203 return kvm_arch_on_sigbus(code, addr);
2206 int kvm_create_device(KVMState *s, uint64_t type, bool test)
2208 int ret;
2209 struct kvm_create_device create_dev;
2211 create_dev.type = type;
2212 create_dev.fd = -1;
2213 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2215 if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2216 return -ENOTSUP;
2219 ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2220 if (ret) {
2221 return ret;
2224 return test ? 0 : create_dev.fd;
2227 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2229 struct kvm_one_reg reg;
2230 int r;
2232 reg.id = id;
2233 reg.addr = (uintptr_t) source;
2234 r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
2235 if (r) {
2236 trace_kvm_failed_reg_set(id, strerror(r));
2238 return r;
2241 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2243 struct kvm_one_reg reg;
2244 int r;
2246 reg.id = id;
2247 reg.addr = (uintptr_t) target;
2248 r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
2249 if (r) {
2250 trace_kvm_failed_reg_get(id, strerror(r));
2252 return r;
2255 static void kvm_accel_class_init(ObjectClass *oc, void *data)
2257 AccelClass *ac = ACCEL_CLASS(oc);
2258 ac->name = "KVM";
2259 ac->init_machine = kvm_init;
2260 ac->allowed = &kvm_allowed;
2263 static const TypeInfo kvm_accel_type = {
2264 .name = TYPE_KVM_ACCEL,
2265 .parent = TYPE_ACCEL,
2266 .class_init = kvm_accel_class_init,
2267 .instance_size = sizeof(KVMState),
2270 static void kvm_type_init(void)
2272 type_register_static(&kvm_accel_type);
2275 type_init(kvm_type_init);