4 * Copyright IBM, Corp. 2008
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 "qemu/osdep.h"
17 #include <sys/ioctl.h>
19 #include <linux/kvm.h>
21 #include "qemu/atomic.h"
22 #include "qemu/option.h"
23 #include "qemu/config-file.h"
24 #include "qemu/error-report.h"
25 #include "qapi/error.h"
26 #include "hw/pci/msi.h"
27 #include "hw/pci/msix.h"
28 #include "hw/s390x/adapter.h"
29 #include "exec/gdbstub.h"
30 #include "sysemu/kvm_int.h"
31 #include "sysemu/cpus.h"
32 #include "qemu/bswap.h"
33 #include "exec/memory.h"
34 #include "exec/ram_addr.h"
35 #include "exec/address-spaces.h"
36 #include "qemu/event_notifier.h"
37 #include "qemu/main-loop.h"
40 #include "sysemu/sev.h"
41 #include "sysemu/balloon.h"
43 #include "hw/boards.h"
45 /* This check must be after config-host.h is included */
47 #include <sys/eventfd.h>
50 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
51 * need to use the real host PAGE_SIZE, as that's what KVM will use.
53 #define PAGE_SIZE getpagesize()
58 #define DPRINTF(fmt, ...) \
59 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
61 #define DPRINTF(fmt, ...) \
65 #define KVM_MSI_HASHTAB_SIZE 256
67 struct KVMParkedVcpu {
68 unsigned long vcpu_id;
70 QLIST_ENTRY(KVMParkedVcpu) node;
75 AccelState parent_obj;
82 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
83 bool coalesced_flush_in_progress;
85 int robust_singlestep;
87 #ifdef KVM_CAP_SET_GUEST_DEBUG
88 QTAILQ_HEAD(, kvm_sw_breakpoint) kvm_sw_breakpoints;
90 int max_nested_state_len;
94 bool manual_dirty_log_protect;
95 /* The man page (and posix) say ioctl numbers are signed int, but
96 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
97 * unsigned, and treating them as signed here can break things */
98 unsigned irq_set_ioctl;
99 unsigned int sigmask_len;
101 #ifdef KVM_CAP_IRQ_ROUTING
102 struct kvm_irq_routing *irq_routes;
103 int nr_allocated_irq_routes;
104 unsigned long *used_gsi_bitmap;
105 unsigned int gsi_count;
106 QTAILQ_HEAD(, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
108 KVMMemoryListener memory_listener;
109 QLIST_HEAD(, KVMParkedVcpu) kvm_parked_vcpus;
111 /* memory encryption */
112 void *memcrypt_handle;
113 int (*memcrypt_encrypt_data)(void *handle, uint8_t *ptr, uint64_t len);
115 /* For "info mtree -f" to tell if an MR is registered in KVM */
118 KVMMemoryListener *ml;
124 bool kvm_kernel_irqchip;
125 bool kvm_split_irqchip;
126 bool kvm_async_interrupts_allowed;
127 bool kvm_halt_in_kernel_allowed;
128 bool kvm_eventfds_allowed;
129 bool kvm_irqfds_allowed;
130 bool kvm_resamplefds_allowed;
131 bool kvm_msi_via_irqfd_allowed;
132 bool kvm_gsi_routing_allowed;
133 bool kvm_gsi_direct_mapping;
135 bool kvm_readonly_mem_allowed;
136 bool kvm_vm_attributes_allowed;
137 bool kvm_direct_msi_allowed;
138 bool kvm_ioeventfd_any_length_allowed;
139 bool kvm_msi_use_devid;
140 static bool kvm_immediate_exit;
142 static const KVMCapabilityInfo kvm_required_capabilites[] = {
143 KVM_CAP_INFO(USER_MEMORY),
144 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
145 KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS),
149 #define kvm_slots_lock(kml) qemu_mutex_lock(&(kml)->slots_lock)
150 #define kvm_slots_unlock(kml) qemu_mutex_unlock(&(kml)->slots_lock)
152 int kvm_get_max_memslots(void)
154 KVMState *s = KVM_STATE(current_machine->accelerator);
159 bool kvm_memcrypt_enabled(void)
161 if (kvm_state && kvm_state->memcrypt_handle) {
168 int kvm_memcrypt_encrypt_data(uint8_t *ptr, uint64_t len)
170 if (kvm_state->memcrypt_handle &&
171 kvm_state->memcrypt_encrypt_data) {
172 return kvm_state->memcrypt_encrypt_data(kvm_state->memcrypt_handle,
179 /* Called with KVMMemoryListener.slots_lock held */
180 static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
182 KVMState *s = kvm_state;
185 for (i = 0; i < s->nr_slots; i++) {
186 if (kml->slots[i].memory_size == 0) {
187 return &kml->slots[i];
194 bool kvm_has_free_slot(MachineState *ms)
196 KVMState *s = KVM_STATE(ms->accelerator);
198 KVMMemoryListener *kml = &s->memory_listener;
201 result = !!kvm_get_free_slot(kml);
202 kvm_slots_unlock(kml);
207 /* Called with KVMMemoryListener.slots_lock held */
208 static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
210 KVMSlot *slot = kvm_get_free_slot(kml);
216 fprintf(stderr, "%s: no free slot available\n", __func__);
220 static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
224 KVMState *s = kvm_state;
227 for (i = 0; i < s->nr_slots; i++) {
228 KVMSlot *mem = &kml->slots[i];
230 if (start_addr == mem->start_addr && size == mem->memory_size) {
239 * Calculate and align the start address and the size of the section.
240 * Return the size. If the size is 0, the aligned section is empty.
242 static hwaddr kvm_align_section(MemoryRegionSection *section,
245 hwaddr size = int128_get64(section->size);
246 hwaddr delta, aligned;
248 /* kvm works in page size chunks, but the function may be called
249 with sub-page size and unaligned start address. Pad the start
250 address to next and truncate size to previous page boundary. */
251 aligned = ROUND_UP(section->offset_within_address_space,
252 qemu_real_host_page_size);
253 delta = aligned - section->offset_within_address_space;
259 return (size - delta) & qemu_real_host_page_mask;
262 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
265 KVMMemoryListener *kml = &s->memory_listener;
269 for (i = 0; i < s->nr_slots; i++) {
270 KVMSlot *mem = &kml->slots[i];
272 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
273 *phys_addr = mem->start_addr + (ram - mem->ram);
278 kvm_slots_unlock(kml);
283 static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot, bool new)
285 KVMState *s = kvm_state;
286 struct kvm_userspace_memory_region mem;
289 mem.slot = slot->slot | (kml->as_id << 16);
290 mem.guest_phys_addr = slot->start_addr;
291 mem.userspace_addr = (unsigned long)slot->ram;
292 mem.flags = slot->flags;
294 if (slot->memory_size && !new && (mem.flags ^ slot->old_flags) & KVM_MEM_READONLY) {
295 /* Set the slot size to 0 before setting the slot to the desired
296 * value. This is needed based on KVM commit 75d61fbc. */
298 kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
300 mem.memory_size = slot->memory_size;
301 ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
302 slot->old_flags = mem.flags;
303 trace_kvm_set_user_memory(mem.slot, mem.flags, mem.guest_phys_addr,
304 mem.memory_size, mem.userspace_addr, ret);
308 int kvm_destroy_vcpu(CPUState *cpu)
310 KVMState *s = kvm_state;
312 struct KVMParkedVcpu *vcpu = NULL;
315 DPRINTF("kvm_destroy_vcpu\n");
317 ret = kvm_arch_destroy_vcpu(cpu);
322 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
325 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
329 ret = munmap(cpu->kvm_run, mmap_size);
334 vcpu = g_malloc0(sizeof(*vcpu));
335 vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
336 vcpu->kvm_fd = cpu->kvm_fd;
337 QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
342 static int kvm_get_vcpu(KVMState *s, unsigned long vcpu_id)
344 struct KVMParkedVcpu *cpu;
346 QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
347 if (cpu->vcpu_id == vcpu_id) {
350 QLIST_REMOVE(cpu, node);
351 kvm_fd = cpu->kvm_fd;
357 return kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)vcpu_id);
360 int kvm_init_vcpu(CPUState *cpu)
362 KVMState *s = kvm_state;
366 DPRINTF("kvm_init_vcpu\n");
368 ret = kvm_get_vcpu(s, kvm_arch_vcpu_id(cpu));
370 DPRINTF("kvm_create_vcpu failed\n");
376 cpu->vcpu_dirty = true;
378 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
381 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
385 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
387 if (cpu->kvm_run == MAP_FAILED) {
389 DPRINTF("mmap'ing vcpu state failed\n");
393 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
394 s->coalesced_mmio_ring =
395 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
398 ret = kvm_arch_init_vcpu(cpu);
404 * dirty pages logging control
407 static int kvm_mem_flags(MemoryRegion *mr)
409 bool readonly = mr->readonly || memory_region_is_romd(mr);
412 if (memory_region_get_dirty_log_mask(mr) != 0) {
413 flags |= KVM_MEM_LOG_DIRTY_PAGES;
415 if (readonly && kvm_readonly_mem_allowed) {
416 flags |= KVM_MEM_READONLY;
421 /* Called with KVMMemoryListener.slots_lock held */
422 static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
425 mem->flags = kvm_mem_flags(mr);
427 /* If nothing changed effectively, no need to issue ioctl */
428 if (mem->flags == mem->old_flags) {
432 return kvm_set_user_memory_region(kml, mem, false);
435 static int kvm_section_update_flags(KVMMemoryListener *kml,
436 MemoryRegionSection *section)
438 hwaddr start_addr, size;
442 size = kvm_align_section(section, &start_addr);
449 mem = kvm_lookup_matching_slot(kml, start_addr, size);
451 /* We don't have a slot if we want to trap every access. */
455 ret = kvm_slot_update_flags(kml, mem, section->mr);
458 kvm_slots_unlock(kml);
462 static void kvm_log_start(MemoryListener *listener,
463 MemoryRegionSection *section,
466 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
473 r = kvm_section_update_flags(kml, section);
479 static void kvm_log_stop(MemoryListener *listener,
480 MemoryRegionSection *section,
483 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
490 r = kvm_section_update_flags(kml, section);
496 /* get kvm's dirty pages bitmap and update qemu's */
497 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
498 unsigned long *bitmap)
500 ram_addr_t start = section->offset_within_region +
501 memory_region_get_ram_addr(section->mr);
502 ram_addr_t pages = int128_get64(section->size) / getpagesize();
504 cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
508 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
511 * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
513 * This function will first try to fetch dirty bitmap from the kernel,
514 * and then updates qemu's dirty bitmap.
516 * NOTE: caller must be with kml->slots_lock held.
518 * @kml: the KVM memory listener object
519 * @section: the memory section to sync the dirty bitmap with
521 static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
522 MemoryRegionSection *section)
524 KVMState *s = kvm_state;
525 struct kvm_dirty_log d = {};
527 hwaddr start_addr, size;
530 size = kvm_align_section(section, &start_addr);
532 mem = kvm_lookup_matching_slot(kml, start_addr, size);
534 /* We don't have a slot if we want to trap every access. */
538 /* XXX bad kernel interface alert
539 * For dirty bitmap, kernel allocates array of size aligned to
540 * bits-per-long. But for case when the kernel is 64bits and
541 * the userspace is 32bits, userspace can't align to the same
542 * bits-per-long, since sizeof(long) is different between kernel
543 * and user space. This way, userspace will provide buffer which
544 * may be 4 bytes less than the kernel will use, resulting in
545 * userspace memory corruption (which is not detectable by valgrind
546 * too, in most cases).
547 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
548 * a hope that sizeof(long) won't become >8 any time soon.
550 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
551 /*HOST_LONG_BITS*/ 64) / 8;
552 if (!mem->dirty_bmap) {
553 /* Allocate on the first log_sync, once and for all */
554 mem->dirty_bmap = g_malloc0(size);
557 d.dirty_bitmap = mem->dirty_bmap;
558 d.slot = mem->slot | (kml->as_id << 16);
559 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
560 DPRINTF("ioctl failed %d\n", errno);
565 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
571 /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
572 #define KVM_CLEAR_LOG_SHIFT 6
573 #define KVM_CLEAR_LOG_ALIGN (qemu_real_host_page_size << KVM_CLEAR_LOG_SHIFT)
574 #define KVM_CLEAR_LOG_MASK (-KVM_CLEAR_LOG_ALIGN)
577 * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
579 * NOTE: this will be a no-op if we haven't enabled manual dirty log
580 * protection in the host kernel because in that case this operation
581 * will be done within log_sync().
583 * @kml: the kvm memory listener
584 * @section: the memory range to clear dirty bitmap
586 static int kvm_physical_log_clear(KVMMemoryListener *kml,
587 MemoryRegionSection *section)
589 KVMState *s = kvm_state;
590 struct kvm_clear_dirty_log d;
591 uint64_t start, end, bmap_start, start_delta, bmap_npages, size;
592 unsigned long *bmap_clear = NULL, psize = qemu_real_host_page_size;
596 if (!s->manual_dirty_log_protect) {
597 /* No need to do explicit clear */
601 start = section->offset_within_address_space;
602 size = int128_get64(section->size);
605 /* Nothing more we can do... */
611 /* Find any possible slot that covers the section */
612 for (i = 0; i < s->nr_slots; i++) {
613 mem = &kml->slots[i];
614 if (mem->start_addr <= start &&
615 start + size <= mem->start_addr + mem->memory_size) {
621 * We should always find one memslot until this point, otherwise
622 * there could be something wrong from the upper layer
624 assert(mem && i != s->nr_slots);
627 * We need to extend either the start or the size or both to
628 * satisfy the KVM interface requirement. Firstly, do the start
629 * page alignment on 64 host pages
631 bmap_start = (start - mem->start_addr) & KVM_CLEAR_LOG_MASK;
632 start_delta = start - mem->start_addr - bmap_start;
636 * The kernel interface has restriction on the size too, that either:
638 * (1) the size is 64 host pages aligned (just like the start), or
639 * (2) the size fills up until the end of the KVM memslot.
641 bmap_npages = DIV_ROUND_UP(size + start_delta, KVM_CLEAR_LOG_ALIGN)
642 << KVM_CLEAR_LOG_SHIFT;
643 end = mem->memory_size / psize;
644 if (bmap_npages > end - bmap_start) {
645 bmap_npages = end - bmap_start;
647 start_delta /= psize;
650 * Prepare the bitmap to clear dirty bits. Here we must guarantee
651 * that we won't clear any unknown dirty bits otherwise we might
652 * accidentally clear some set bits which are not yet synced from
653 * the kernel into QEMU's bitmap, then we'll lose track of the
654 * guest modifications upon those pages (which can directly lead
655 * to guest data loss or panic after migration).
657 * Layout of the KVMSlot.dirty_bmap:
659 * |<-------- bmap_npages -----------..>|
662 * |----------------|-------------|------------------|------------|
665 * start bmap_start (start) end
666 * of memslot of memslot
668 * [1] bmap_npages can be aligned to either 64 pages or the end of slot
671 assert(bmap_start % BITS_PER_LONG == 0);
672 /* We should never do log_clear before log_sync */
673 assert(mem->dirty_bmap);
675 /* Slow path - we need to manipulate a temp bitmap */
676 bmap_clear = bitmap_new(bmap_npages);
677 bitmap_copy_with_src_offset(bmap_clear, mem->dirty_bmap,
678 bmap_start, start_delta + size / psize);
680 * We need to fill the holes at start because that was not
681 * specified by the caller and we extended the bitmap only for
684 bitmap_clear(bmap_clear, 0, start_delta);
685 d.dirty_bitmap = bmap_clear;
687 /* Fast path - start address aligns well with BITS_PER_LONG */
688 d.dirty_bitmap = mem->dirty_bmap + BIT_WORD(bmap_start);
691 d.first_page = bmap_start;
692 /* It should never overflow. If it happens, say something */
693 assert(bmap_npages <= UINT32_MAX);
694 d.num_pages = bmap_npages;
695 d.slot = mem->slot | (kml->as_id << 16);
697 if (kvm_vm_ioctl(s, KVM_CLEAR_DIRTY_LOG, &d) == -1) {
699 error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
700 "start=0x%"PRIx64", size=0x%"PRIx32", errno=%d",
701 __func__, d.slot, (uint64_t)d.first_page,
702 (uint32_t)d.num_pages, ret);
705 trace_kvm_clear_dirty_log(d.slot, d.first_page, d.num_pages);
709 * After we have updated the remote dirty bitmap, we update the
710 * cached bitmap as well for the memslot, then if another user
711 * clears the same region we know we shouldn't clear it again on
712 * the remote otherwise it's data loss as well.
714 bitmap_clear(mem->dirty_bmap, bmap_start + start_delta,
716 /* This handles the NULL case well */
719 kvm_slots_unlock(kml);
724 static void kvm_coalesce_mmio_region(MemoryListener *listener,
725 MemoryRegionSection *secion,
726 hwaddr start, hwaddr size)
728 KVMState *s = kvm_state;
730 if (s->coalesced_mmio) {
731 struct kvm_coalesced_mmio_zone zone;
737 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
741 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
742 MemoryRegionSection *secion,
743 hwaddr start, hwaddr size)
745 KVMState *s = kvm_state;
747 if (s->coalesced_mmio) {
748 struct kvm_coalesced_mmio_zone zone;
754 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
758 static void kvm_coalesce_pio_add(MemoryListener *listener,
759 MemoryRegionSection *section,
760 hwaddr start, hwaddr size)
762 KVMState *s = kvm_state;
764 if (s->coalesced_pio) {
765 struct kvm_coalesced_mmio_zone zone;
771 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
775 static void kvm_coalesce_pio_del(MemoryListener *listener,
776 MemoryRegionSection *section,
777 hwaddr start, hwaddr size)
779 KVMState *s = kvm_state;
781 if (s->coalesced_pio) {
782 struct kvm_coalesced_mmio_zone zone;
788 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
792 static MemoryListener kvm_coalesced_pio_listener = {
793 .coalesced_io_add = kvm_coalesce_pio_add,
794 .coalesced_io_del = kvm_coalesce_pio_del,
797 int kvm_check_extension(KVMState *s, unsigned int extension)
801 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
809 int kvm_vm_check_extension(KVMState *s, unsigned int extension)
813 ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
815 /* VM wide version not implemented, use global one instead */
816 ret = kvm_check_extension(s, extension);
822 static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
824 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
825 /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
826 * endianness, but the memory core hands them in target endianness.
827 * For example, PPC is always treated as big-endian even if running
828 * on KVM and on PPC64LE. Correct here.
842 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
843 bool assign, uint32_t size, bool datamatch)
846 struct kvm_ioeventfd iofd = {
847 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
854 trace_kvm_set_ioeventfd_mmio(fd, (uint64_t)addr, val, assign, size,
856 if (!kvm_enabled()) {
861 iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
864 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
867 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
876 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
877 bool assign, uint32_t size, bool datamatch)
879 struct kvm_ioeventfd kick = {
880 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
882 .flags = KVM_IOEVENTFD_FLAG_PIO,
887 trace_kvm_set_ioeventfd_pio(fd, addr, val, assign, size, datamatch);
888 if (!kvm_enabled()) {
892 kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
895 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
897 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
905 static int kvm_check_many_ioeventfds(void)
907 /* Userspace can use ioeventfd for io notification. This requires a host
908 * that supports eventfd(2) and an I/O thread; since eventfd does not
909 * support SIGIO it cannot interrupt the vcpu.
911 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
912 * can avoid creating too many ioeventfds.
914 #if defined(CONFIG_EVENTFD)
917 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
918 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
919 if (ioeventfds[i] < 0) {
922 ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
924 close(ioeventfds[i]);
929 /* Decide whether many devices are supported or not */
930 ret = i == ARRAY_SIZE(ioeventfds);
933 kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
934 close(ioeventfds[i]);
942 static const KVMCapabilityInfo *
943 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
946 if (!kvm_check_extension(s, list->value)) {
954 static void kvm_set_phys_mem(KVMMemoryListener *kml,
955 MemoryRegionSection *section, bool add)
959 MemoryRegion *mr = section->mr;
960 bool writeable = !mr->readonly && !mr->rom_device;
961 hwaddr start_addr, size;
964 if (!memory_region_is_ram(mr)) {
965 if (writeable || !kvm_readonly_mem_allowed) {
967 } else if (!mr->romd_mode) {
968 /* If the memory device is not in romd_mode, then we actually want
969 * to remove the kvm memory slot so all accesses will trap. */
974 size = kvm_align_section(section, &start_addr);
979 /* use aligned delta to align the ram address */
980 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region +
981 (start_addr - section->offset_within_address_space);
986 mem = kvm_lookup_matching_slot(kml, start_addr, size);
990 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
991 kvm_physical_sync_dirty_bitmap(kml, section);
994 /* unregister the slot */
995 g_free(mem->dirty_bmap);
996 mem->dirty_bmap = NULL;
997 mem->memory_size = 0;
999 err = kvm_set_user_memory_region(kml, mem, false);
1001 fprintf(stderr, "%s: error unregistering slot: %s\n",
1002 __func__, strerror(-err));
1008 /* register the new slot */
1009 mem = kvm_alloc_slot(kml);
1010 mem->memory_size = size;
1011 mem->start_addr = start_addr;
1013 mem->flags = kvm_mem_flags(mr);
1015 err = kvm_set_user_memory_region(kml, mem, true);
1017 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
1023 kvm_slots_unlock(kml);
1026 static void kvm_region_add(MemoryListener *listener,
1027 MemoryRegionSection *section)
1029 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1031 memory_region_ref(section->mr);
1032 kvm_set_phys_mem(kml, section, true);
1035 static void kvm_region_del(MemoryListener *listener,
1036 MemoryRegionSection *section)
1038 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1040 kvm_set_phys_mem(kml, section, false);
1041 memory_region_unref(section->mr);
1044 static void kvm_log_sync(MemoryListener *listener,
1045 MemoryRegionSection *section)
1047 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1050 kvm_slots_lock(kml);
1051 r = kvm_physical_sync_dirty_bitmap(kml, section);
1052 kvm_slots_unlock(kml);
1058 static void kvm_log_clear(MemoryListener *listener,
1059 MemoryRegionSection *section)
1061 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1064 r = kvm_physical_log_clear(kml, section);
1066 error_report_once("%s: kvm log clear failed: mr=%s "
1067 "offset=%"HWADDR_PRIx" size=%"PRIx64, __func__,
1068 section->mr->name, section->offset_within_region,
1069 int128_get64(section->size));
1074 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
1075 MemoryRegionSection *section,
1076 bool match_data, uint64_t data,
1079 int fd = event_notifier_get_fd(e);
1082 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
1083 data, true, int128_get64(section->size),
1086 fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1087 __func__, strerror(-r), -r);
1092 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
1093 MemoryRegionSection *section,
1094 bool match_data, uint64_t data,
1097 int fd = event_notifier_get_fd(e);
1100 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
1101 data, false, int128_get64(section->size),
1104 fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1105 __func__, strerror(-r), -r);
1110 static void kvm_io_ioeventfd_add(MemoryListener *listener,
1111 MemoryRegionSection *section,
1112 bool match_data, uint64_t data,
1115 int fd = event_notifier_get_fd(e);
1118 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
1119 data, true, int128_get64(section->size),
1122 fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1123 __func__, strerror(-r), -r);
1128 static void kvm_io_ioeventfd_del(MemoryListener *listener,
1129 MemoryRegionSection *section,
1130 bool match_data, uint64_t data,
1134 int fd = event_notifier_get_fd(e);
1137 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
1138 data, false, int128_get64(section->size),
1141 fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1142 __func__, strerror(-r), -r);
1147 void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
1148 AddressSpace *as, int as_id)
1152 qemu_mutex_init(&kml->slots_lock);
1153 kml->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
1156 for (i = 0; i < s->nr_slots; i++) {
1157 kml->slots[i].slot = i;
1160 kml->listener.region_add = kvm_region_add;
1161 kml->listener.region_del = kvm_region_del;
1162 kml->listener.log_start = kvm_log_start;
1163 kml->listener.log_stop = kvm_log_stop;
1164 kml->listener.log_sync = kvm_log_sync;
1165 kml->listener.log_clear = kvm_log_clear;
1166 kml->listener.priority = 10;
1168 memory_listener_register(&kml->listener, as);
1170 for (i = 0; i < s->nr_as; ++i) {
1179 static MemoryListener kvm_io_listener = {
1180 .eventfd_add = kvm_io_ioeventfd_add,
1181 .eventfd_del = kvm_io_ioeventfd_del,
1185 int kvm_set_irq(KVMState *s, int irq, int level)
1187 struct kvm_irq_level event;
1190 assert(kvm_async_interrupts_enabled());
1192 event.level = level;
1194 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
1196 perror("kvm_set_irq");
1200 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
1203 #ifdef KVM_CAP_IRQ_ROUTING
1204 typedef struct KVMMSIRoute {
1205 struct kvm_irq_routing_entry kroute;
1206 QTAILQ_ENTRY(KVMMSIRoute) entry;
1209 static void set_gsi(KVMState *s, unsigned int gsi)
1211 set_bit(gsi, s->used_gsi_bitmap);
1214 static void clear_gsi(KVMState *s, unsigned int gsi)
1216 clear_bit(gsi, s->used_gsi_bitmap);
1219 void kvm_init_irq_routing(KVMState *s)
1223 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
1224 if (gsi_count > 0) {
1225 /* Round up so we can search ints using ffs */
1226 s->used_gsi_bitmap = bitmap_new(gsi_count);
1227 s->gsi_count = gsi_count;
1230 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
1231 s->nr_allocated_irq_routes = 0;
1233 if (!kvm_direct_msi_allowed) {
1234 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
1235 QTAILQ_INIT(&s->msi_hashtab[i]);
1239 kvm_arch_init_irq_routing(s);
1242 void kvm_irqchip_commit_routes(KVMState *s)
1246 if (kvm_gsi_direct_mapping()) {
1250 if (!kvm_gsi_routing_enabled()) {
1254 s->irq_routes->flags = 0;
1255 trace_kvm_irqchip_commit_routes();
1256 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1260 static void kvm_add_routing_entry(KVMState *s,
1261 struct kvm_irq_routing_entry *entry)
1263 struct kvm_irq_routing_entry *new;
1266 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1267 n = s->nr_allocated_irq_routes * 2;
1271 size = sizeof(struct kvm_irq_routing);
1272 size += n * sizeof(*new);
1273 s->irq_routes = g_realloc(s->irq_routes, size);
1274 s->nr_allocated_irq_routes = n;
1276 n = s->irq_routes->nr++;
1277 new = &s->irq_routes->entries[n];
1281 set_gsi(s, entry->gsi);
1284 static int kvm_update_routing_entry(KVMState *s,
1285 struct kvm_irq_routing_entry *new_entry)
1287 struct kvm_irq_routing_entry *entry;
1290 for (n = 0; n < s->irq_routes->nr; n++) {
1291 entry = &s->irq_routes->entries[n];
1292 if (entry->gsi != new_entry->gsi) {
1296 if(!memcmp(entry, new_entry, sizeof *entry)) {
1300 *entry = *new_entry;
1308 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1310 struct kvm_irq_routing_entry e = {};
1312 assert(pin < s->gsi_count);
1315 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1317 e.u.irqchip.irqchip = irqchip;
1318 e.u.irqchip.pin = pin;
1319 kvm_add_routing_entry(s, &e);
1322 void kvm_irqchip_release_virq(KVMState *s, int virq)
1324 struct kvm_irq_routing_entry *e;
1327 if (kvm_gsi_direct_mapping()) {
1331 for (i = 0; i < s->irq_routes->nr; i++) {
1332 e = &s->irq_routes->entries[i];
1333 if (e->gsi == virq) {
1334 s->irq_routes->nr--;
1335 *e = s->irq_routes->entries[s->irq_routes->nr];
1339 kvm_arch_release_virq_post(virq);
1340 trace_kvm_irqchip_release_virq(virq);
1343 static unsigned int kvm_hash_msi(uint32_t data)
1345 /* This is optimized for IA32 MSI layout. However, no other arch shall
1346 * repeat the mistake of not providing a direct MSI injection API. */
1350 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1352 KVMMSIRoute *route, *next;
1355 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1356 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1357 kvm_irqchip_release_virq(s, route->kroute.gsi);
1358 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1364 static int kvm_irqchip_get_virq(KVMState *s)
1369 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1370 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1371 * number can succeed even though a new route entry cannot be added.
1372 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1374 if (!kvm_direct_msi_allowed && s->irq_routes->nr == s->gsi_count) {
1375 kvm_flush_dynamic_msi_routes(s);
1378 /* Return the lowest unused GSI in the bitmap */
1379 next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
1380 if (next_virq >= s->gsi_count) {
1387 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1389 unsigned int hash = kvm_hash_msi(msg.data);
1392 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1393 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1394 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1395 route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1402 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1407 if (kvm_direct_msi_allowed) {
1408 msi.address_lo = (uint32_t)msg.address;
1409 msi.address_hi = msg.address >> 32;
1410 msi.data = le32_to_cpu(msg.data);
1412 memset(msi.pad, 0, sizeof(msi.pad));
1414 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1417 route = kvm_lookup_msi_route(s, msg);
1421 virq = kvm_irqchip_get_virq(s);
1426 route = g_malloc0(sizeof(KVMMSIRoute));
1427 route->kroute.gsi = virq;
1428 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1429 route->kroute.flags = 0;
1430 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1431 route->kroute.u.msi.address_hi = msg.address >> 32;
1432 route->kroute.u.msi.data = le32_to_cpu(msg.data);
1434 kvm_add_routing_entry(s, &route->kroute);
1435 kvm_irqchip_commit_routes(s);
1437 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1441 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1443 return kvm_set_irq(s, route->kroute.gsi, 1);
1446 int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
1448 struct kvm_irq_routing_entry kroute = {};
1450 MSIMessage msg = {0, 0};
1452 if (pci_available && dev) {
1453 msg = pci_get_msi_message(dev, vector);
1456 if (kvm_gsi_direct_mapping()) {
1457 return kvm_arch_msi_data_to_gsi(msg.data);
1460 if (!kvm_gsi_routing_enabled()) {
1464 virq = kvm_irqchip_get_virq(s);
1470 kroute.type = KVM_IRQ_ROUTING_MSI;
1472 kroute.u.msi.address_lo = (uint32_t)msg.address;
1473 kroute.u.msi.address_hi = msg.address >> 32;
1474 kroute.u.msi.data = le32_to_cpu(msg.data);
1475 if (pci_available && kvm_msi_devid_required()) {
1476 kroute.flags = KVM_MSI_VALID_DEVID;
1477 kroute.u.msi.devid = pci_requester_id(dev);
1479 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1480 kvm_irqchip_release_virq(s, virq);
1484 trace_kvm_irqchip_add_msi_route(dev ? dev->name : (char *)"N/A",
1487 kvm_add_routing_entry(s, &kroute);
1488 kvm_arch_add_msi_route_post(&kroute, vector, dev);
1489 kvm_irqchip_commit_routes(s);
1494 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
1497 struct kvm_irq_routing_entry kroute = {};
1499 if (kvm_gsi_direct_mapping()) {
1503 if (!kvm_irqchip_in_kernel()) {
1508 kroute.type = KVM_IRQ_ROUTING_MSI;
1510 kroute.u.msi.address_lo = (uint32_t)msg.address;
1511 kroute.u.msi.address_hi = msg.address >> 32;
1512 kroute.u.msi.data = le32_to_cpu(msg.data);
1513 if (pci_available && kvm_msi_devid_required()) {
1514 kroute.flags = KVM_MSI_VALID_DEVID;
1515 kroute.u.msi.devid = pci_requester_id(dev);
1517 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1521 trace_kvm_irqchip_update_msi_route(virq);
1523 return kvm_update_routing_entry(s, &kroute);
1526 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int rfd, int virq,
1529 struct kvm_irqfd irqfd = {
1532 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1536 irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1537 irqfd.resamplefd = rfd;
1540 if (!kvm_irqfds_enabled()) {
1544 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1547 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1549 struct kvm_irq_routing_entry kroute = {};
1552 if (!kvm_gsi_routing_enabled()) {
1556 virq = kvm_irqchip_get_virq(s);
1562 kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1564 kroute.u.adapter.summary_addr = adapter->summary_addr;
1565 kroute.u.adapter.ind_addr = adapter->ind_addr;
1566 kroute.u.adapter.summary_offset = adapter->summary_offset;
1567 kroute.u.adapter.ind_offset = adapter->ind_offset;
1568 kroute.u.adapter.adapter_id = adapter->adapter_id;
1570 kvm_add_routing_entry(s, &kroute);
1575 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1577 struct kvm_irq_routing_entry kroute = {};
1580 if (!kvm_gsi_routing_enabled()) {
1583 if (!kvm_check_extension(s, KVM_CAP_HYPERV_SYNIC)) {
1586 virq = kvm_irqchip_get_virq(s);
1592 kroute.type = KVM_IRQ_ROUTING_HV_SINT;
1594 kroute.u.hv_sint.vcpu = vcpu;
1595 kroute.u.hv_sint.sint = sint;
1597 kvm_add_routing_entry(s, &kroute);
1598 kvm_irqchip_commit_routes(s);
1603 #else /* !KVM_CAP_IRQ_ROUTING */
1605 void kvm_init_irq_routing(KVMState *s)
1609 void kvm_irqchip_release_virq(KVMState *s, int virq)
1613 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1618 int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
1623 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1628 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1633 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1638 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1642 #endif /* !KVM_CAP_IRQ_ROUTING */
1644 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1645 EventNotifier *rn, int virq)
1647 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n),
1648 rn ? event_notifier_get_fd(rn) : -1, virq, true);
1651 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1654 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), -1, virq,
1658 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1659 EventNotifier *rn, qemu_irq irq)
1662 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1667 return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
1670 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
1674 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1679 return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
1682 void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
1684 g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
1687 static void kvm_irqchip_create(MachineState *machine, KVMState *s)
1691 if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
1693 } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
1694 ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
1696 fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
1703 /* First probe and see if there's a arch-specific hook to create the
1704 * in-kernel irqchip for us */
1705 ret = kvm_arch_irqchip_create(machine, s);
1707 if (machine_kernel_irqchip_split(machine)) {
1708 perror("Split IRQ chip mode not supported.");
1711 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1715 fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
1719 kvm_kernel_irqchip = true;
1720 /* If we have an in-kernel IRQ chip then we must have asynchronous
1721 * interrupt delivery (though the reverse is not necessarily true)
1723 kvm_async_interrupts_allowed = true;
1724 kvm_halt_in_kernel_allowed = true;
1726 kvm_init_irq_routing(s);
1728 s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
1731 /* Find number of supported CPUs using the recommended
1732 * procedure from the kernel API documentation to cope with
1733 * older kernels that may be missing capabilities.
1735 static int kvm_recommended_vcpus(KVMState *s)
1737 int ret = kvm_vm_check_extension(s, KVM_CAP_NR_VCPUS);
1738 return (ret) ? ret : 4;
1741 static int kvm_max_vcpus(KVMState *s)
1743 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1744 return (ret) ? ret : kvm_recommended_vcpus(s);
1747 static int kvm_max_vcpu_id(KVMState *s)
1749 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
1750 return (ret) ? ret : kvm_max_vcpus(s);
1753 bool kvm_vcpu_id_is_valid(int vcpu_id)
1755 KVMState *s = KVM_STATE(current_machine->accelerator);
1756 return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
1759 static int kvm_init(MachineState *ms)
1761 MachineClass *mc = MACHINE_GET_CLASS(ms);
1762 static const char upgrade_note[] =
1763 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1764 "(see http://sourceforge.net/projects/kvm).\n";
1769 { "SMP", ms->smp.cpus },
1770 { "hotpluggable", ms->smp.max_cpus },
1773 int soft_vcpus_limit, hard_vcpus_limit;
1775 const KVMCapabilityInfo *missing_cap;
1778 const char *kvm_type;
1780 s = KVM_STATE(ms->accelerator);
1783 * On systems where the kernel can support different base page
1784 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1785 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1786 * page size for the system though.
1788 assert(TARGET_PAGE_SIZE <= getpagesize());
1792 #ifdef KVM_CAP_SET_GUEST_DEBUG
1793 QTAILQ_INIT(&s->kvm_sw_breakpoints);
1795 QLIST_INIT(&s->kvm_parked_vcpus);
1797 s->fd = qemu_open("/dev/kvm", O_RDWR);
1799 fprintf(stderr, "Could not access KVM kernel module: %m\n");
1804 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1805 if (ret < KVM_API_VERSION) {
1809 fprintf(stderr, "kvm version too old\n");
1813 if (ret > KVM_API_VERSION) {
1815 fprintf(stderr, "kvm version not supported\n");
1819 kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
1820 s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
1822 /* If unspecified, use the default value */
1827 s->nr_as = kvm_check_extension(s, KVM_CAP_MULTI_ADDRESS_SPACE);
1828 if (s->nr_as <= 1) {
1831 s->as = g_new0(struct KVMAs, s->nr_as);
1833 kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1835 type = mc->kvm_type(ms, kvm_type);
1836 } else if (kvm_type) {
1838 fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1843 ret = kvm_ioctl(s, KVM_CREATE_VM, type);
1844 } while (ret == -EINTR);
1847 fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
1851 if (ret == -EINVAL) {
1853 "Host kernel setup problem detected. Please verify:\n");
1854 fprintf(stderr, "- for kernels supporting the switch_amode or"
1855 " user_mode parameters, whether\n");
1857 " user space is running in primary address space\n");
1859 "- for kernels supporting the vm.allocate_pgste sysctl, "
1860 "whether it is enabled\n");
1868 /* check the vcpu limits */
1869 soft_vcpus_limit = kvm_recommended_vcpus(s);
1870 hard_vcpus_limit = kvm_max_vcpus(s);
1873 if (nc->num > soft_vcpus_limit) {
1874 warn_report("Number of %s cpus requested (%d) exceeds "
1875 "the recommended cpus supported by KVM (%d)",
1876 nc->name, nc->num, soft_vcpus_limit);
1878 if (nc->num > hard_vcpus_limit) {
1879 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
1880 "the maximum cpus supported by KVM (%d)\n",
1881 nc->name, nc->num, hard_vcpus_limit);
1888 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1891 kvm_check_extension_list(s, kvm_arch_required_capabilities);
1895 fprintf(stderr, "kvm does not support %s\n%s",
1896 missing_cap->name, upgrade_note);
1900 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1901 s->coalesced_pio = s->coalesced_mmio &&
1902 kvm_check_extension(s, KVM_CAP_COALESCED_PIO);
1904 s->manual_dirty_log_protect =
1905 kvm_check_extension(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
1906 if (s->manual_dirty_log_protect) {
1907 ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0, 1);
1909 warn_report("Trying to enable KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 "
1910 "but failed. Falling back to the legacy mode. ");
1911 s->manual_dirty_log_protect = false;
1915 #ifdef KVM_CAP_VCPU_EVENTS
1916 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1919 s->robust_singlestep =
1920 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1922 #ifdef KVM_CAP_DEBUGREGS
1923 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1926 s->max_nested_state_len = kvm_check_extension(s, KVM_CAP_NESTED_STATE);
1928 #ifdef KVM_CAP_IRQ_ROUTING
1929 kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1932 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1934 s->irq_set_ioctl = KVM_IRQ_LINE;
1935 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1936 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1939 kvm_readonly_mem_allowed =
1940 (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1942 kvm_eventfds_allowed =
1943 (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
1945 kvm_irqfds_allowed =
1946 (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
1948 kvm_resamplefds_allowed =
1949 (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
1951 kvm_vm_attributes_allowed =
1952 (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
1954 kvm_ioeventfd_any_length_allowed =
1955 (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
1960 * if memory encryption object is specified then initialize the memory
1961 * encryption context.
1963 if (ms->memory_encryption) {
1964 kvm_state->memcrypt_handle = sev_guest_init(ms->memory_encryption);
1965 if (!kvm_state->memcrypt_handle) {
1970 kvm_state->memcrypt_encrypt_data = sev_encrypt_data;
1973 ret = kvm_arch_init(ms, s);
1978 if (machine_kernel_irqchip_allowed(ms)) {
1979 kvm_irqchip_create(ms, s);
1982 if (kvm_eventfds_allowed) {
1983 s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
1984 s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
1986 s->memory_listener.listener.coalesced_io_add = kvm_coalesce_mmio_region;
1987 s->memory_listener.listener.coalesced_io_del = kvm_uncoalesce_mmio_region;
1989 kvm_memory_listener_register(s, &s->memory_listener,
1990 &address_space_memory, 0);
1991 memory_listener_register(&kvm_io_listener,
1993 memory_listener_register(&kvm_coalesced_pio_listener,
1996 s->many_ioeventfds = kvm_check_many_ioeventfds();
1998 s->sync_mmu = !!kvm_vm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2000 qemu_balloon_inhibit(true);
2013 g_free(s->memory_listener.slots);
2018 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
2020 s->sigmask_len = sigmask_len;
2023 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
2024 int size, uint32_t count)
2027 uint8_t *ptr = data;
2029 for (i = 0; i < count; i++) {
2030 address_space_rw(&address_space_io, port, attrs,
2032 direction == KVM_EXIT_IO_OUT);
2037 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
2039 fprintf(stderr, "KVM internal error. Suberror: %d\n",
2040 run->internal.suberror);
2042 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
2045 for (i = 0; i < run->internal.ndata; ++i) {
2046 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
2047 i, (uint64_t)run->internal.data[i]);
2050 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
2051 fprintf(stderr, "emulation failure\n");
2052 if (!kvm_arch_stop_on_emulation_error(cpu)) {
2053 cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2054 return EXCP_INTERRUPT;
2057 /* FIXME: Should trigger a qmp message to let management know
2058 * something went wrong.
2063 void kvm_flush_coalesced_mmio_buffer(void)
2065 KVMState *s = kvm_state;
2067 if (s->coalesced_flush_in_progress) {
2071 s->coalesced_flush_in_progress = true;
2073 if (s->coalesced_mmio_ring) {
2074 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
2075 while (ring->first != ring->last) {
2076 struct kvm_coalesced_mmio *ent;
2078 ent = &ring->coalesced_mmio[ring->first];
2080 if (ent->pio == 1) {
2081 address_space_rw(&address_space_io, ent->phys_addr,
2082 MEMTXATTRS_UNSPECIFIED, ent->data,
2085 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
2088 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
2092 s->coalesced_flush_in_progress = false;
2095 static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
2097 if (!cpu->vcpu_dirty) {
2098 kvm_arch_get_registers(cpu);
2099 cpu->vcpu_dirty = true;
2103 void kvm_cpu_synchronize_state(CPUState *cpu)
2105 if (!cpu->vcpu_dirty) {
2106 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
2110 static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
2112 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
2113 cpu->vcpu_dirty = false;
2116 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
2118 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
2121 static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
2123 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
2124 cpu->vcpu_dirty = false;
2127 void kvm_cpu_synchronize_post_init(CPUState *cpu)
2129 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
2132 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
2134 cpu->vcpu_dirty = true;
2137 void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
2139 run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
2142 #ifdef KVM_HAVE_MCE_INJECTION
2143 static __thread void *pending_sigbus_addr;
2144 static __thread int pending_sigbus_code;
2145 static __thread bool have_sigbus_pending;
2148 static void kvm_cpu_kick(CPUState *cpu)
2150 atomic_set(&cpu->kvm_run->immediate_exit, 1);
2153 static void kvm_cpu_kick_self(void)
2155 if (kvm_immediate_exit) {
2156 kvm_cpu_kick(current_cpu);
2158 qemu_cpu_kick_self();
2162 static void kvm_eat_signals(CPUState *cpu)
2164 struct timespec ts = { 0, 0 };
2170 if (kvm_immediate_exit) {
2171 atomic_set(&cpu->kvm_run->immediate_exit, 0);
2172 /* Write kvm_run->immediate_exit before the cpu->exit_request
2173 * write in kvm_cpu_exec.
2179 sigemptyset(&waitset);
2180 sigaddset(&waitset, SIG_IPI);
2183 r = sigtimedwait(&waitset, &siginfo, &ts);
2184 if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
2185 perror("sigtimedwait");
2189 r = sigpending(&chkset);
2191 perror("sigpending");
2194 } while (sigismember(&chkset, SIG_IPI));
2197 int kvm_cpu_exec(CPUState *cpu)
2199 struct kvm_run *run = cpu->kvm_run;
2202 DPRINTF("kvm_cpu_exec()\n");
2204 if (kvm_arch_process_async_events(cpu)) {
2205 atomic_set(&cpu->exit_request, 0);
2209 qemu_mutex_unlock_iothread();
2210 cpu_exec_start(cpu);
2215 if (cpu->vcpu_dirty) {
2216 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
2217 cpu->vcpu_dirty = false;
2220 kvm_arch_pre_run(cpu, run);
2221 if (atomic_read(&cpu->exit_request)) {
2222 DPRINTF("interrupt exit requested\n");
2224 * KVM requires us to reenter the kernel after IO exits to complete
2225 * instruction emulation. This self-signal will ensure that we
2228 kvm_cpu_kick_self();
2231 /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2232 * Matching barrier in kvm_eat_signals.
2236 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
2238 attrs = kvm_arch_post_run(cpu, run);
2240 #ifdef KVM_HAVE_MCE_INJECTION
2241 if (unlikely(have_sigbus_pending)) {
2242 qemu_mutex_lock_iothread();
2243 kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
2244 pending_sigbus_addr);
2245 have_sigbus_pending = false;
2246 qemu_mutex_unlock_iothread();
2251 if (run_ret == -EINTR || run_ret == -EAGAIN) {
2252 DPRINTF("io window exit\n");
2253 kvm_eat_signals(cpu);
2254 ret = EXCP_INTERRUPT;
2257 fprintf(stderr, "error: kvm run failed %s\n",
2258 strerror(-run_ret));
2260 if (run_ret == -EBUSY) {
2262 "This is probably because your SMT is enabled.\n"
2263 "VCPU can only run on primary threads with all "
2264 "secondary threads offline.\n");
2271 trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
2272 switch (run->exit_reason) {
2274 DPRINTF("handle_io\n");
2275 /* Called outside BQL */
2276 kvm_handle_io(run->io.port, attrs,
2277 (uint8_t *)run + run->io.data_offset,
2284 DPRINTF("handle_mmio\n");
2285 /* Called outside BQL */
2286 address_space_rw(&address_space_memory,
2287 run->mmio.phys_addr, attrs,
2290 run->mmio.is_write);
2293 case KVM_EXIT_IRQ_WINDOW_OPEN:
2294 DPRINTF("irq_window_open\n");
2295 ret = EXCP_INTERRUPT;
2297 case KVM_EXIT_SHUTDOWN:
2298 DPRINTF("shutdown\n");
2299 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
2300 ret = EXCP_INTERRUPT;
2302 case KVM_EXIT_UNKNOWN:
2303 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
2304 (uint64_t)run->hw.hardware_exit_reason);
2307 case KVM_EXIT_INTERNAL_ERROR:
2308 ret = kvm_handle_internal_error(cpu, run);
2310 case KVM_EXIT_SYSTEM_EVENT:
2311 switch (run->system_event.type) {
2312 case KVM_SYSTEM_EVENT_SHUTDOWN:
2313 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
2314 ret = EXCP_INTERRUPT;
2316 case KVM_SYSTEM_EVENT_RESET:
2317 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
2318 ret = EXCP_INTERRUPT;
2320 case KVM_SYSTEM_EVENT_CRASH:
2321 kvm_cpu_synchronize_state(cpu);
2322 qemu_mutex_lock_iothread();
2323 qemu_system_guest_panicked(cpu_get_crash_info(cpu));
2324 qemu_mutex_unlock_iothread();
2328 DPRINTF("kvm_arch_handle_exit\n");
2329 ret = kvm_arch_handle_exit(cpu, run);
2334 DPRINTF("kvm_arch_handle_exit\n");
2335 ret = kvm_arch_handle_exit(cpu, run);
2341 qemu_mutex_lock_iothread();
2344 cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2345 vm_stop(RUN_STATE_INTERNAL_ERROR);
2348 atomic_set(&cpu->exit_request, 0);
2352 int kvm_ioctl(KVMState *s, int type, ...)
2359 arg = va_arg(ap, void *);
2362 trace_kvm_ioctl(type, arg);
2363 ret = ioctl(s->fd, type, arg);
2370 int kvm_vm_ioctl(KVMState *s, int type, ...)
2377 arg = va_arg(ap, void *);
2380 trace_kvm_vm_ioctl(type, arg);
2381 ret = ioctl(s->vmfd, type, arg);
2388 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
2395 arg = va_arg(ap, void *);
2398 trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
2399 ret = ioctl(cpu->kvm_fd, type, arg);
2406 int kvm_device_ioctl(int fd, int type, ...)
2413 arg = va_arg(ap, void *);
2416 trace_kvm_device_ioctl(fd, type, arg);
2417 ret = ioctl(fd, type, arg);
2424 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
2427 struct kvm_device_attr attribute = {
2432 if (!kvm_vm_attributes_allowed) {
2436 ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
2437 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2441 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
2443 struct kvm_device_attr attribute = {
2449 return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
2452 int kvm_device_access(int fd, int group, uint64_t attr,
2453 void *val, bool write, Error **errp)
2455 struct kvm_device_attr kvmattr;
2459 kvmattr.group = group;
2460 kvmattr.attr = attr;
2461 kvmattr.addr = (uintptr_t)val;
2463 err = kvm_device_ioctl(fd,
2464 write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
2467 error_setg_errno(errp, -err,
2468 "KVM_%s_DEVICE_ATTR failed: Group %d "
2469 "attr 0x%016" PRIx64,
2470 write ? "SET" : "GET", group, attr);
2475 bool kvm_has_sync_mmu(void)
2477 return kvm_state->sync_mmu;
2480 int kvm_has_vcpu_events(void)
2482 return kvm_state->vcpu_events;
2485 int kvm_has_robust_singlestep(void)
2487 return kvm_state->robust_singlestep;
2490 int kvm_has_debugregs(void)
2492 return kvm_state->debugregs;
2495 int kvm_max_nested_state_length(void)
2497 return kvm_state->max_nested_state_len;
2500 int kvm_has_many_ioeventfds(void)
2502 if (!kvm_enabled()) {
2505 return kvm_state->many_ioeventfds;
2508 int kvm_has_gsi_routing(void)
2510 #ifdef KVM_CAP_IRQ_ROUTING
2511 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
2517 int kvm_has_intx_set_mask(void)
2519 return kvm_state->intx_set_mask;
2522 bool kvm_arm_supports_user_irq(void)
2524 return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
2527 #ifdef KVM_CAP_SET_GUEST_DEBUG
2528 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
2531 struct kvm_sw_breakpoint *bp;
2533 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
2541 int kvm_sw_breakpoints_active(CPUState *cpu)
2543 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
2546 struct kvm_set_guest_debug_data {
2547 struct kvm_guest_debug dbg;
2551 static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
2553 struct kvm_set_guest_debug_data *dbg_data =
2554 (struct kvm_set_guest_debug_data *) data.host_ptr;
2556 dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
2560 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2562 struct kvm_set_guest_debug_data data;
2564 data.dbg.control = reinject_trap;
2566 if (cpu->singlestep_enabled) {
2567 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2569 kvm_arch_update_guest_debug(cpu, &data.dbg);
2571 run_on_cpu(cpu, kvm_invoke_set_guest_debug,
2572 RUN_ON_CPU_HOST_PTR(&data));
2576 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2577 target_ulong len, int type)
2579 struct kvm_sw_breakpoint *bp;
2582 if (type == GDB_BREAKPOINT_SW) {
2583 bp = kvm_find_sw_breakpoint(cpu, addr);
2589 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2592 err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2598 QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2600 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2607 err = kvm_update_guest_debug(cpu, 0);
2615 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2616 target_ulong len, int type)
2618 struct kvm_sw_breakpoint *bp;
2621 if (type == GDB_BREAKPOINT_SW) {
2622 bp = kvm_find_sw_breakpoint(cpu, addr);
2627 if (bp->use_count > 1) {
2632 err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2637 QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2640 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2647 err = kvm_update_guest_debug(cpu, 0);
2655 void kvm_remove_all_breakpoints(CPUState *cpu)
2657 struct kvm_sw_breakpoint *bp, *next;
2658 KVMState *s = cpu->kvm_state;
2661 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2662 if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2663 /* Try harder to find a CPU that currently sees the breakpoint. */
2664 CPU_FOREACH(tmpcpu) {
2665 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2670 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2673 kvm_arch_remove_all_hw_breakpoints();
2676 kvm_update_guest_debug(cpu, 0);
2680 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2682 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2687 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2688 target_ulong len, int type)
2693 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2694 target_ulong len, int type)
2699 void kvm_remove_all_breakpoints(CPUState *cpu)
2702 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2704 static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2706 KVMState *s = kvm_state;
2707 struct kvm_signal_mask *sigmask;
2710 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2712 sigmask->len = s->sigmask_len;
2713 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2714 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2720 static void kvm_ipi_signal(int sig)
2723 assert(kvm_immediate_exit);
2724 kvm_cpu_kick(current_cpu);
2728 void kvm_init_cpu_signals(CPUState *cpu)
2732 struct sigaction sigact;
2734 memset(&sigact, 0, sizeof(sigact));
2735 sigact.sa_handler = kvm_ipi_signal;
2736 sigaction(SIG_IPI, &sigact, NULL);
2738 pthread_sigmask(SIG_BLOCK, NULL, &set);
2739 #if defined KVM_HAVE_MCE_INJECTION
2740 sigdelset(&set, SIGBUS);
2741 pthread_sigmask(SIG_SETMASK, &set, NULL);
2743 sigdelset(&set, SIG_IPI);
2744 if (kvm_immediate_exit) {
2745 r = pthread_sigmask(SIG_SETMASK, &set, NULL);
2747 r = kvm_set_signal_mask(cpu, &set);
2750 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
2755 /* Called asynchronously in VCPU thread. */
2756 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2758 #ifdef KVM_HAVE_MCE_INJECTION
2759 if (have_sigbus_pending) {
2762 have_sigbus_pending = true;
2763 pending_sigbus_addr = addr;
2764 pending_sigbus_code = code;
2765 atomic_set(&cpu->exit_request, 1);
2772 /* Called synchronously (via signalfd) in main thread. */
2773 int kvm_on_sigbus(int code, void *addr)
2775 #ifdef KVM_HAVE_MCE_INJECTION
2776 /* Action required MCE kills the process if SIGBUS is blocked. Because
2777 * that's what happens in the I/O thread, where we handle MCE via signalfd,
2778 * we can only get action optional here.
2780 assert(code != BUS_MCEERR_AR);
2781 kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
2788 int kvm_create_device(KVMState *s, uint64_t type, bool test)
2791 struct kvm_create_device create_dev;
2793 create_dev.type = type;
2795 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2797 if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2801 ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2806 return test ? 0 : create_dev.fd;
2809 bool kvm_device_supported(int vmfd, uint64_t type)
2811 struct kvm_create_device create_dev = {
2814 .flags = KVM_CREATE_DEVICE_TEST,
2817 if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
2821 return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
2824 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2826 struct kvm_one_reg reg;
2830 reg.addr = (uintptr_t) source;
2831 r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, ®);
2833 trace_kvm_failed_reg_set(id, strerror(-r));
2838 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2840 struct kvm_one_reg reg;
2844 reg.addr = (uintptr_t) target;
2845 r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, ®);
2847 trace_kvm_failed_reg_get(id, strerror(-r));
2852 static bool kvm_accel_has_memory(MachineState *ms, AddressSpace *as,
2853 hwaddr start_addr, hwaddr size)
2855 KVMState *kvm = KVM_STATE(ms->accelerator);
2858 for (i = 0; i < kvm->nr_as; ++i) {
2859 if (kvm->as[i].as == as && kvm->as[i].ml) {
2860 return NULL != kvm_lookup_matching_slot(kvm->as[i].ml,
2868 static void kvm_accel_class_init(ObjectClass *oc, void *data)
2870 AccelClass *ac = ACCEL_CLASS(oc);
2872 ac->init_machine = kvm_init;
2873 ac->has_memory = kvm_accel_has_memory;
2874 ac->allowed = &kvm_allowed;
2877 static const TypeInfo kvm_accel_type = {
2878 .name = TYPE_KVM_ACCEL,
2879 .parent = TYPE_ACCEL,
2880 .class_init = kvm_accel_class_init,
2881 .instance_size = sizeof(KVMState),
2884 static void kvm_type_init(void)
2886 type_register_static(&kvm_accel_type);
2889 type_init(kvm_type_init);