4 * Copyright IBM, Corp. 2008
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 "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/runstate.h"
32 #include "sysemu/cpus.h"
33 #include "sysemu/sysemu.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 "qemu/main-loop.h"
42 #include "sysemu/sev.h"
43 #include "sysemu/balloon.h"
45 #include "hw/boards.h"
47 /* This check must be after config-host.h is included */
49 #include <sys/eventfd.h>
52 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
53 * need to use the real host PAGE_SIZE, as that's what KVM will use.
55 #define PAGE_SIZE getpagesize()
60 #define DPRINTF(fmt, ...) \
61 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
63 #define DPRINTF(fmt, ...) \
67 #define KVM_MSI_HASHTAB_SIZE 256
69 struct KVMParkedVcpu
{
70 unsigned long vcpu_id
;
72 QLIST_ENTRY(KVMParkedVcpu
) node
;
77 AccelState parent_obj
;
84 struct kvm_coalesced_mmio_ring
*coalesced_mmio_ring
;
85 bool coalesced_flush_in_progress
;
87 int robust_singlestep
;
89 #ifdef KVM_CAP_SET_GUEST_DEBUG
90 QTAILQ_HEAD(, kvm_sw_breakpoint
) kvm_sw_breakpoints
;
92 int max_nested_state_len
;
96 bool manual_dirty_log_protect
;
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
;
103 #ifdef KVM_CAP_IRQ_ROUTING
104 struct kvm_irq_routing
*irq_routes
;
105 int nr_allocated_irq_routes
;
106 unsigned long *used_gsi_bitmap
;
107 unsigned int gsi_count
;
108 QTAILQ_HEAD(, KVMMSIRoute
) msi_hashtab
[KVM_MSI_HASHTAB_SIZE
];
110 KVMMemoryListener memory_listener
;
111 QLIST_HEAD(, KVMParkedVcpu
) kvm_parked_vcpus
;
113 /* memory encryption */
114 void *memcrypt_handle
;
115 int (*memcrypt_encrypt_data
)(void *handle
, uint8_t *ptr
, uint64_t len
);
117 /* For "info mtree -f" to tell if an MR is registered in KVM */
120 KVMMemoryListener
*ml
;
126 bool kvm_kernel_irqchip
;
127 bool kvm_split_irqchip
;
128 bool kvm_async_interrupts_allowed
;
129 bool kvm_halt_in_kernel_allowed
;
130 bool kvm_eventfds_allowed
;
131 bool kvm_irqfds_allowed
;
132 bool kvm_resamplefds_allowed
;
133 bool kvm_msi_via_irqfd_allowed
;
134 bool kvm_gsi_routing_allowed
;
135 bool kvm_gsi_direct_mapping
;
137 bool kvm_readonly_mem_allowed
;
138 bool kvm_vm_attributes_allowed
;
139 bool kvm_direct_msi_allowed
;
140 bool kvm_ioeventfd_any_length_allowed
;
141 bool kvm_msi_use_devid
;
142 static bool kvm_immediate_exit
;
144 static const KVMCapabilityInfo kvm_required_capabilites
[] = {
145 KVM_CAP_INFO(USER_MEMORY
),
146 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS
),
147 KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS
),
151 #define kvm_slots_lock(kml) qemu_mutex_lock(&(kml)->slots_lock)
152 #define kvm_slots_unlock(kml) qemu_mutex_unlock(&(kml)->slots_lock)
154 int kvm_get_max_memslots(void)
156 KVMState
*s
= KVM_STATE(current_machine
->accelerator
);
161 bool kvm_memcrypt_enabled(void)
163 if (kvm_state
&& kvm_state
->memcrypt_handle
) {
170 int kvm_memcrypt_encrypt_data(uint8_t *ptr
, uint64_t len
)
172 if (kvm_state
->memcrypt_handle
&&
173 kvm_state
->memcrypt_encrypt_data
) {
174 return kvm_state
->memcrypt_encrypt_data(kvm_state
->memcrypt_handle
,
181 /* Called with KVMMemoryListener.slots_lock held */
182 static KVMSlot
*kvm_get_free_slot(KVMMemoryListener
*kml
)
184 KVMState
*s
= kvm_state
;
187 for (i
= 0; i
< s
->nr_slots
; i
++) {
188 if (kml
->slots
[i
].memory_size
== 0) {
189 return &kml
->slots
[i
];
196 bool kvm_has_free_slot(MachineState
*ms
)
198 KVMState
*s
= KVM_STATE(ms
->accelerator
);
200 KVMMemoryListener
*kml
= &s
->memory_listener
;
203 result
= !!kvm_get_free_slot(kml
);
204 kvm_slots_unlock(kml
);
209 /* Called with KVMMemoryListener.slots_lock held */
210 static KVMSlot
*kvm_alloc_slot(KVMMemoryListener
*kml
)
212 KVMSlot
*slot
= kvm_get_free_slot(kml
);
218 fprintf(stderr
, "%s: no free slot available\n", __func__
);
222 static KVMSlot
*kvm_lookup_matching_slot(KVMMemoryListener
*kml
,
226 KVMState
*s
= kvm_state
;
229 for (i
= 0; i
< s
->nr_slots
; i
++) {
230 KVMSlot
*mem
= &kml
->slots
[i
];
232 if (start_addr
== mem
->start_addr
&& size
== mem
->memory_size
) {
241 * Calculate and align the start address and the size of the section.
242 * Return the size. If the size is 0, the aligned section is empty.
244 static hwaddr
kvm_align_section(MemoryRegionSection
*section
,
247 hwaddr size
= int128_get64(section
->size
);
248 hwaddr delta
, aligned
;
250 /* kvm works in page size chunks, but the function may be called
251 with sub-page size and unaligned start address. Pad the start
252 address to next and truncate size to previous page boundary. */
253 aligned
= ROUND_UP(section
->offset_within_address_space
,
254 qemu_real_host_page_size
);
255 delta
= aligned
- section
->offset_within_address_space
;
261 return (size
- delta
) & qemu_real_host_page_mask
;
264 int kvm_physical_memory_addr_from_host(KVMState
*s
, void *ram
,
267 KVMMemoryListener
*kml
= &s
->memory_listener
;
271 for (i
= 0; i
< s
->nr_slots
; i
++) {
272 KVMSlot
*mem
= &kml
->slots
[i
];
274 if (ram
>= mem
->ram
&& ram
< mem
->ram
+ mem
->memory_size
) {
275 *phys_addr
= mem
->start_addr
+ (ram
- mem
->ram
);
280 kvm_slots_unlock(kml
);
285 static int kvm_set_user_memory_region(KVMMemoryListener
*kml
, KVMSlot
*slot
, bool new)
287 KVMState
*s
= kvm_state
;
288 struct kvm_userspace_memory_region mem
;
291 mem
.slot
= slot
->slot
| (kml
->as_id
<< 16);
292 mem
.guest_phys_addr
= slot
->start_addr
;
293 mem
.userspace_addr
= (unsigned long)slot
->ram
;
294 mem
.flags
= slot
->flags
;
296 if (slot
->memory_size
&& !new && (mem
.flags
^ slot
->old_flags
) & KVM_MEM_READONLY
) {
297 /* Set the slot size to 0 before setting the slot to the desired
298 * value. This is needed based on KVM commit 75d61fbc. */
300 kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
302 mem
.memory_size
= slot
->memory_size
;
303 ret
= kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
304 slot
->old_flags
= mem
.flags
;
305 trace_kvm_set_user_memory(mem
.slot
, mem
.flags
, mem
.guest_phys_addr
,
306 mem
.memory_size
, mem
.userspace_addr
, ret
);
310 int kvm_destroy_vcpu(CPUState
*cpu
)
312 KVMState
*s
= kvm_state
;
314 struct KVMParkedVcpu
*vcpu
= NULL
;
317 DPRINTF("kvm_destroy_vcpu\n");
319 ret
= kvm_arch_destroy_vcpu(cpu
);
324 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
327 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
331 ret
= munmap(cpu
->kvm_run
, mmap_size
);
336 vcpu
= g_malloc0(sizeof(*vcpu
));
337 vcpu
->vcpu_id
= kvm_arch_vcpu_id(cpu
);
338 vcpu
->kvm_fd
= cpu
->kvm_fd
;
339 QLIST_INSERT_HEAD(&kvm_state
->kvm_parked_vcpus
, vcpu
, node
);
344 static int kvm_get_vcpu(KVMState
*s
, unsigned long vcpu_id
)
346 struct KVMParkedVcpu
*cpu
;
348 QLIST_FOREACH(cpu
, &s
->kvm_parked_vcpus
, node
) {
349 if (cpu
->vcpu_id
== vcpu_id
) {
352 QLIST_REMOVE(cpu
, node
);
353 kvm_fd
= cpu
->kvm_fd
;
359 return kvm_vm_ioctl(s
, KVM_CREATE_VCPU
, (void *)vcpu_id
);
362 int kvm_init_vcpu(CPUState
*cpu
)
364 KVMState
*s
= kvm_state
;
368 DPRINTF("kvm_init_vcpu\n");
370 ret
= kvm_get_vcpu(s
, kvm_arch_vcpu_id(cpu
));
372 DPRINTF("kvm_create_vcpu failed\n");
378 cpu
->vcpu_dirty
= true;
380 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
383 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
387 cpu
->kvm_run
= mmap(NULL
, mmap_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
389 if (cpu
->kvm_run
== MAP_FAILED
) {
391 DPRINTF("mmap'ing vcpu state failed\n");
395 if (s
->coalesced_mmio
&& !s
->coalesced_mmio_ring
) {
396 s
->coalesced_mmio_ring
=
397 (void *)cpu
->kvm_run
+ s
->coalesced_mmio
* PAGE_SIZE
;
400 ret
= kvm_arch_init_vcpu(cpu
);
406 * dirty pages logging control
409 static int kvm_mem_flags(MemoryRegion
*mr
)
411 bool readonly
= mr
->readonly
|| memory_region_is_romd(mr
);
414 if (memory_region_get_dirty_log_mask(mr
) != 0) {
415 flags
|= KVM_MEM_LOG_DIRTY_PAGES
;
417 if (readonly
&& kvm_readonly_mem_allowed
) {
418 flags
|= KVM_MEM_READONLY
;
423 /* Called with KVMMemoryListener.slots_lock held */
424 static int kvm_slot_update_flags(KVMMemoryListener
*kml
, KVMSlot
*mem
,
427 mem
->flags
= kvm_mem_flags(mr
);
429 /* If nothing changed effectively, no need to issue ioctl */
430 if (mem
->flags
== mem
->old_flags
) {
434 return kvm_set_user_memory_region(kml
, mem
, false);
437 static int kvm_section_update_flags(KVMMemoryListener
*kml
,
438 MemoryRegionSection
*section
)
440 hwaddr start_addr
, size
;
444 size
= kvm_align_section(section
, &start_addr
);
451 mem
= kvm_lookup_matching_slot(kml
, start_addr
, size
);
453 /* We don't have a slot if we want to trap every access. */
457 ret
= kvm_slot_update_flags(kml
, mem
, section
->mr
);
460 kvm_slots_unlock(kml
);
464 static void kvm_log_start(MemoryListener
*listener
,
465 MemoryRegionSection
*section
,
468 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
475 r
= kvm_section_update_flags(kml
, section
);
481 static void kvm_log_stop(MemoryListener
*listener
,
482 MemoryRegionSection
*section
,
485 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
492 r
= kvm_section_update_flags(kml
, section
);
498 /* get kvm's dirty pages bitmap and update qemu's */
499 static int kvm_get_dirty_pages_log_range(MemoryRegionSection
*section
,
500 unsigned long *bitmap
)
502 ram_addr_t start
= section
->offset_within_region
+
503 memory_region_get_ram_addr(section
->mr
);
504 ram_addr_t pages
= int128_get64(section
->size
) / getpagesize();
506 cpu_physical_memory_set_dirty_lebitmap(bitmap
, start
, pages
);
510 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
513 * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
515 * This function will first try to fetch dirty bitmap from the kernel,
516 * and then updates qemu's dirty bitmap.
518 * NOTE: caller must be with kml->slots_lock held.
520 * @kml: the KVM memory listener object
521 * @section: the memory section to sync the dirty bitmap with
523 static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener
*kml
,
524 MemoryRegionSection
*section
)
526 KVMState
*s
= kvm_state
;
527 struct kvm_dirty_log d
= {};
529 hwaddr start_addr
, size
;
532 size
= kvm_align_section(section
, &start_addr
);
534 mem
= kvm_lookup_matching_slot(kml
, start_addr
, size
);
536 /* We don't have a slot if we want to trap every access. */
540 /* XXX bad kernel interface alert
541 * For dirty bitmap, kernel allocates array of size aligned to
542 * bits-per-long. But for case when the kernel is 64bits and
543 * the userspace is 32bits, userspace can't align to the same
544 * bits-per-long, since sizeof(long) is different between kernel
545 * and user space. This way, userspace will provide buffer which
546 * may be 4 bytes less than the kernel will use, resulting in
547 * userspace memory corruption (which is not detectable by valgrind
548 * too, in most cases).
549 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
550 * a hope that sizeof(long) won't become >8 any time soon.
552 size
= ALIGN(((mem
->memory_size
) >> TARGET_PAGE_BITS
),
553 /*HOST_LONG_BITS*/ 64) / 8;
554 if (!mem
->dirty_bmap
) {
555 /* Allocate on the first log_sync, once and for all */
556 mem
->dirty_bmap
= g_malloc0(size
);
559 d
.dirty_bitmap
= mem
->dirty_bmap
;
560 d
.slot
= mem
->slot
| (kml
->as_id
<< 16);
561 if (kvm_vm_ioctl(s
, KVM_GET_DIRTY_LOG
, &d
) == -1) {
562 DPRINTF("ioctl failed %d\n", errno
);
567 kvm_get_dirty_pages_log_range(section
, d
.dirty_bitmap
);
573 /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
574 #define KVM_CLEAR_LOG_SHIFT 6
575 #define KVM_CLEAR_LOG_ALIGN (qemu_real_host_page_size << KVM_CLEAR_LOG_SHIFT)
576 #define KVM_CLEAR_LOG_MASK (-KVM_CLEAR_LOG_ALIGN)
578 static int kvm_log_clear_one_slot(KVMSlot
*mem
, int as_id
, uint64_t start
,
581 KVMState
*s
= kvm_state
;
582 uint64_t end
, bmap_start
, start_delta
, bmap_npages
;
583 struct kvm_clear_dirty_log d
;
584 unsigned long *bmap_clear
= NULL
, psize
= qemu_real_host_page_size
;
588 * We need to extend either the start or the size or both to
589 * satisfy the KVM interface requirement. Firstly, do the start
590 * page alignment on 64 host pages
592 bmap_start
= start
& KVM_CLEAR_LOG_MASK
;
593 start_delta
= start
- bmap_start
;
597 * The kernel interface has restriction on the size too, that either:
599 * (1) the size is 64 host pages aligned (just like the start), or
600 * (2) the size fills up until the end of the KVM memslot.
602 bmap_npages
= DIV_ROUND_UP(size
+ start_delta
, KVM_CLEAR_LOG_ALIGN
)
603 << KVM_CLEAR_LOG_SHIFT
;
604 end
= mem
->memory_size
/ psize
;
605 if (bmap_npages
> end
- bmap_start
) {
606 bmap_npages
= end
- bmap_start
;
608 start_delta
/= psize
;
611 * Prepare the bitmap to clear dirty bits. Here we must guarantee
612 * that we won't clear any unknown dirty bits otherwise we might
613 * accidentally clear some set bits which are not yet synced from
614 * the kernel into QEMU's bitmap, then we'll lose track of the
615 * guest modifications upon those pages (which can directly lead
616 * to guest data loss or panic after migration).
618 * Layout of the KVMSlot.dirty_bmap:
620 * |<-------- bmap_npages -----------..>|
623 * |----------------|-------------|------------------|------------|
626 * start bmap_start (start) end
627 * of memslot of memslot
629 * [1] bmap_npages can be aligned to either 64 pages or the end of slot
632 assert(bmap_start
% BITS_PER_LONG
== 0);
633 /* We should never do log_clear before log_sync */
634 assert(mem
->dirty_bmap
);
636 /* Slow path - we need to manipulate a temp bitmap */
637 bmap_clear
= bitmap_new(bmap_npages
);
638 bitmap_copy_with_src_offset(bmap_clear
, mem
->dirty_bmap
,
639 bmap_start
, start_delta
+ size
/ psize
);
641 * We need to fill the holes at start because that was not
642 * specified by the caller and we extended the bitmap only for
645 bitmap_clear(bmap_clear
, 0, start_delta
);
646 d
.dirty_bitmap
= bmap_clear
;
648 /* Fast path - start address aligns well with BITS_PER_LONG */
649 d
.dirty_bitmap
= mem
->dirty_bmap
+ BIT_WORD(bmap_start
);
652 d
.first_page
= bmap_start
;
653 /* It should never overflow. If it happens, say something */
654 assert(bmap_npages
<= UINT32_MAX
);
655 d
.num_pages
= bmap_npages
;
656 d
.slot
= mem
->slot
| (as_id
<< 16);
658 if (kvm_vm_ioctl(s
, KVM_CLEAR_DIRTY_LOG
, &d
) == -1) {
660 error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
661 "start=0x%"PRIx64
", size=0x%"PRIx32
", errno=%d",
662 __func__
, d
.slot
, (uint64_t)d
.first_page
,
663 (uint32_t)d
.num_pages
, ret
);
666 trace_kvm_clear_dirty_log(d
.slot
, d
.first_page
, d
.num_pages
);
670 * After we have updated the remote dirty bitmap, we update the
671 * cached bitmap as well for the memslot, then if another user
672 * clears the same region we know we shouldn't clear it again on
673 * the remote otherwise it's data loss as well.
675 bitmap_clear(mem
->dirty_bmap
, bmap_start
+ start_delta
,
677 /* This handles the NULL case well */
684 * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
686 * NOTE: this will be a no-op if we haven't enabled manual dirty log
687 * protection in the host kernel because in that case this operation
688 * will be done within log_sync().
690 * @kml: the kvm memory listener
691 * @section: the memory range to clear dirty bitmap
693 static int kvm_physical_log_clear(KVMMemoryListener
*kml
,
694 MemoryRegionSection
*section
)
696 KVMState
*s
= kvm_state
;
697 uint64_t start
, size
, offset
, count
;
701 if (!s
->manual_dirty_log_protect
) {
702 /* No need to do explicit clear */
706 start
= section
->offset_within_address_space
;
707 size
= int128_get64(section
->size
);
710 /* Nothing more we can do... */
716 for (i
= 0; i
< s
->nr_slots
; i
++) {
717 mem
= &kml
->slots
[i
];
718 /* Discard slots that are empty or do not overlap the section */
719 if (!mem
->memory_size
||
720 mem
->start_addr
> start
+ size
- 1 ||
721 start
> mem
->start_addr
+ mem
->memory_size
- 1) {
725 if (start
>= mem
->start_addr
) {
726 /* The slot starts before section or is aligned to it. */
727 offset
= start
- mem
->start_addr
;
728 count
= MIN(mem
->memory_size
- offset
, size
);
730 /* The slot starts after section. */
732 count
= MIN(mem
->memory_size
, size
- (mem
->start_addr
- start
));
734 ret
= kvm_log_clear_one_slot(mem
, kml
->as_id
, offset
, count
);
740 kvm_slots_unlock(kml
);
745 static void kvm_coalesce_mmio_region(MemoryListener
*listener
,
746 MemoryRegionSection
*secion
,
747 hwaddr start
, hwaddr size
)
749 KVMState
*s
= kvm_state
;
751 if (s
->coalesced_mmio
) {
752 struct kvm_coalesced_mmio_zone zone
;
758 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
762 static void kvm_uncoalesce_mmio_region(MemoryListener
*listener
,
763 MemoryRegionSection
*secion
,
764 hwaddr start
, hwaddr size
)
766 KVMState
*s
= kvm_state
;
768 if (s
->coalesced_mmio
) {
769 struct kvm_coalesced_mmio_zone zone
;
775 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
779 static void kvm_coalesce_pio_add(MemoryListener
*listener
,
780 MemoryRegionSection
*section
,
781 hwaddr start
, hwaddr size
)
783 KVMState
*s
= kvm_state
;
785 if (s
->coalesced_pio
) {
786 struct kvm_coalesced_mmio_zone zone
;
792 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
796 static void kvm_coalesce_pio_del(MemoryListener
*listener
,
797 MemoryRegionSection
*section
,
798 hwaddr start
, hwaddr size
)
800 KVMState
*s
= kvm_state
;
802 if (s
->coalesced_pio
) {
803 struct kvm_coalesced_mmio_zone zone
;
809 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
813 static MemoryListener kvm_coalesced_pio_listener
= {
814 .coalesced_io_add
= kvm_coalesce_pio_add
,
815 .coalesced_io_del
= kvm_coalesce_pio_del
,
818 int kvm_check_extension(KVMState
*s
, unsigned int extension
)
822 ret
= kvm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
830 int kvm_vm_check_extension(KVMState
*s
, unsigned int extension
)
834 ret
= kvm_vm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
836 /* VM wide version not implemented, use global one instead */
837 ret
= kvm_check_extension(s
, extension
);
843 static uint32_t adjust_ioeventfd_endianness(uint32_t val
, uint32_t size
)
845 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
846 /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
847 * endianness, but the memory core hands them in target endianness.
848 * For example, PPC is always treated as big-endian even if running
849 * on KVM and on PPC64LE. Correct here.
863 static int kvm_set_ioeventfd_mmio(int fd
, hwaddr addr
, uint32_t val
,
864 bool assign
, uint32_t size
, bool datamatch
)
867 struct kvm_ioeventfd iofd
= {
868 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
875 trace_kvm_set_ioeventfd_mmio(fd
, (uint64_t)addr
, val
, assign
, size
,
877 if (!kvm_enabled()) {
882 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
885 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
888 ret
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &iofd
);
897 static int kvm_set_ioeventfd_pio(int fd
, uint16_t addr
, uint16_t val
,
898 bool assign
, uint32_t size
, bool datamatch
)
900 struct kvm_ioeventfd kick
= {
901 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
903 .flags
= KVM_IOEVENTFD_FLAG_PIO
,
908 trace_kvm_set_ioeventfd_pio(fd
, addr
, val
, assign
, size
, datamatch
);
909 if (!kvm_enabled()) {
913 kick
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
916 kick
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
918 r
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &kick
);
926 static int kvm_check_many_ioeventfds(void)
928 /* Userspace can use ioeventfd for io notification. This requires a host
929 * that supports eventfd(2) and an I/O thread; since eventfd does not
930 * support SIGIO it cannot interrupt the vcpu.
932 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
933 * can avoid creating too many ioeventfds.
935 #if defined(CONFIG_EVENTFD)
938 for (i
= 0; i
< ARRAY_SIZE(ioeventfds
); i
++) {
939 ioeventfds
[i
] = eventfd(0, EFD_CLOEXEC
);
940 if (ioeventfds
[i
] < 0) {
943 ret
= kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, true, 2, true);
945 close(ioeventfds
[i
]);
950 /* Decide whether many devices are supported or not */
951 ret
= i
== ARRAY_SIZE(ioeventfds
);
954 kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, false, 2, true);
955 close(ioeventfds
[i
]);
963 static const KVMCapabilityInfo
*
964 kvm_check_extension_list(KVMState
*s
, const KVMCapabilityInfo
*list
)
967 if (!kvm_check_extension(s
, list
->value
)) {
975 static void kvm_set_phys_mem(KVMMemoryListener
*kml
,
976 MemoryRegionSection
*section
, bool add
)
980 MemoryRegion
*mr
= section
->mr
;
981 bool writeable
= !mr
->readonly
&& !mr
->rom_device
;
982 hwaddr start_addr
, size
;
985 if (!memory_region_is_ram(mr
)) {
986 if (writeable
|| !kvm_readonly_mem_allowed
) {
988 } else if (!mr
->romd_mode
) {
989 /* If the memory device is not in romd_mode, then we actually want
990 * to remove the kvm memory slot so all accesses will trap. */
995 size
= kvm_align_section(section
, &start_addr
);
1000 /* use aligned delta to align the ram address */
1001 ram
= memory_region_get_ram_ptr(mr
) + section
->offset_within_region
+
1002 (start_addr
- section
->offset_within_address_space
);
1004 kvm_slots_lock(kml
);
1007 mem
= kvm_lookup_matching_slot(kml
, start_addr
, size
);
1011 if (mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
1012 kvm_physical_sync_dirty_bitmap(kml
, section
);
1015 /* unregister the slot */
1016 g_free(mem
->dirty_bmap
);
1017 mem
->dirty_bmap
= NULL
;
1018 mem
->memory_size
= 0;
1020 err
= kvm_set_user_memory_region(kml
, mem
, false);
1022 fprintf(stderr
, "%s: error unregistering slot: %s\n",
1023 __func__
, strerror(-err
));
1029 /* register the new slot */
1030 mem
= kvm_alloc_slot(kml
);
1031 mem
->memory_size
= size
;
1032 mem
->start_addr
= start_addr
;
1034 mem
->flags
= kvm_mem_flags(mr
);
1036 err
= kvm_set_user_memory_region(kml
, mem
, true);
1038 fprintf(stderr
, "%s: error registering slot: %s\n", __func__
,
1044 kvm_slots_unlock(kml
);
1047 static void kvm_region_add(MemoryListener
*listener
,
1048 MemoryRegionSection
*section
)
1050 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1052 memory_region_ref(section
->mr
);
1053 kvm_set_phys_mem(kml
, section
, true);
1056 static void kvm_region_del(MemoryListener
*listener
,
1057 MemoryRegionSection
*section
)
1059 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1061 kvm_set_phys_mem(kml
, section
, false);
1062 memory_region_unref(section
->mr
);
1065 static void kvm_log_sync(MemoryListener
*listener
,
1066 MemoryRegionSection
*section
)
1068 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1071 kvm_slots_lock(kml
);
1072 r
= kvm_physical_sync_dirty_bitmap(kml
, section
);
1073 kvm_slots_unlock(kml
);
1079 static void kvm_log_clear(MemoryListener
*listener
,
1080 MemoryRegionSection
*section
)
1082 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1085 r
= kvm_physical_log_clear(kml
, section
);
1087 error_report_once("%s: kvm log clear failed: mr=%s "
1088 "offset=%"HWADDR_PRIx
" size=%"PRIx64
, __func__
,
1089 section
->mr
->name
, section
->offset_within_region
,
1090 int128_get64(section
->size
));
1095 static void kvm_mem_ioeventfd_add(MemoryListener
*listener
,
1096 MemoryRegionSection
*section
,
1097 bool match_data
, uint64_t data
,
1100 int fd
= event_notifier_get_fd(e
);
1103 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
1104 data
, true, int128_get64(section
->size
),
1107 fprintf(stderr
, "%s: error adding ioeventfd: %s (%d)\n",
1108 __func__
, strerror(-r
), -r
);
1113 static void kvm_mem_ioeventfd_del(MemoryListener
*listener
,
1114 MemoryRegionSection
*section
,
1115 bool match_data
, uint64_t data
,
1118 int fd
= event_notifier_get_fd(e
);
1121 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
1122 data
, false, int128_get64(section
->size
),
1125 fprintf(stderr
, "%s: error deleting ioeventfd: %s (%d)\n",
1126 __func__
, strerror(-r
), -r
);
1131 static void kvm_io_ioeventfd_add(MemoryListener
*listener
,
1132 MemoryRegionSection
*section
,
1133 bool match_data
, uint64_t data
,
1136 int fd
= event_notifier_get_fd(e
);
1139 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
1140 data
, true, int128_get64(section
->size
),
1143 fprintf(stderr
, "%s: error adding ioeventfd: %s (%d)\n",
1144 __func__
, strerror(-r
), -r
);
1149 static void kvm_io_ioeventfd_del(MemoryListener
*listener
,
1150 MemoryRegionSection
*section
,
1151 bool match_data
, uint64_t data
,
1155 int fd
= event_notifier_get_fd(e
);
1158 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
1159 data
, false, int128_get64(section
->size
),
1162 fprintf(stderr
, "%s: error deleting ioeventfd: %s (%d)\n",
1163 __func__
, strerror(-r
), -r
);
1168 void kvm_memory_listener_register(KVMState
*s
, KVMMemoryListener
*kml
,
1169 AddressSpace
*as
, int as_id
)
1173 qemu_mutex_init(&kml
->slots_lock
);
1174 kml
->slots
= g_malloc0(s
->nr_slots
* sizeof(KVMSlot
));
1177 for (i
= 0; i
< s
->nr_slots
; i
++) {
1178 kml
->slots
[i
].slot
= i
;
1181 kml
->listener
.region_add
= kvm_region_add
;
1182 kml
->listener
.region_del
= kvm_region_del
;
1183 kml
->listener
.log_start
= kvm_log_start
;
1184 kml
->listener
.log_stop
= kvm_log_stop
;
1185 kml
->listener
.log_sync
= kvm_log_sync
;
1186 kml
->listener
.log_clear
= kvm_log_clear
;
1187 kml
->listener
.priority
= 10;
1189 memory_listener_register(&kml
->listener
, as
);
1191 for (i
= 0; i
< s
->nr_as
; ++i
) {
1200 static MemoryListener kvm_io_listener
= {
1201 .eventfd_add
= kvm_io_ioeventfd_add
,
1202 .eventfd_del
= kvm_io_ioeventfd_del
,
1206 int kvm_set_irq(KVMState
*s
, int irq
, int level
)
1208 struct kvm_irq_level event
;
1211 assert(kvm_async_interrupts_enabled());
1213 event
.level
= level
;
1215 ret
= kvm_vm_ioctl(s
, s
->irq_set_ioctl
, &event
);
1217 perror("kvm_set_irq");
1221 return (s
->irq_set_ioctl
== KVM_IRQ_LINE
) ? 1 : event
.status
;
1224 #ifdef KVM_CAP_IRQ_ROUTING
1225 typedef struct KVMMSIRoute
{
1226 struct kvm_irq_routing_entry kroute
;
1227 QTAILQ_ENTRY(KVMMSIRoute
) entry
;
1230 static void set_gsi(KVMState
*s
, unsigned int gsi
)
1232 set_bit(gsi
, s
->used_gsi_bitmap
);
1235 static void clear_gsi(KVMState
*s
, unsigned int gsi
)
1237 clear_bit(gsi
, s
->used_gsi_bitmap
);
1240 void kvm_init_irq_routing(KVMState
*s
)
1244 gsi_count
= kvm_check_extension(s
, KVM_CAP_IRQ_ROUTING
) - 1;
1245 if (gsi_count
> 0) {
1246 /* Round up so we can search ints using ffs */
1247 s
->used_gsi_bitmap
= bitmap_new(gsi_count
);
1248 s
->gsi_count
= gsi_count
;
1251 s
->irq_routes
= g_malloc0(sizeof(*s
->irq_routes
));
1252 s
->nr_allocated_irq_routes
= 0;
1254 if (!kvm_direct_msi_allowed
) {
1255 for (i
= 0; i
< KVM_MSI_HASHTAB_SIZE
; i
++) {
1256 QTAILQ_INIT(&s
->msi_hashtab
[i
]);
1260 kvm_arch_init_irq_routing(s
);
1263 void kvm_irqchip_commit_routes(KVMState
*s
)
1267 if (kvm_gsi_direct_mapping()) {
1271 if (!kvm_gsi_routing_enabled()) {
1275 s
->irq_routes
->flags
= 0;
1276 trace_kvm_irqchip_commit_routes();
1277 ret
= kvm_vm_ioctl(s
, KVM_SET_GSI_ROUTING
, s
->irq_routes
);
1281 static void kvm_add_routing_entry(KVMState
*s
,
1282 struct kvm_irq_routing_entry
*entry
)
1284 struct kvm_irq_routing_entry
*new;
1287 if (s
->irq_routes
->nr
== s
->nr_allocated_irq_routes
) {
1288 n
= s
->nr_allocated_irq_routes
* 2;
1292 size
= sizeof(struct kvm_irq_routing
);
1293 size
+= n
* sizeof(*new);
1294 s
->irq_routes
= g_realloc(s
->irq_routes
, size
);
1295 s
->nr_allocated_irq_routes
= n
;
1297 n
= s
->irq_routes
->nr
++;
1298 new = &s
->irq_routes
->entries
[n
];
1302 set_gsi(s
, entry
->gsi
);
1305 static int kvm_update_routing_entry(KVMState
*s
,
1306 struct kvm_irq_routing_entry
*new_entry
)
1308 struct kvm_irq_routing_entry
*entry
;
1311 for (n
= 0; n
< s
->irq_routes
->nr
; n
++) {
1312 entry
= &s
->irq_routes
->entries
[n
];
1313 if (entry
->gsi
!= new_entry
->gsi
) {
1317 if(!memcmp(entry
, new_entry
, sizeof *entry
)) {
1321 *entry
= *new_entry
;
1329 void kvm_irqchip_add_irq_route(KVMState
*s
, int irq
, int irqchip
, int pin
)
1331 struct kvm_irq_routing_entry e
= {};
1333 assert(pin
< s
->gsi_count
);
1336 e
.type
= KVM_IRQ_ROUTING_IRQCHIP
;
1338 e
.u
.irqchip
.irqchip
= irqchip
;
1339 e
.u
.irqchip
.pin
= pin
;
1340 kvm_add_routing_entry(s
, &e
);
1343 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
1345 struct kvm_irq_routing_entry
*e
;
1348 if (kvm_gsi_direct_mapping()) {
1352 for (i
= 0; i
< s
->irq_routes
->nr
; i
++) {
1353 e
= &s
->irq_routes
->entries
[i
];
1354 if (e
->gsi
== virq
) {
1355 s
->irq_routes
->nr
--;
1356 *e
= s
->irq_routes
->entries
[s
->irq_routes
->nr
];
1360 kvm_arch_release_virq_post(virq
);
1361 trace_kvm_irqchip_release_virq(virq
);
1364 static unsigned int kvm_hash_msi(uint32_t data
)
1366 /* This is optimized for IA32 MSI layout. However, no other arch shall
1367 * repeat the mistake of not providing a direct MSI injection API. */
1371 static void kvm_flush_dynamic_msi_routes(KVMState
*s
)
1373 KVMMSIRoute
*route
, *next
;
1376 for (hash
= 0; hash
< KVM_MSI_HASHTAB_SIZE
; hash
++) {
1377 QTAILQ_FOREACH_SAFE(route
, &s
->msi_hashtab
[hash
], entry
, next
) {
1378 kvm_irqchip_release_virq(s
, route
->kroute
.gsi
);
1379 QTAILQ_REMOVE(&s
->msi_hashtab
[hash
], route
, entry
);
1385 static int kvm_irqchip_get_virq(KVMState
*s
)
1390 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1391 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1392 * number can succeed even though a new route entry cannot be added.
1393 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1395 if (!kvm_direct_msi_allowed
&& s
->irq_routes
->nr
== s
->gsi_count
) {
1396 kvm_flush_dynamic_msi_routes(s
);
1399 /* Return the lowest unused GSI in the bitmap */
1400 next_virq
= find_first_zero_bit(s
->used_gsi_bitmap
, s
->gsi_count
);
1401 if (next_virq
>= s
->gsi_count
) {
1408 static KVMMSIRoute
*kvm_lookup_msi_route(KVMState
*s
, MSIMessage msg
)
1410 unsigned int hash
= kvm_hash_msi(msg
.data
);
1413 QTAILQ_FOREACH(route
, &s
->msi_hashtab
[hash
], entry
) {
1414 if (route
->kroute
.u
.msi
.address_lo
== (uint32_t)msg
.address
&&
1415 route
->kroute
.u
.msi
.address_hi
== (msg
.address
>> 32) &&
1416 route
->kroute
.u
.msi
.data
== le32_to_cpu(msg
.data
)) {
1423 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1428 if (kvm_direct_msi_allowed
) {
1429 msi
.address_lo
= (uint32_t)msg
.address
;
1430 msi
.address_hi
= msg
.address
>> 32;
1431 msi
.data
= le32_to_cpu(msg
.data
);
1433 memset(msi
.pad
, 0, sizeof(msi
.pad
));
1435 return kvm_vm_ioctl(s
, KVM_SIGNAL_MSI
, &msi
);
1438 route
= kvm_lookup_msi_route(s
, msg
);
1442 virq
= kvm_irqchip_get_virq(s
);
1447 route
= g_malloc0(sizeof(KVMMSIRoute
));
1448 route
->kroute
.gsi
= virq
;
1449 route
->kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1450 route
->kroute
.flags
= 0;
1451 route
->kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1452 route
->kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1453 route
->kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1455 kvm_add_routing_entry(s
, &route
->kroute
);
1456 kvm_irqchip_commit_routes(s
);
1458 QTAILQ_INSERT_TAIL(&s
->msi_hashtab
[kvm_hash_msi(msg
.data
)], route
,
1462 assert(route
->kroute
.type
== KVM_IRQ_ROUTING_MSI
);
1464 return kvm_set_irq(s
, route
->kroute
.gsi
, 1);
1467 int kvm_irqchip_add_msi_route(KVMState
*s
, int vector
, PCIDevice
*dev
)
1469 struct kvm_irq_routing_entry kroute
= {};
1471 MSIMessage msg
= {0, 0};
1473 if (pci_available
&& dev
) {
1474 msg
= pci_get_msi_message(dev
, vector
);
1477 if (kvm_gsi_direct_mapping()) {
1478 return kvm_arch_msi_data_to_gsi(msg
.data
);
1481 if (!kvm_gsi_routing_enabled()) {
1485 virq
= kvm_irqchip_get_virq(s
);
1491 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1493 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1494 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1495 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1496 if (pci_available
&& kvm_msi_devid_required()) {
1497 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1498 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1500 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1501 kvm_irqchip_release_virq(s
, virq
);
1505 trace_kvm_irqchip_add_msi_route(dev
? dev
->name
: (char *)"N/A",
1508 kvm_add_routing_entry(s
, &kroute
);
1509 kvm_arch_add_msi_route_post(&kroute
, vector
, dev
);
1510 kvm_irqchip_commit_routes(s
);
1515 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
,
1518 struct kvm_irq_routing_entry kroute
= {};
1520 if (kvm_gsi_direct_mapping()) {
1524 if (!kvm_irqchip_in_kernel()) {
1529 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1531 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1532 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1533 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1534 if (pci_available
&& kvm_msi_devid_required()) {
1535 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1536 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1538 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1542 trace_kvm_irqchip_update_msi_route(virq
);
1544 return kvm_update_routing_entry(s
, &kroute
);
1547 static int kvm_irqchip_assign_irqfd(KVMState
*s
, int fd
, int rfd
, int virq
,
1550 struct kvm_irqfd irqfd
= {
1553 .flags
= assign
? 0 : KVM_IRQFD_FLAG_DEASSIGN
,
1557 irqfd
.flags
|= KVM_IRQFD_FLAG_RESAMPLE
;
1558 irqfd
.resamplefd
= rfd
;
1561 if (!kvm_irqfds_enabled()) {
1565 return kvm_vm_ioctl(s
, KVM_IRQFD
, &irqfd
);
1568 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
1570 struct kvm_irq_routing_entry kroute
= {};
1573 if (!kvm_gsi_routing_enabled()) {
1577 virq
= kvm_irqchip_get_virq(s
);
1583 kroute
.type
= KVM_IRQ_ROUTING_S390_ADAPTER
;
1585 kroute
.u
.adapter
.summary_addr
= adapter
->summary_addr
;
1586 kroute
.u
.adapter
.ind_addr
= adapter
->ind_addr
;
1587 kroute
.u
.adapter
.summary_offset
= adapter
->summary_offset
;
1588 kroute
.u
.adapter
.ind_offset
= adapter
->ind_offset
;
1589 kroute
.u
.adapter
.adapter_id
= adapter
->adapter_id
;
1591 kvm_add_routing_entry(s
, &kroute
);
1596 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
1598 struct kvm_irq_routing_entry kroute
= {};
1601 if (!kvm_gsi_routing_enabled()) {
1604 if (!kvm_check_extension(s
, KVM_CAP_HYPERV_SYNIC
)) {
1607 virq
= kvm_irqchip_get_virq(s
);
1613 kroute
.type
= KVM_IRQ_ROUTING_HV_SINT
;
1615 kroute
.u
.hv_sint
.vcpu
= vcpu
;
1616 kroute
.u
.hv_sint
.sint
= sint
;
1618 kvm_add_routing_entry(s
, &kroute
);
1619 kvm_irqchip_commit_routes(s
);
1624 #else /* !KVM_CAP_IRQ_ROUTING */
1626 void kvm_init_irq_routing(KVMState
*s
)
1630 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
1634 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1639 int kvm_irqchip_add_msi_route(KVMState
*s
, int vector
, PCIDevice
*dev
)
1644 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
1649 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
1654 static int kvm_irqchip_assign_irqfd(KVMState
*s
, int fd
, int virq
, bool assign
)
1659 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
)
1663 #endif /* !KVM_CAP_IRQ_ROUTING */
1665 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
1666 EventNotifier
*rn
, int virq
)
1668 return kvm_irqchip_assign_irqfd(s
, event_notifier_get_fd(n
),
1669 rn
? event_notifier_get_fd(rn
) : -1, virq
, true);
1672 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
1675 return kvm_irqchip_assign_irqfd(s
, event_notifier_get_fd(n
), -1, virq
,
1679 int kvm_irqchip_add_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
1680 EventNotifier
*rn
, qemu_irq irq
)
1683 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
1688 return kvm_irqchip_add_irqfd_notifier_gsi(s
, n
, rn
, GPOINTER_TO_INT(gsi
));
1691 int kvm_irqchip_remove_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
1695 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
1700 return kvm_irqchip_remove_irqfd_notifier_gsi(s
, n
, GPOINTER_TO_INT(gsi
));
1703 void kvm_irqchip_set_qemuirq_gsi(KVMState
*s
, qemu_irq irq
, int gsi
)
1705 g_hash_table_insert(s
->gsimap
, irq
, GINT_TO_POINTER(gsi
));
1708 static void kvm_irqchip_create(MachineState
*machine
, KVMState
*s
)
1712 if (kvm_check_extension(s
, KVM_CAP_IRQCHIP
)) {
1714 } else if (kvm_check_extension(s
, KVM_CAP_S390_IRQCHIP
)) {
1715 ret
= kvm_vm_enable_cap(s
, KVM_CAP_S390_IRQCHIP
, 0);
1717 fprintf(stderr
, "Enable kernel irqchip failed: %s\n", strerror(-ret
));
1724 /* First probe and see if there's a arch-specific hook to create the
1725 * in-kernel irqchip for us */
1726 ret
= kvm_arch_irqchip_create(machine
, s
);
1728 if (machine_kernel_irqchip_split(machine
)) {
1729 perror("Split IRQ chip mode not supported.");
1732 ret
= kvm_vm_ioctl(s
, KVM_CREATE_IRQCHIP
);
1736 fprintf(stderr
, "Create kernel irqchip failed: %s\n", strerror(-ret
));
1740 kvm_kernel_irqchip
= true;
1741 /* If we have an in-kernel IRQ chip then we must have asynchronous
1742 * interrupt delivery (though the reverse is not necessarily true)
1744 kvm_async_interrupts_allowed
= true;
1745 kvm_halt_in_kernel_allowed
= true;
1747 kvm_init_irq_routing(s
);
1749 s
->gsimap
= g_hash_table_new(g_direct_hash
, g_direct_equal
);
1752 /* Find number of supported CPUs using the recommended
1753 * procedure from the kernel API documentation to cope with
1754 * older kernels that may be missing capabilities.
1756 static int kvm_recommended_vcpus(KVMState
*s
)
1758 int ret
= kvm_vm_check_extension(s
, KVM_CAP_NR_VCPUS
);
1759 return (ret
) ? ret
: 4;
1762 static int kvm_max_vcpus(KVMState
*s
)
1764 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPUS
);
1765 return (ret
) ? ret
: kvm_recommended_vcpus(s
);
1768 static int kvm_max_vcpu_id(KVMState
*s
)
1770 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPU_ID
);
1771 return (ret
) ? ret
: kvm_max_vcpus(s
);
1774 bool kvm_vcpu_id_is_valid(int vcpu_id
)
1776 KVMState
*s
= KVM_STATE(current_machine
->accelerator
);
1777 return vcpu_id
>= 0 && vcpu_id
< kvm_max_vcpu_id(s
);
1780 static int kvm_init(MachineState
*ms
)
1782 MachineClass
*mc
= MACHINE_GET_CLASS(ms
);
1783 static const char upgrade_note
[] =
1784 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1785 "(see http://sourceforge.net/projects/kvm).\n";
1790 { "SMP", ms
->smp
.cpus
},
1791 { "hotpluggable", ms
->smp
.max_cpus
},
1794 int soft_vcpus_limit
, hard_vcpus_limit
;
1796 const KVMCapabilityInfo
*missing_cap
;
1799 const char *kvm_type
;
1801 s
= KVM_STATE(ms
->accelerator
);
1804 * On systems where the kernel can support different base page
1805 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1806 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1807 * page size for the system though.
1809 assert(TARGET_PAGE_SIZE
<= getpagesize());
1813 #ifdef KVM_CAP_SET_GUEST_DEBUG
1814 QTAILQ_INIT(&s
->kvm_sw_breakpoints
);
1816 QLIST_INIT(&s
->kvm_parked_vcpus
);
1818 s
->fd
= qemu_open("/dev/kvm", O_RDWR
);
1820 fprintf(stderr
, "Could not access KVM kernel module: %m\n");
1825 ret
= kvm_ioctl(s
, KVM_GET_API_VERSION
, 0);
1826 if (ret
< KVM_API_VERSION
) {
1830 fprintf(stderr
, "kvm version too old\n");
1834 if (ret
> KVM_API_VERSION
) {
1836 fprintf(stderr
, "kvm version not supported\n");
1840 kvm_immediate_exit
= kvm_check_extension(s
, KVM_CAP_IMMEDIATE_EXIT
);
1841 s
->nr_slots
= kvm_check_extension(s
, KVM_CAP_NR_MEMSLOTS
);
1843 /* If unspecified, use the default value */
1848 s
->nr_as
= kvm_check_extension(s
, KVM_CAP_MULTI_ADDRESS_SPACE
);
1849 if (s
->nr_as
<= 1) {
1852 s
->as
= g_new0(struct KVMAs
, s
->nr_as
);
1854 kvm_type
= qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1856 type
= mc
->kvm_type(ms
, kvm_type
);
1857 } else if (kvm_type
) {
1859 fprintf(stderr
, "Invalid argument kvm-type=%s\n", kvm_type
);
1864 ret
= kvm_ioctl(s
, KVM_CREATE_VM
, type
);
1865 } while (ret
== -EINTR
);
1868 fprintf(stderr
, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret
,
1872 if (ret
== -EINVAL
) {
1874 "Host kernel setup problem detected. Please verify:\n");
1875 fprintf(stderr
, "- for kernels supporting the switch_amode or"
1876 " user_mode parameters, whether\n");
1878 " user space is running in primary address space\n");
1880 "- for kernels supporting the vm.allocate_pgste sysctl, "
1881 "whether it is enabled\n");
1889 /* check the vcpu limits */
1890 soft_vcpus_limit
= kvm_recommended_vcpus(s
);
1891 hard_vcpus_limit
= kvm_max_vcpus(s
);
1894 if (nc
->num
> soft_vcpus_limit
) {
1895 warn_report("Number of %s cpus requested (%d) exceeds "
1896 "the recommended cpus supported by KVM (%d)",
1897 nc
->name
, nc
->num
, soft_vcpus_limit
);
1899 if (nc
->num
> hard_vcpus_limit
) {
1900 fprintf(stderr
, "Number of %s cpus requested (%d) exceeds "
1901 "the maximum cpus supported by KVM (%d)\n",
1902 nc
->name
, nc
->num
, hard_vcpus_limit
);
1909 missing_cap
= kvm_check_extension_list(s
, kvm_required_capabilites
);
1912 kvm_check_extension_list(s
, kvm_arch_required_capabilities
);
1916 fprintf(stderr
, "kvm does not support %s\n%s",
1917 missing_cap
->name
, upgrade_note
);
1921 s
->coalesced_mmio
= kvm_check_extension(s
, KVM_CAP_COALESCED_MMIO
);
1922 s
->coalesced_pio
= s
->coalesced_mmio
&&
1923 kvm_check_extension(s
, KVM_CAP_COALESCED_PIO
);
1925 s
->manual_dirty_log_protect
=
1926 kvm_check_extension(s
, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2
);
1927 if (s
->manual_dirty_log_protect
) {
1928 ret
= kvm_vm_enable_cap(s
, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2
, 0, 1);
1930 warn_report("Trying to enable KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 "
1931 "but failed. Falling back to the legacy mode. ");
1932 s
->manual_dirty_log_protect
= false;
1936 #ifdef KVM_CAP_VCPU_EVENTS
1937 s
->vcpu_events
= kvm_check_extension(s
, KVM_CAP_VCPU_EVENTS
);
1940 s
->robust_singlestep
=
1941 kvm_check_extension(s
, KVM_CAP_X86_ROBUST_SINGLESTEP
);
1943 #ifdef KVM_CAP_DEBUGREGS
1944 s
->debugregs
= kvm_check_extension(s
, KVM_CAP_DEBUGREGS
);
1947 s
->max_nested_state_len
= kvm_check_extension(s
, KVM_CAP_NESTED_STATE
);
1949 #ifdef KVM_CAP_IRQ_ROUTING
1950 kvm_direct_msi_allowed
= (kvm_check_extension(s
, KVM_CAP_SIGNAL_MSI
) > 0);
1953 s
->intx_set_mask
= kvm_check_extension(s
, KVM_CAP_PCI_2_3
);
1955 s
->irq_set_ioctl
= KVM_IRQ_LINE
;
1956 if (kvm_check_extension(s
, KVM_CAP_IRQ_INJECT_STATUS
)) {
1957 s
->irq_set_ioctl
= KVM_IRQ_LINE_STATUS
;
1960 kvm_readonly_mem_allowed
=
1961 (kvm_check_extension(s
, KVM_CAP_READONLY_MEM
) > 0);
1963 kvm_eventfds_allowed
=
1964 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD
) > 0);
1966 kvm_irqfds_allowed
=
1967 (kvm_check_extension(s
, KVM_CAP_IRQFD
) > 0);
1969 kvm_resamplefds_allowed
=
1970 (kvm_check_extension(s
, KVM_CAP_IRQFD_RESAMPLE
) > 0);
1972 kvm_vm_attributes_allowed
=
1973 (kvm_check_extension(s
, KVM_CAP_VM_ATTRIBUTES
) > 0);
1975 kvm_ioeventfd_any_length_allowed
=
1976 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD_ANY_LENGTH
) > 0);
1981 * if memory encryption object is specified then initialize the memory
1982 * encryption context.
1984 if (ms
->memory_encryption
) {
1985 kvm_state
->memcrypt_handle
= sev_guest_init(ms
->memory_encryption
);
1986 if (!kvm_state
->memcrypt_handle
) {
1991 kvm_state
->memcrypt_encrypt_data
= sev_encrypt_data
;
1994 ret
= kvm_arch_init(ms
, s
);
1999 if (machine_kernel_irqchip_allowed(ms
)) {
2000 kvm_irqchip_create(ms
, s
);
2003 if (kvm_eventfds_allowed
) {
2004 s
->memory_listener
.listener
.eventfd_add
= kvm_mem_ioeventfd_add
;
2005 s
->memory_listener
.listener
.eventfd_del
= kvm_mem_ioeventfd_del
;
2007 s
->memory_listener
.listener
.coalesced_io_add
= kvm_coalesce_mmio_region
;
2008 s
->memory_listener
.listener
.coalesced_io_del
= kvm_uncoalesce_mmio_region
;
2010 kvm_memory_listener_register(s
, &s
->memory_listener
,
2011 &address_space_memory
, 0);
2012 memory_listener_register(&kvm_io_listener
,
2014 memory_listener_register(&kvm_coalesced_pio_listener
,
2017 s
->many_ioeventfds
= kvm_check_many_ioeventfds();
2019 s
->sync_mmu
= !!kvm_vm_check_extension(kvm_state
, KVM_CAP_SYNC_MMU
);
2021 qemu_balloon_inhibit(true);
2034 g_free(s
->memory_listener
.slots
);
2039 void kvm_set_sigmask_len(KVMState
*s
, unsigned int sigmask_len
)
2041 s
->sigmask_len
= sigmask_len
;
2044 static void kvm_handle_io(uint16_t port
, MemTxAttrs attrs
, void *data
, int direction
,
2045 int size
, uint32_t count
)
2048 uint8_t *ptr
= data
;
2050 for (i
= 0; i
< count
; i
++) {
2051 address_space_rw(&address_space_io
, port
, attrs
,
2053 direction
== KVM_EXIT_IO_OUT
);
2058 static int kvm_handle_internal_error(CPUState
*cpu
, struct kvm_run
*run
)
2060 fprintf(stderr
, "KVM internal error. Suberror: %d\n",
2061 run
->internal
.suberror
);
2063 if (kvm_check_extension(kvm_state
, KVM_CAP_INTERNAL_ERROR_DATA
)) {
2066 for (i
= 0; i
< run
->internal
.ndata
; ++i
) {
2067 fprintf(stderr
, "extra data[%d]: %"PRIx64
"\n",
2068 i
, (uint64_t)run
->internal
.data
[i
]);
2071 if (run
->internal
.suberror
== KVM_INTERNAL_ERROR_EMULATION
) {
2072 fprintf(stderr
, "emulation failure\n");
2073 if (!kvm_arch_stop_on_emulation_error(cpu
)) {
2074 cpu_dump_state(cpu
, stderr
, CPU_DUMP_CODE
);
2075 return EXCP_INTERRUPT
;
2078 /* FIXME: Should trigger a qmp message to let management know
2079 * something went wrong.
2084 void kvm_flush_coalesced_mmio_buffer(void)
2086 KVMState
*s
= kvm_state
;
2088 if (s
->coalesced_flush_in_progress
) {
2092 s
->coalesced_flush_in_progress
= true;
2094 if (s
->coalesced_mmio_ring
) {
2095 struct kvm_coalesced_mmio_ring
*ring
= s
->coalesced_mmio_ring
;
2096 while (ring
->first
!= ring
->last
) {
2097 struct kvm_coalesced_mmio
*ent
;
2099 ent
= &ring
->coalesced_mmio
[ring
->first
];
2101 if (ent
->pio
== 1) {
2102 address_space_rw(&address_space_io
, ent
->phys_addr
,
2103 MEMTXATTRS_UNSPECIFIED
, ent
->data
,
2106 cpu_physical_memory_write(ent
->phys_addr
, ent
->data
, ent
->len
);
2109 ring
->first
= (ring
->first
+ 1) % KVM_COALESCED_MMIO_MAX
;
2113 s
->coalesced_flush_in_progress
= false;
2116 static void do_kvm_cpu_synchronize_state(CPUState
*cpu
, run_on_cpu_data arg
)
2118 if (!cpu
->vcpu_dirty
) {
2119 kvm_arch_get_registers(cpu
);
2120 cpu
->vcpu_dirty
= true;
2124 void kvm_cpu_synchronize_state(CPUState
*cpu
)
2126 if (!cpu
->vcpu_dirty
) {
2127 run_on_cpu(cpu
, do_kvm_cpu_synchronize_state
, RUN_ON_CPU_NULL
);
2131 static void do_kvm_cpu_synchronize_post_reset(CPUState
*cpu
, run_on_cpu_data arg
)
2133 kvm_arch_put_registers(cpu
, KVM_PUT_RESET_STATE
);
2134 cpu
->vcpu_dirty
= false;
2137 void kvm_cpu_synchronize_post_reset(CPUState
*cpu
)
2139 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_reset
, RUN_ON_CPU_NULL
);
2142 static void do_kvm_cpu_synchronize_post_init(CPUState
*cpu
, run_on_cpu_data arg
)
2144 kvm_arch_put_registers(cpu
, KVM_PUT_FULL_STATE
);
2145 cpu
->vcpu_dirty
= false;
2148 void kvm_cpu_synchronize_post_init(CPUState
*cpu
)
2150 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_init
, RUN_ON_CPU_NULL
);
2153 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
, run_on_cpu_data arg
)
2155 cpu
->vcpu_dirty
= true;
2158 void kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
)
2160 run_on_cpu(cpu
, do_kvm_cpu_synchronize_pre_loadvm
, RUN_ON_CPU_NULL
);
2163 #ifdef KVM_HAVE_MCE_INJECTION
2164 static __thread
void *pending_sigbus_addr
;
2165 static __thread
int pending_sigbus_code
;
2166 static __thread
bool have_sigbus_pending
;
2169 static void kvm_cpu_kick(CPUState
*cpu
)
2171 atomic_set(&cpu
->kvm_run
->immediate_exit
, 1);
2174 static void kvm_cpu_kick_self(void)
2176 if (kvm_immediate_exit
) {
2177 kvm_cpu_kick(current_cpu
);
2179 qemu_cpu_kick_self();
2183 static void kvm_eat_signals(CPUState
*cpu
)
2185 struct timespec ts
= { 0, 0 };
2191 if (kvm_immediate_exit
) {
2192 atomic_set(&cpu
->kvm_run
->immediate_exit
, 0);
2193 /* Write kvm_run->immediate_exit before the cpu->exit_request
2194 * write in kvm_cpu_exec.
2200 sigemptyset(&waitset
);
2201 sigaddset(&waitset
, SIG_IPI
);
2204 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
2205 if (r
== -1 && !(errno
== EAGAIN
|| errno
== EINTR
)) {
2206 perror("sigtimedwait");
2210 r
= sigpending(&chkset
);
2212 perror("sigpending");
2215 } while (sigismember(&chkset
, SIG_IPI
));
2218 int kvm_cpu_exec(CPUState
*cpu
)
2220 struct kvm_run
*run
= cpu
->kvm_run
;
2223 DPRINTF("kvm_cpu_exec()\n");
2225 if (kvm_arch_process_async_events(cpu
)) {
2226 atomic_set(&cpu
->exit_request
, 0);
2230 qemu_mutex_unlock_iothread();
2231 cpu_exec_start(cpu
);
2236 if (cpu
->vcpu_dirty
) {
2237 kvm_arch_put_registers(cpu
, KVM_PUT_RUNTIME_STATE
);
2238 cpu
->vcpu_dirty
= false;
2241 kvm_arch_pre_run(cpu
, run
);
2242 if (atomic_read(&cpu
->exit_request
)) {
2243 DPRINTF("interrupt exit requested\n");
2245 * KVM requires us to reenter the kernel after IO exits to complete
2246 * instruction emulation. This self-signal will ensure that we
2249 kvm_cpu_kick_self();
2252 /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2253 * Matching barrier in kvm_eat_signals.
2257 run_ret
= kvm_vcpu_ioctl(cpu
, KVM_RUN
, 0);
2259 attrs
= kvm_arch_post_run(cpu
, run
);
2261 #ifdef KVM_HAVE_MCE_INJECTION
2262 if (unlikely(have_sigbus_pending
)) {
2263 qemu_mutex_lock_iothread();
2264 kvm_arch_on_sigbus_vcpu(cpu
, pending_sigbus_code
,
2265 pending_sigbus_addr
);
2266 have_sigbus_pending
= false;
2267 qemu_mutex_unlock_iothread();
2272 if (run_ret
== -EINTR
|| run_ret
== -EAGAIN
) {
2273 DPRINTF("io window exit\n");
2274 kvm_eat_signals(cpu
);
2275 ret
= EXCP_INTERRUPT
;
2278 fprintf(stderr
, "error: kvm run failed %s\n",
2279 strerror(-run_ret
));
2281 if (run_ret
== -EBUSY
) {
2283 "This is probably because your SMT is enabled.\n"
2284 "VCPU can only run on primary threads with all "
2285 "secondary threads offline.\n");
2292 trace_kvm_run_exit(cpu
->cpu_index
, run
->exit_reason
);
2293 switch (run
->exit_reason
) {
2295 DPRINTF("handle_io\n");
2296 /* Called outside BQL */
2297 kvm_handle_io(run
->io
.port
, attrs
,
2298 (uint8_t *)run
+ run
->io
.data_offset
,
2305 DPRINTF("handle_mmio\n");
2306 /* Called outside BQL */
2307 address_space_rw(&address_space_memory
,
2308 run
->mmio
.phys_addr
, attrs
,
2311 run
->mmio
.is_write
);
2314 case KVM_EXIT_IRQ_WINDOW_OPEN
:
2315 DPRINTF("irq_window_open\n");
2316 ret
= EXCP_INTERRUPT
;
2318 case KVM_EXIT_SHUTDOWN
:
2319 DPRINTF("shutdown\n");
2320 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
2321 ret
= EXCP_INTERRUPT
;
2323 case KVM_EXIT_UNKNOWN
:
2324 fprintf(stderr
, "KVM: unknown exit, hardware reason %" PRIx64
"\n",
2325 (uint64_t)run
->hw
.hardware_exit_reason
);
2328 case KVM_EXIT_INTERNAL_ERROR
:
2329 ret
= kvm_handle_internal_error(cpu
, run
);
2331 case KVM_EXIT_SYSTEM_EVENT
:
2332 switch (run
->system_event
.type
) {
2333 case KVM_SYSTEM_EVENT_SHUTDOWN
:
2334 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN
);
2335 ret
= EXCP_INTERRUPT
;
2337 case KVM_SYSTEM_EVENT_RESET
:
2338 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
2339 ret
= EXCP_INTERRUPT
;
2341 case KVM_SYSTEM_EVENT_CRASH
:
2342 kvm_cpu_synchronize_state(cpu
);
2343 qemu_mutex_lock_iothread();
2344 qemu_system_guest_panicked(cpu_get_crash_info(cpu
));
2345 qemu_mutex_unlock_iothread();
2349 DPRINTF("kvm_arch_handle_exit\n");
2350 ret
= kvm_arch_handle_exit(cpu
, run
);
2355 DPRINTF("kvm_arch_handle_exit\n");
2356 ret
= kvm_arch_handle_exit(cpu
, run
);
2362 qemu_mutex_lock_iothread();
2365 cpu_dump_state(cpu
, stderr
, CPU_DUMP_CODE
);
2366 vm_stop(RUN_STATE_INTERNAL_ERROR
);
2369 atomic_set(&cpu
->exit_request
, 0);
2373 int kvm_ioctl(KVMState
*s
, int type
, ...)
2380 arg
= va_arg(ap
, void *);
2383 trace_kvm_ioctl(type
, arg
);
2384 ret
= ioctl(s
->fd
, type
, arg
);
2391 int kvm_vm_ioctl(KVMState
*s
, int type
, ...)
2398 arg
= va_arg(ap
, void *);
2401 trace_kvm_vm_ioctl(type
, arg
);
2402 ret
= ioctl(s
->vmfd
, type
, arg
);
2409 int kvm_vcpu_ioctl(CPUState
*cpu
, int type
, ...)
2416 arg
= va_arg(ap
, void *);
2419 trace_kvm_vcpu_ioctl(cpu
->cpu_index
, type
, arg
);
2420 ret
= ioctl(cpu
->kvm_fd
, type
, arg
);
2427 int kvm_device_ioctl(int fd
, int type
, ...)
2434 arg
= va_arg(ap
, void *);
2437 trace_kvm_device_ioctl(fd
, type
, arg
);
2438 ret
= ioctl(fd
, type
, arg
);
2445 int kvm_vm_check_attr(KVMState
*s
, uint32_t group
, uint64_t attr
)
2448 struct kvm_device_attr attribute
= {
2453 if (!kvm_vm_attributes_allowed
) {
2457 ret
= kvm_vm_ioctl(s
, KVM_HAS_DEVICE_ATTR
, &attribute
);
2458 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2462 int kvm_device_check_attr(int dev_fd
, uint32_t group
, uint64_t attr
)
2464 struct kvm_device_attr attribute
= {
2470 return kvm_device_ioctl(dev_fd
, KVM_HAS_DEVICE_ATTR
, &attribute
) ? 0 : 1;
2473 int kvm_device_access(int fd
, int group
, uint64_t attr
,
2474 void *val
, bool write
, Error
**errp
)
2476 struct kvm_device_attr kvmattr
;
2480 kvmattr
.group
= group
;
2481 kvmattr
.attr
= attr
;
2482 kvmattr
.addr
= (uintptr_t)val
;
2484 err
= kvm_device_ioctl(fd
,
2485 write
? KVM_SET_DEVICE_ATTR
: KVM_GET_DEVICE_ATTR
,
2488 error_setg_errno(errp
, -err
,
2489 "KVM_%s_DEVICE_ATTR failed: Group %d "
2490 "attr 0x%016" PRIx64
,
2491 write
? "SET" : "GET", group
, attr
);
2496 bool kvm_has_sync_mmu(void)
2498 return kvm_state
->sync_mmu
;
2501 int kvm_has_vcpu_events(void)
2503 return kvm_state
->vcpu_events
;
2506 int kvm_has_robust_singlestep(void)
2508 return kvm_state
->robust_singlestep
;
2511 int kvm_has_debugregs(void)
2513 return kvm_state
->debugregs
;
2516 int kvm_max_nested_state_length(void)
2518 return kvm_state
->max_nested_state_len
;
2521 int kvm_has_many_ioeventfds(void)
2523 if (!kvm_enabled()) {
2526 return kvm_state
->many_ioeventfds
;
2529 int kvm_has_gsi_routing(void)
2531 #ifdef KVM_CAP_IRQ_ROUTING
2532 return kvm_check_extension(kvm_state
, KVM_CAP_IRQ_ROUTING
);
2538 int kvm_has_intx_set_mask(void)
2540 return kvm_state
->intx_set_mask
;
2543 bool kvm_arm_supports_user_irq(void)
2545 return kvm_check_extension(kvm_state
, KVM_CAP_ARM_USER_IRQ
);
2548 #ifdef KVM_CAP_SET_GUEST_DEBUG
2549 struct kvm_sw_breakpoint
*kvm_find_sw_breakpoint(CPUState
*cpu
,
2552 struct kvm_sw_breakpoint
*bp
;
2554 QTAILQ_FOREACH(bp
, &cpu
->kvm_state
->kvm_sw_breakpoints
, entry
) {
2562 int kvm_sw_breakpoints_active(CPUState
*cpu
)
2564 return !QTAILQ_EMPTY(&cpu
->kvm_state
->kvm_sw_breakpoints
);
2567 struct kvm_set_guest_debug_data
{
2568 struct kvm_guest_debug dbg
;
2572 static void kvm_invoke_set_guest_debug(CPUState
*cpu
, run_on_cpu_data data
)
2574 struct kvm_set_guest_debug_data
*dbg_data
=
2575 (struct kvm_set_guest_debug_data
*) data
.host_ptr
;
2577 dbg_data
->err
= kvm_vcpu_ioctl(cpu
, KVM_SET_GUEST_DEBUG
,
2581 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
2583 struct kvm_set_guest_debug_data data
;
2585 data
.dbg
.control
= reinject_trap
;
2587 if (cpu
->singlestep_enabled
) {
2588 data
.dbg
.control
|= KVM_GUESTDBG_ENABLE
| KVM_GUESTDBG_SINGLESTEP
;
2590 kvm_arch_update_guest_debug(cpu
, &data
.dbg
);
2592 run_on_cpu(cpu
, kvm_invoke_set_guest_debug
,
2593 RUN_ON_CPU_HOST_PTR(&data
));
2597 int kvm_insert_breakpoint(CPUState
*cpu
, target_ulong addr
,
2598 target_ulong len
, int type
)
2600 struct kvm_sw_breakpoint
*bp
;
2603 if (type
== GDB_BREAKPOINT_SW
) {
2604 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
2610 bp
= g_malloc(sizeof(struct kvm_sw_breakpoint
));
2613 err
= kvm_arch_insert_sw_breakpoint(cpu
, bp
);
2619 QTAILQ_INSERT_HEAD(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
2621 err
= kvm_arch_insert_hw_breakpoint(addr
, len
, type
);
2628 err
= kvm_update_guest_debug(cpu
, 0);
2636 int kvm_remove_breakpoint(CPUState
*cpu
, target_ulong addr
,
2637 target_ulong len
, int type
)
2639 struct kvm_sw_breakpoint
*bp
;
2642 if (type
== GDB_BREAKPOINT_SW
) {
2643 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
2648 if (bp
->use_count
> 1) {
2653 err
= kvm_arch_remove_sw_breakpoint(cpu
, bp
);
2658 QTAILQ_REMOVE(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
2661 err
= kvm_arch_remove_hw_breakpoint(addr
, len
, type
);
2668 err
= kvm_update_guest_debug(cpu
, 0);
2676 void kvm_remove_all_breakpoints(CPUState
*cpu
)
2678 struct kvm_sw_breakpoint
*bp
, *next
;
2679 KVMState
*s
= cpu
->kvm_state
;
2682 QTAILQ_FOREACH_SAFE(bp
, &s
->kvm_sw_breakpoints
, entry
, next
) {
2683 if (kvm_arch_remove_sw_breakpoint(cpu
, bp
) != 0) {
2684 /* Try harder to find a CPU that currently sees the breakpoint. */
2685 CPU_FOREACH(tmpcpu
) {
2686 if (kvm_arch_remove_sw_breakpoint(tmpcpu
, bp
) == 0) {
2691 QTAILQ_REMOVE(&s
->kvm_sw_breakpoints
, bp
, entry
);
2694 kvm_arch_remove_all_hw_breakpoints();
2697 kvm_update_guest_debug(cpu
, 0);
2701 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2703 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
2708 int kvm_insert_breakpoint(CPUState
*cpu
, target_ulong addr
,
2709 target_ulong len
, int type
)
2714 int kvm_remove_breakpoint(CPUState
*cpu
, target_ulong addr
,
2715 target_ulong len
, int type
)
2720 void kvm_remove_all_breakpoints(CPUState
*cpu
)
2723 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2725 static int kvm_set_signal_mask(CPUState
*cpu
, const sigset_t
*sigset
)
2727 KVMState
*s
= kvm_state
;
2728 struct kvm_signal_mask
*sigmask
;
2731 sigmask
= g_malloc(sizeof(*sigmask
) + sizeof(*sigset
));
2733 sigmask
->len
= s
->sigmask_len
;
2734 memcpy(sigmask
->sigset
, sigset
, sizeof(*sigset
));
2735 r
= kvm_vcpu_ioctl(cpu
, KVM_SET_SIGNAL_MASK
, sigmask
);
2741 static void kvm_ipi_signal(int sig
)
2744 assert(kvm_immediate_exit
);
2745 kvm_cpu_kick(current_cpu
);
2749 void kvm_init_cpu_signals(CPUState
*cpu
)
2753 struct sigaction sigact
;
2755 memset(&sigact
, 0, sizeof(sigact
));
2756 sigact
.sa_handler
= kvm_ipi_signal
;
2757 sigaction(SIG_IPI
, &sigact
, NULL
);
2759 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
2760 #if defined KVM_HAVE_MCE_INJECTION
2761 sigdelset(&set
, SIGBUS
);
2762 pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
2764 sigdelset(&set
, SIG_IPI
);
2765 if (kvm_immediate_exit
) {
2766 r
= pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
2768 r
= kvm_set_signal_mask(cpu
, &set
);
2771 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(-r
));
2776 /* Called asynchronously in VCPU thread. */
2777 int kvm_on_sigbus_vcpu(CPUState
*cpu
, int code
, void *addr
)
2779 #ifdef KVM_HAVE_MCE_INJECTION
2780 if (have_sigbus_pending
) {
2783 have_sigbus_pending
= true;
2784 pending_sigbus_addr
= addr
;
2785 pending_sigbus_code
= code
;
2786 atomic_set(&cpu
->exit_request
, 1);
2793 /* Called synchronously (via signalfd) in main thread. */
2794 int kvm_on_sigbus(int code
, void *addr
)
2796 #ifdef KVM_HAVE_MCE_INJECTION
2797 /* Action required MCE kills the process if SIGBUS is blocked. Because
2798 * that's what happens in the I/O thread, where we handle MCE via signalfd,
2799 * we can only get action optional here.
2801 assert(code
!= BUS_MCEERR_AR
);
2802 kvm_arch_on_sigbus_vcpu(first_cpu
, code
, addr
);
2809 int kvm_create_device(KVMState
*s
, uint64_t type
, bool test
)
2812 struct kvm_create_device create_dev
;
2814 create_dev
.type
= type
;
2816 create_dev
.flags
= test
? KVM_CREATE_DEVICE_TEST
: 0;
2818 if (!kvm_check_extension(s
, KVM_CAP_DEVICE_CTRL
)) {
2822 ret
= kvm_vm_ioctl(s
, KVM_CREATE_DEVICE
, &create_dev
);
2827 return test
? 0 : create_dev
.fd
;
2830 bool kvm_device_supported(int vmfd
, uint64_t type
)
2832 struct kvm_create_device create_dev
= {
2835 .flags
= KVM_CREATE_DEVICE_TEST
,
2838 if (ioctl(vmfd
, KVM_CHECK_EXTENSION
, KVM_CAP_DEVICE_CTRL
) <= 0) {
2842 return (ioctl(vmfd
, KVM_CREATE_DEVICE
, &create_dev
) >= 0);
2845 int kvm_set_one_reg(CPUState
*cs
, uint64_t id
, void *source
)
2847 struct kvm_one_reg reg
;
2851 reg
.addr
= (uintptr_t) source
;
2852 r
= kvm_vcpu_ioctl(cs
, KVM_SET_ONE_REG
, ®
);
2854 trace_kvm_failed_reg_set(id
, strerror(-r
));
2859 int kvm_get_one_reg(CPUState
*cs
, uint64_t id
, void *target
)
2861 struct kvm_one_reg reg
;
2865 reg
.addr
= (uintptr_t) target
;
2866 r
= kvm_vcpu_ioctl(cs
, KVM_GET_ONE_REG
, ®
);
2868 trace_kvm_failed_reg_get(id
, strerror(-r
));
2873 static bool kvm_accel_has_memory(MachineState
*ms
, AddressSpace
*as
,
2874 hwaddr start_addr
, hwaddr size
)
2876 KVMState
*kvm
= KVM_STATE(ms
->accelerator
);
2879 for (i
= 0; i
< kvm
->nr_as
; ++i
) {
2880 if (kvm
->as
[i
].as
== as
&& kvm
->as
[i
].ml
) {
2881 return NULL
!= kvm_lookup_matching_slot(kvm
->as
[i
].ml
,
2889 static void kvm_accel_class_init(ObjectClass
*oc
, void *data
)
2891 AccelClass
*ac
= ACCEL_CLASS(oc
);
2893 ac
->init_machine
= kvm_init
;
2894 ac
->has_memory
= kvm_accel_has_memory
;
2895 ac
->allowed
= &kvm_allowed
;
2898 static const TypeInfo kvm_accel_type
= {
2899 .name
= TYPE_KVM_ACCEL
,
2900 .parent
= TYPE_ACCEL
,
2901 .class_init
= kvm_accel_class_init
,
2902 .instance_size
= sizeof(KVMState
),
2905 static void kvm_type_init(void)
2907 type_register_static(&kvm_accel_type
);
2910 type_init(kvm_type_init
);