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"
44 #include "qapi/visitor.h"
45 #include "qapi/qapi-types-common.h"
46 #include "qapi/qapi-visit-common.h"
48 #include "hw/boards.h"
50 /* This check must be after config-host.h is included */
52 #include <sys/eventfd.h>
55 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
56 * need to use the real host PAGE_SIZE, as that's what KVM will use.
58 #define PAGE_SIZE qemu_real_host_page_size
63 #define DPRINTF(fmt, ...) \
64 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
66 #define DPRINTF(fmt, ...) \
70 #define KVM_MSI_HASHTAB_SIZE 256
72 struct KVMParkedVcpu
{
73 unsigned long vcpu_id
;
75 QLIST_ENTRY(KVMParkedVcpu
) node
;
80 AccelState parent_obj
;
87 struct kvm_coalesced_mmio_ring
*coalesced_mmio_ring
;
88 bool coalesced_flush_in_progress
;
90 int robust_singlestep
;
92 #ifdef KVM_CAP_SET_GUEST_DEBUG
93 QTAILQ_HEAD(, kvm_sw_breakpoint
) kvm_sw_breakpoints
;
95 int max_nested_state_len
;
99 bool kernel_irqchip_allowed
;
100 bool kernel_irqchip_required
;
101 bool kernel_irqchip_split
;
103 bool manual_dirty_log_protect
;
104 /* The man page (and posix) say ioctl numbers are signed int, but
105 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
106 * unsigned, and treating them as signed here can break things */
107 unsigned irq_set_ioctl
;
108 unsigned int sigmask_len
;
110 #ifdef KVM_CAP_IRQ_ROUTING
111 struct kvm_irq_routing
*irq_routes
;
112 int nr_allocated_irq_routes
;
113 unsigned long *used_gsi_bitmap
;
114 unsigned int gsi_count
;
115 QTAILQ_HEAD(, KVMMSIRoute
) msi_hashtab
[KVM_MSI_HASHTAB_SIZE
];
117 KVMMemoryListener memory_listener
;
118 QLIST_HEAD(, KVMParkedVcpu
) kvm_parked_vcpus
;
120 /* memory encryption */
121 void *memcrypt_handle
;
122 int (*memcrypt_encrypt_data
)(void *handle
, uint8_t *ptr
, uint64_t len
);
124 /* For "info mtree -f" to tell if an MR is registered in KVM */
127 KVMMemoryListener
*ml
;
133 bool kvm_kernel_irqchip
;
134 bool kvm_split_irqchip
;
135 bool kvm_async_interrupts_allowed
;
136 bool kvm_halt_in_kernel_allowed
;
137 bool kvm_eventfds_allowed
;
138 bool kvm_irqfds_allowed
;
139 bool kvm_resamplefds_allowed
;
140 bool kvm_msi_via_irqfd_allowed
;
141 bool kvm_gsi_routing_allowed
;
142 bool kvm_gsi_direct_mapping
;
144 bool kvm_readonly_mem_allowed
;
145 bool kvm_vm_attributes_allowed
;
146 bool kvm_direct_msi_allowed
;
147 bool kvm_ioeventfd_any_length_allowed
;
148 bool kvm_msi_use_devid
;
149 static bool kvm_immediate_exit
;
150 static hwaddr kvm_max_slot_size
= ~0;
152 static const KVMCapabilityInfo kvm_required_capabilites
[] = {
153 KVM_CAP_INFO(USER_MEMORY
),
154 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS
),
155 KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS
),
159 static NotifierList kvm_irqchip_change_notifiers
=
160 NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers
);
162 #define kvm_slots_lock(kml) qemu_mutex_lock(&(kml)->slots_lock)
163 #define kvm_slots_unlock(kml) qemu_mutex_unlock(&(kml)->slots_lock)
165 int kvm_get_max_memslots(void)
167 KVMState
*s
= KVM_STATE(current_machine
->accelerator
);
172 bool kvm_memcrypt_enabled(void)
174 if (kvm_state
&& kvm_state
->memcrypt_handle
) {
181 int kvm_memcrypt_encrypt_data(uint8_t *ptr
, uint64_t len
)
183 if (kvm_state
->memcrypt_handle
&&
184 kvm_state
->memcrypt_encrypt_data
) {
185 return kvm_state
->memcrypt_encrypt_data(kvm_state
->memcrypt_handle
,
192 /* Called with KVMMemoryListener.slots_lock held */
193 static KVMSlot
*kvm_get_free_slot(KVMMemoryListener
*kml
)
195 KVMState
*s
= kvm_state
;
198 for (i
= 0; i
< s
->nr_slots
; i
++) {
199 if (kml
->slots
[i
].memory_size
== 0) {
200 return &kml
->slots
[i
];
207 bool kvm_has_free_slot(MachineState
*ms
)
209 KVMState
*s
= KVM_STATE(ms
->accelerator
);
211 KVMMemoryListener
*kml
= &s
->memory_listener
;
214 result
= !!kvm_get_free_slot(kml
);
215 kvm_slots_unlock(kml
);
220 /* Called with KVMMemoryListener.slots_lock held */
221 static KVMSlot
*kvm_alloc_slot(KVMMemoryListener
*kml
)
223 KVMSlot
*slot
= kvm_get_free_slot(kml
);
229 fprintf(stderr
, "%s: no free slot available\n", __func__
);
233 static KVMSlot
*kvm_lookup_matching_slot(KVMMemoryListener
*kml
,
237 KVMState
*s
= kvm_state
;
240 for (i
= 0; i
< s
->nr_slots
; i
++) {
241 KVMSlot
*mem
= &kml
->slots
[i
];
243 if (start_addr
== mem
->start_addr
&& size
== mem
->memory_size
) {
252 * Calculate and align the start address and the size of the section.
253 * Return the size. If the size is 0, the aligned section is empty.
255 static hwaddr
kvm_align_section(MemoryRegionSection
*section
,
258 hwaddr size
= int128_get64(section
->size
);
259 hwaddr delta
, aligned
;
261 /* kvm works in page size chunks, but the function may be called
262 with sub-page size and unaligned start address. Pad the start
263 address to next and truncate size to previous page boundary. */
264 aligned
= ROUND_UP(section
->offset_within_address_space
,
265 qemu_real_host_page_size
);
266 delta
= aligned
- section
->offset_within_address_space
;
272 return (size
- delta
) & qemu_real_host_page_mask
;
275 int kvm_physical_memory_addr_from_host(KVMState
*s
, void *ram
,
278 KVMMemoryListener
*kml
= &s
->memory_listener
;
282 for (i
= 0; i
< s
->nr_slots
; i
++) {
283 KVMSlot
*mem
= &kml
->slots
[i
];
285 if (ram
>= mem
->ram
&& ram
< mem
->ram
+ mem
->memory_size
) {
286 *phys_addr
= mem
->start_addr
+ (ram
- mem
->ram
);
291 kvm_slots_unlock(kml
);
296 static int kvm_set_user_memory_region(KVMMemoryListener
*kml
, KVMSlot
*slot
, bool new)
298 KVMState
*s
= kvm_state
;
299 struct kvm_userspace_memory_region mem
;
302 mem
.slot
= slot
->slot
| (kml
->as_id
<< 16);
303 mem
.guest_phys_addr
= slot
->start_addr
;
304 mem
.userspace_addr
= (unsigned long)slot
->ram
;
305 mem
.flags
= slot
->flags
;
307 if (slot
->memory_size
&& !new && (mem
.flags
^ slot
->old_flags
) & KVM_MEM_READONLY
) {
308 /* Set the slot size to 0 before setting the slot to the desired
309 * value. This is needed based on KVM commit 75d61fbc. */
311 kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
313 mem
.memory_size
= slot
->memory_size
;
314 ret
= kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
315 slot
->old_flags
= mem
.flags
;
316 trace_kvm_set_user_memory(mem
.slot
, mem
.flags
, mem
.guest_phys_addr
,
317 mem
.memory_size
, mem
.userspace_addr
, ret
);
321 int kvm_destroy_vcpu(CPUState
*cpu
)
323 KVMState
*s
= kvm_state
;
325 struct KVMParkedVcpu
*vcpu
= NULL
;
328 DPRINTF("kvm_destroy_vcpu\n");
330 ret
= kvm_arch_destroy_vcpu(cpu
);
335 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
338 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
342 ret
= munmap(cpu
->kvm_run
, mmap_size
);
347 vcpu
= g_malloc0(sizeof(*vcpu
));
348 vcpu
->vcpu_id
= kvm_arch_vcpu_id(cpu
);
349 vcpu
->kvm_fd
= cpu
->kvm_fd
;
350 QLIST_INSERT_HEAD(&kvm_state
->kvm_parked_vcpus
, vcpu
, node
);
355 static int kvm_get_vcpu(KVMState
*s
, unsigned long vcpu_id
)
357 struct KVMParkedVcpu
*cpu
;
359 QLIST_FOREACH(cpu
, &s
->kvm_parked_vcpus
, node
) {
360 if (cpu
->vcpu_id
== vcpu_id
) {
363 QLIST_REMOVE(cpu
, node
);
364 kvm_fd
= cpu
->kvm_fd
;
370 return kvm_vm_ioctl(s
, KVM_CREATE_VCPU
, (void *)vcpu_id
);
373 int kvm_init_vcpu(CPUState
*cpu
)
375 KVMState
*s
= kvm_state
;
379 DPRINTF("kvm_init_vcpu\n");
381 ret
= kvm_get_vcpu(s
, kvm_arch_vcpu_id(cpu
));
383 DPRINTF("kvm_create_vcpu failed\n");
389 cpu
->vcpu_dirty
= true;
391 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
394 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
398 cpu
->kvm_run
= mmap(NULL
, mmap_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
400 if (cpu
->kvm_run
== MAP_FAILED
) {
402 DPRINTF("mmap'ing vcpu state failed\n");
406 if (s
->coalesced_mmio
&& !s
->coalesced_mmio_ring
) {
407 s
->coalesced_mmio_ring
=
408 (void *)cpu
->kvm_run
+ s
->coalesced_mmio
* PAGE_SIZE
;
411 ret
= kvm_arch_init_vcpu(cpu
);
417 * dirty pages logging control
420 static int kvm_mem_flags(MemoryRegion
*mr
)
422 bool readonly
= mr
->readonly
|| memory_region_is_romd(mr
);
425 if (memory_region_get_dirty_log_mask(mr
) != 0) {
426 flags
|= KVM_MEM_LOG_DIRTY_PAGES
;
428 if (readonly
&& kvm_readonly_mem_allowed
) {
429 flags
|= KVM_MEM_READONLY
;
434 /* Called with KVMMemoryListener.slots_lock held */
435 static int kvm_slot_update_flags(KVMMemoryListener
*kml
, KVMSlot
*mem
,
438 mem
->flags
= kvm_mem_flags(mr
);
440 /* If nothing changed effectively, no need to issue ioctl */
441 if (mem
->flags
== mem
->old_flags
) {
445 return kvm_set_user_memory_region(kml
, mem
, false);
448 static int kvm_section_update_flags(KVMMemoryListener
*kml
,
449 MemoryRegionSection
*section
)
451 hwaddr start_addr
, size
, slot_size
;
455 size
= kvm_align_section(section
, &start_addr
);
462 while (size
&& !ret
) {
463 slot_size
= MIN(kvm_max_slot_size
, size
);
464 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
466 /* We don't have a slot if we want to trap every access. */
470 ret
= kvm_slot_update_flags(kml
, mem
, section
->mr
);
471 start_addr
+= slot_size
;
476 kvm_slots_unlock(kml
);
480 static void kvm_log_start(MemoryListener
*listener
,
481 MemoryRegionSection
*section
,
484 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
491 r
= kvm_section_update_flags(kml
, section
);
497 static void kvm_log_stop(MemoryListener
*listener
,
498 MemoryRegionSection
*section
,
501 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
508 r
= kvm_section_update_flags(kml
, section
);
514 /* get kvm's dirty pages bitmap and update qemu's */
515 static int kvm_get_dirty_pages_log_range(MemoryRegionSection
*section
,
516 unsigned long *bitmap
)
518 ram_addr_t start
= section
->offset_within_region
+
519 memory_region_get_ram_addr(section
->mr
);
520 ram_addr_t pages
= int128_get64(section
->size
) / qemu_real_host_page_size
;
522 cpu_physical_memory_set_dirty_lebitmap(bitmap
, start
, pages
);
526 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
528 /* Allocate the dirty bitmap for a slot */
529 static void kvm_memslot_init_dirty_bitmap(KVMSlot
*mem
)
532 * XXX bad kernel interface alert
533 * For dirty bitmap, kernel allocates array of size aligned to
534 * bits-per-long. But for case when the kernel is 64bits and
535 * the userspace is 32bits, userspace can't align to the same
536 * bits-per-long, since sizeof(long) is different between kernel
537 * and user space. This way, userspace will provide buffer which
538 * may be 4 bytes less than the kernel will use, resulting in
539 * userspace memory corruption (which is not detectable by valgrind
540 * too, in most cases).
541 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
542 * a hope that sizeof(long) won't become >8 any time soon.
544 hwaddr bitmap_size
= ALIGN(((mem
->memory_size
) >> TARGET_PAGE_BITS
),
545 /*HOST_LONG_BITS*/ 64) / 8;
546 mem
->dirty_bmap
= g_malloc0(bitmap_size
);
550 * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
552 * This function will first try to fetch dirty bitmap from the kernel,
553 * and then updates qemu's dirty bitmap.
555 * NOTE: caller must be with kml->slots_lock held.
557 * @kml: the KVM memory listener object
558 * @section: the memory section to sync the dirty bitmap with
560 static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener
*kml
,
561 MemoryRegionSection
*section
)
563 KVMState
*s
= kvm_state
;
564 struct kvm_dirty_log d
= {};
566 hwaddr start_addr
, size
;
567 hwaddr slot_size
, slot_offset
= 0;
570 size
= kvm_align_section(section
, &start_addr
);
572 MemoryRegionSection subsection
= *section
;
574 slot_size
= MIN(kvm_max_slot_size
, size
);
575 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
577 /* We don't have a slot if we want to trap every access. */
581 if (!mem
->dirty_bmap
) {
582 /* Allocate on the first log_sync, once and for all */
583 kvm_memslot_init_dirty_bitmap(mem
);
586 d
.dirty_bitmap
= mem
->dirty_bmap
;
587 d
.slot
= mem
->slot
| (kml
->as_id
<< 16);
588 if (kvm_vm_ioctl(s
, KVM_GET_DIRTY_LOG
, &d
) == -1) {
589 DPRINTF("ioctl failed %d\n", errno
);
594 subsection
.offset_within_region
+= slot_offset
;
595 subsection
.size
= int128_make64(slot_size
);
596 kvm_get_dirty_pages_log_range(&subsection
, d
.dirty_bitmap
);
598 slot_offset
+= slot_size
;
599 start_addr
+= slot_size
;
606 /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
607 #define KVM_CLEAR_LOG_SHIFT 6
608 #define KVM_CLEAR_LOG_ALIGN (qemu_real_host_page_size << KVM_CLEAR_LOG_SHIFT)
609 #define KVM_CLEAR_LOG_MASK (-KVM_CLEAR_LOG_ALIGN)
611 static int kvm_log_clear_one_slot(KVMSlot
*mem
, int as_id
, uint64_t start
,
614 KVMState
*s
= kvm_state
;
615 uint64_t end
, bmap_start
, start_delta
, bmap_npages
;
616 struct kvm_clear_dirty_log d
;
617 unsigned long *bmap_clear
= NULL
, psize
= qemu_real_host_page_size
;
621 * We need to extend either the start or the size or both to
622 * satisfy the KVM interface requirement. Firstly, do the start
623 * page alignment on 64 host pages
625 bmap_start
= start
& KVM_CLEAR_LOG_MASK
;
626 start_delta
= start
- bmap_start
;
630 * The kernel interface has restriction on the size too, that either:
632 * (1) the size is 64 host pages aligned (just like the start), or
633 * (2) the size fills up until the end of the KVM memslot.
635 bmap_npages
= DIV_ROUND_UP(size
+ start_delta
, KVM_CLEAR_LOG_ALIGN
)
636 << KVM_CLEAR_LOG_SHIFT
;
637 end
= mem
->memory_size
/ psize
;
638 if (bmap_npages
> end
- bmap_start
) {
639 bmap_npages
= end
- bmap_start
;
641 start_delta
/= psize
;
644 * Prepare the bitmap to clear dirty bits. Here we must guarantee
645 * that we won't clear any unknown dirty bits otherwise we might
646 * accidentally clear some set bits which are not yet synced from
647 * the kernel into QEMU's bitmap, then we'll lose track of the
648 * guest modifications upon those pages (which can directly lead
649 * to guest data loss or panic after migration).
651 * Layout of the KVMSlot.dirty_bmap:
653 * |<-------- bmap_npages -----------..>|
656 * |----------------|-------------|------------------|------------|
659 * start bmap_start (start) end
660 * of memslot of memslot
662 * [1] bmap_npages can be aligned to either 64 pages or the end of slot
665 assert(bmap_start
% BITS_PER_LONG
== 0);
666 /* We should never do log_clear before log_sync */
667 assert(mem
->dirty_bmap
);
669 /* Slow path - we need to manipulate a temp bitmap */
670 bmap_clear
= bitmap_new(bmap_npages
);
671 bitmap_copy_with_src_offset(bmap_clear
, mem
->dirty_bmap
,
672 bmap_start
, start_delta
+ size
/ psize
);
674 * We need to fill the holes at start because that was not
675 * specified by the caller and we extended the bitmap only for
678 bitmap_clear(bmap_clear
, 0, start_delta
);
679 d
.dirty_bitmap
= bmap_clear
;
681 /* Fast path - start address aligns well with BITS_PER_LONG */
682 d
.dirty_bitmap
= mem
->dirty_bmap
+ BIT_WORD(bmap_start
);
685 d
.first_page
= bmap_start
;
686 /* It should never overflow. If it happens, say something */
687 assert(bmap_npages
<= UINT32_MAX
);
688 d
.num_pages
= bmap_npages
;
689 d
.slot
= mem
->slot
| (as_id
<< 16);
691 if (kvm_vm_ioctl(s
, KVM_CLEAR_DIRTY_LOG
, &d
) == -1) {
693 error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
694 "start=0x%"PRIx64
", size=0x%"PRIx32
", errno=%d",
695 __func__
, d
.slot
, (uint64_t)d
.first_page
,
696 (uint32_t)d
.num_pages
, ret
);
699 trace_kvm_clear_dirty_log(d
.slot
, d
.first_page
, d
.num_pages
);
703 * After we have updated the remote dirty bitmap, we update the
704 * cached bitmap as well for the memslot, then if another user
705 * clears the same region we know we shouldn't clear it again on
706 * the remote otherwise it's data loss as well.
708 bitmap_clear(mem
->dirty_bmap
, bmap_start
+ start_delta
,
710 /* This handles the NULL case well */
717 * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
719 * NOTE: this will be a no-op if we haven't enabled manual dirty log
720 * protection in the host kernel because in that case this operation
721 * will be done within log_sync().
723 * @kml: the kvm memory listener
724 * @section: the memory range to clear dirty bitmap
726 static int kvm_physical_log_clear(KVMMemoryListener
*kml
,
727 MemoryRegionSection
*section
)
729 KVMState
*s
= kvm_state
;
730 uint64_t start
, size
, offset
, count
;
734 if (!s
->manual_dirty_log_protect
) {
735 /* No need to do explicit clear */
739 start
= section
->offset_within_address_space
;
740 size
= int128_get64(section
->size
);
743 /* Nothing more we can do... */
749 for (i
= 0; i
< s
->nr_slots
; i
++) {
750 mem
= &kml
->slots
[i
];
751 /* Discard slots that are empty or do not overlap the section */
752 if (!mem
->memory_size
||
753 mem
->start_addr
> start
+ size
- 1 ||
754 start
> mem
->start_addr
+ mem
->memory_size
- 1) {
758 if (start
>= mem
->start_addr
) {
759 /* The slot starts before section or is aligned to it. */
760 offset
= start
- mem
->start_addr
;
761 count
= MIN(mem
->memory_size
- offset
, size
);
763 /* The slot starts after section. */
765 count
= MIN(mem
->memory_size
, size
- (mem
->start_addr
- start
));
767 ret
= kvm_log_clear_one_slot(mem
, kml
->as_id
, offset
, count
);
773 kvm_slots_unlock(kml
);
778 static void kvm_coalesce_mmio_region(MemoryListener
*listener
,
779 MemoryRegionSection
*secion
,
780 hwaddr start
, hwaddr size
)
782 KVMState
*s
= kvm_state
;
784 if (s
->coalesced_mmio
) {
785 struct kvm_coalesced_mmio_zone zone
;
791 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
795 static void kvm_uncoalesce_mmio_region(MemoryListener
*listener
,
796 MemoryRegionSection
*secion
,
797 hwaddr start
, hwaddr size
)
799 KVMState
*s
= kvm_state
;
801 if (s
->coalesced_mmio
) {
802 struct kvm_coalesced_mmio_zone zone
;
808 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
812 static void kvm_coalesce_pio_add(MemoryListener
*listener
,
813 MemoryRegionSection
*section
,
814 hwaddr start
, hwaddr size
)
816 KVMState
*s
= kvm_state
;
818 if (s
->coalesced_pio
) {
819 struct kvm_coalesced_mmio_zone zone
;
825 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
829 static void kvm_coalesce_pio_del(MemoryListener
*listener
,
830 MemoryRegionSection
*section
,
831 hwaddr start
, hwaddr size
)
833 KVMState
*s
= kvm_state
;
835 if (s
->coalesced_pio
) {
836 struct kvm_coalesced_mmio_zone zone
;
842 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
846 static MemoryListener kvm_coalesced_pio_listener
= {
847 .coalesced_io_add
= kvm_coalesce_pio_add
,
848 .coalesced_io_del
= kvm_coalesce_pio_del
,
851 int kvm_check_extension(KVMState
*s
, unsigned int extension
)
855 ret
= kvm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
863 int kvm_vm_check_extension(KVMState
*s
, unsigned int extension
)
867 ret
= kvm_vm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
869 /* VM wide version not implemented, use global one instead */
870 ret
= kvm_check_extension(s
, extension
);
876 static uint32_t adjust_ioeventfd_endianness(uint32_t val
, uint32_t size
)
878 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
879 /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
880 * endianness, but the memory core hands them in target endianness.
881 * For example, PPC is always treated as big-endian even if running
882 * on KVM and on PPC64LE. Correct here.
896 static int kvm_set_ioeventfd_mmio(int fd
, hwaddr addr
, uint32_t val
,
897 bool assign
, uint32_t size
, bool datamatch
)
900 struct kvm_ioeventfd iofd
= {
901 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
908 trace_kvm_set_ioeventfd_mmio(fd
, (uint64_t)addr
, val
, assign
, size
,
910 if (!kvm_enabled()) {
915 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
918 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
921 ret
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &iofd
);
930 static int kvm_set_ioeventfd_pio(int fd
, uint16_t addr
, uint16_t val
,
931 bool assign
, uint32_t size
, bool datamatch
)
933 struct kvm_ioeventfd kick
= {
934 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
936 .flags
= KVM_IOEVENTFD_FLAG_PIO
,
941 trace_kvm_set_ioeventfd_pio(fd
, addr
, val
, assign
, size
, datamatch
);
942 if (!kvm_enabled()) {
946 kick
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
949 kick
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
951 r
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &kick
);
959 static int kvm_check_many_ioeventfds(void)
961 /* Userspace can use ioeventfd for io notification. This requires a host
962 * that supports eventfd(2) and an I/O thread; since eventfd does not
963 * support SIGIO it cannot interrupt the vcpu.
965 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
966 * can avoid creating too many ioeventfds.
968 #if defined(CONFIG_EVENTFD)
971 for (i
= 0; i
< ARRAY_SIZE(ioeventfds
); i
++) {
972 ioeventfds
[i
] = eventfd(0, EFD_CLOEXEC
);
973 if (ioeventfds
[i
] < 0) {
976 ret
= kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, true, 2, true);
978 close(ioeventfds
[i
]);
983 /* Decide whether many devices are supported or not */
984 ret
= i
== ARRAY_SIZE(ioeventfds
);
987 kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, false, 2, true);
988 close(ioeventfds
[i
]);
996 static const KVMCapabilityInfo
*
997 kvm_check_extension_list(KVMState
*s
, const KVMCapabilityInfo
*list
)
1000 if (!kvm_check_extension(s
, list
->value
)) {
1008 void kvm_set_max_memslot_size(hwaddr max_slot_size
)
1011 ROUND_UP(max_slot_size
, qemu_real_host_page_size
) == max_slot_size
1013 kvm_max_slot_size
= max_slot_size
;
1016 static void kvm_set_phys_mem(KVMMemoryListener
*kml
,
1017 MemoryRegionSection
*section
, bool add
)
1021 MemoryRegion
*mr
= section
->mr
;
1022 bool writeable
= !mr
->readonly
&& !mr
->rom_device
;
1023 hwaddr start_addr
, size
, slot_size
;
1026 if (!memory_region_is_ram(mr
)) {
1027 if (writeable
|| !kvm_readonly_mem_allowed
) {
1029 } else if (!mr
->romd_mode
) {
1030 /* If the memory device is not in romd_mode, then we actually want
1031 * to remove the kvm memory slot so all accesses will trap. */
1036 size
= kvm_align_section(section
, &start_addr
);
1041 /* use aligned delta to align the ram address */
1042 ram
= memory_region_get_ram_ptr(mr
) + section
->offset_within_region
+
1043 (start_addr
- section
->offset_within_address_space
);
1045 kvm_slots_lock(kml
);
1049 slot_size
= MIN(kvm_max_slot_size
, size
);
1050 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
1054 if (mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
1055 kvm_physical_sync_dirty_bitmap(kml
, section
);
1058 /* unregister the slot */
1059 g_free(mem
->dirty_bmap
);
1060 mem
->dirty_bmap
= NULL
;
1061 mem
->memory_size
= 0;
1063 err
= kvm_set_user_memory_region(kml
, mem
, false);
1065 fprintf(stderr
, "%s: error unregistering slot: %s\n",
1066 __func__
, strerror(-err
));
1069 start_addr
+= slot_size
;
1075 /* register the new slot */
1077 slot_size
= MIN(kvm_max_slot_size
, size
);
1078 mem
= kvm_alloc_slot(kml
);
1079 mem
->memory_size
= slot_size
;
1080 mem
->start_addr
= start_addr
;
1082 mem
->flags
= kvm_mem_flags(mr
);
1084 if (mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
1086 * Reallocate the bmap; it means it doesn't disappear in
1087 * middle of a migrate.
1089 kvm_memslot_init_dirty_bitmap(mem
);
1091 err
= kvm_set_user_memory_region(kml
, mem
, true);
1093 fprintf(stderr
, "%s: error registering slot: %s\n", __func__
,
1097 start_addr
+= slot_size
;
1103 kvm_slots_unlock(kml
);
1106 static void kvm_region_add(MemoryListener
*listener
,
1107 MemoryRegionSection
*section
)
1109 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1111 memory_region_ref(section
->mr
);
1112 kvm_set_phys_mem(kml
, section
, true);
1115 static void kvm_region_del(MemoryListener
*listener
,
1116 MemoryRegionSection
*section
)
1118 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1120 kvm_set_phys_mem(kml
, section
, false);
1121 memory_region_unref(section
->mr
);
1124 static void kvm_log_sync(MemoryListener
*listener
,
1125 MemoryRegionSection
*section
)
1127 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1130 kvm_slots_lock(kml
);
1131 r
= kvm_physical_sync_dirty_bitmap(kml
, section
);
1132 kvm_slots_unlock(kml
);
1138 static void kvm_log_clear(MemoryListener
*listener
,
1139 MemoryRegionSection
*section
)
1141 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1144 r
= kvm_physical_log_clear(kml
, section
);
1146 error_report_once("%s: kvm log clear failed: mr=%s "
1147 "offset=%"HWADDR_PRIx
" size=%"PRIx64
, __func__
,
1148 section
->mr
->name
, section
->offset_within_region
,
1149 int128_get64(section
->size
));
1154 static void kvm_mem_ioeventfd_add(MemoryListener
*listener
,
1155 MemoryRegionSection
*section
,
1156 bool match_data
, uint64_t data
,
1159 int fd
= event_notifier_get_fd(e
);
1162 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
1163 data
, true, int128_get64(section
->size
),
1166 fprintf(stderr
, "%s: error adding ioeventfd: %s (%d)\n",
1167 __func__
, strerror(-r
), -r
);
1172 static void kvm_mem_ioeventfd_del(MemoryListener
*listener
,
1173 MemoryRegionSection
*section
,
1174 bool match_data
, uint64_t data
,
1177 int fd
= event_notifier_get_fd(e
);
1180 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
1181 data
, false, int128_get64(section
->size
),
1184 fprintf(stderr
, "%s: error deleting ioeventfd: %s (%d)\n",
1185 __func__
, strerror(-r
), -r
);
1190 static void kvm_io_ioeventfd_add(MemoryListener
*listener
,
1191 MemoryRegionSection
*section
,
1192 bool match_data
, uint64_t data
,
1195 int fd
= event_notifier_get_fd(e
);
1198 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
1199 data
, true, int128_get64(section
->size
),
1202 fprintf(stderr
, "%s: error adding ioeventfd: %s (%d)\n",
1203 __func__
, strerror(-r
), -r
);
1208 static void kvm_io_ioeventfd_del(MemoryListener
*listener
,
1209 MemoryRegionSection
*section
,
1210 bool match_data
, uint64_t data
,
1214 int fd
= event_notifier_get_fd(e
);
1217 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
1218 data
, false, int128_get64(section
->size
),
1221 fprintf(stderr
, "%s: error deleting ioeventfd: %s (%d)\n",
1222 __func__
, strerror(-r
), -r
);
1227 void kvm_memory_listener_register(KVMState
*s
, KVMMemoryListener
*kml
,
1228 AddressSpace
*as
, int as_id
)
1232 qemu_mutex_init(&kml
->slots_lock
);
1233 kml
->slots
= g_malloc0(s
->nr_slots
* sizeof(KVMSlot
));
1236 for (i
= 0; i
< s
->nr_slots
; i
++) {
1237 kml
->slots
[i
].slot
= i
;
1240 kml
->listener
.region_add
= kvm_region_add
;
1241 kml
->listener
.region_del
= kvm_region_del
;
1242 kml
->listener
.log_start
= kvm_log_start
;
1243 kml
->listener
.log_stop
= kvm_log_stop
;
1244 kml
->listener
.log_sync
= kvm_log_sync
;
1245 kml
->listener
.log_clear
= kvm_log_clear
;
1246 kml
->listener
.priority
= 10;
1248 memory_listener_register(&kml
->listener
, as
);
1250 for (i
= 0; i
< s
->nr_as
; ++i
) {
1259 static MemoryListener kvm_io_listener
= {
1260 .eventfd_add
= kvm_io_ioeventfd_add
,
1261 .eventfd_del
= kvm_io_ioeventfd_del
,
1265 int kvm_set_irq(KVMState
*s
, int irq
, int level
)
1267 struct kvm_irq_level event
;
1270 assert(kvm_async_interrupts_enabled());
1272 event
.level
= level
;
1274 ret
= kvm_vm_ioctl(s
, s
->irq_set_ioctl
, &event
);
1276 perror("kvm_set_irq");
1280 return (s
->irq_set_ioctl
== KVM_IRQ_LINE
) ? 1 : event
.status
;
1283 #ifdef KVM_CAP_IRQ_ROUTING
1284 typedef struct KVMMSIRoute
{
1285 struct kvm_irq_routing_entry kroute
;
1286 QTAILQ_ENTRY(KVMMSIRoute
) entry
;
1289 static void set_gsi(KVMState
*s
, unsigned int gsi
)
1291 set_bit(gsi
, s
->used_gsi_bitmap
);
1294 static void clear_gsi(KVMState
*s
, unsigned int gsi
)
1296 clear_bit(gsi
, s
->used_gsi_bitmap
);
1299 void kvm_init_irq_routing(KVMState
*s
)
1303 gsi_count
= kvm_check_extension(s
, KVM_CAP_IRQ_ROUTING
) - 1;
1304 if (gsi_count
> 0) {
1305 /* Round up so we can search ints using ffs */
1306 s
->used_gsi_bitmap
= bitmap_new(gsi_count
);
1307 s
->gsi_count
= gsi_count
;
1310 s
->irq_routes
= g_malloc0(sizeof(*s
->irq_routes
));
1311 s
->nr_allocated_irq_routes
= 0;
1313 if (!kvm_direct_msi_allowed
) {
1314 for (i
= 0; i
< KVM_MSI_HASHTAB_SIZE
; i
++) {
1315 QTAILQ_INIT(&s
->msi_hashtab
[i
]);
1319 kvm_arch_init_irq_routing(s
);
1322 void kvm_irqchip_commit_routes(KVMState
*s
)
1326 if (kvm_gsi_direct_mapping()) {
1330 if (!kvm_gsi_routing_enabled()) {
1334 s
->irq_routes
->flags
= 0;
1335 trace_kvm_irqchip_commit_routes();
1336 ret
= kvm_vm_ioctl(s
, KVM_SET_GSI_ROUTING
, s
->irq_routes
);
1340 static void kvm_add_routing_entry(KVMState
*s
,
1341 struct kvm_irq_routing_entry
*entry
)
1343 struct kvm_irq_routing_entry
*new;
1346 if (s
->irq_routes
->nr
== s
->nr_allocated_irq_routes
) {
1347 n
= s
->nr_allocated_irq_routes
* 2;
1351 size
= sizeof(struct kvm_irq_routing
);
1352 size
+= n
* sizeof(*new);
1353 s
->irq_routes
= g_realloc(s
->irq_routes
, size
);
1354 s
->nr_allocated_irq_routes
= n
;
1356 n
= s
->irq_routes
->nr
++;
1357 new = &s
->irq_routes
->entries
[n
];
1361 set_gsi(s
, entry
->gsi
);
1364 static int kvm_update_routing_entry(KVMState
*s
,
1365 struct kvm_irq_routing_entry
*new_entry
)
1367 struct kvm_irq_routing_entry
*entry
;
1370 for (n
= 0; n
< s
->irq_routes
->nr
; n
++) {
1371 entry
= &s
->irq_routes
->entries
[n
];
1372 if (entry
->gsi
!= new_entry
->gsi
) {
1376 if(!memcmp(entry
, new_entry
, sizeof *entry
)) {
1380 *entry
= *new_entry
;
1388 void kvm_irqchip_add_irq_route(KVMState
*s
, int irq
, int irqchip
, int pin
)
1390 struct kvm_irq_routing_entry e
= {};
1392 assert(pin
< s
->gsi_count
);
1395 e
.type
= KVM_IRQ_ROUTING_IRQCHIP
;
1397 e
.u
.irqchip
.irqchip
= irqchip
;
1398 e
.u
.irqchip
.pin
= pin
;
1399 kvm_add_routing_entry(s
, &e
);
1402 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
1404 struct kvm_irq_routing_entry
*e
;
1407 if (kvm_gsi_direct_mapping()) {
1411 for (i
= 0; i
< s
->irq_routes
->nr
; i
++) {
1412 e
= &s
->irq_routes
->entries
[i
];
1413 if (e
->gsi
== virq
) {
1414 s
->irq_routes
->nr
--;
1415 *e
= s
->irq_routes
->entries
[s
->irq_routes
->nr
];
1419 kvm_arch_release_virq_post(virq
);
1420 trace_kvm_irqchip_release_virq(virq
);
1423 void kvm_irqchip_add_change_notifier(Notifier
*n
)
1425 notifier_list_add(&kvm_irqchip_change_notifiers
, n
);
1428 void kvm_irqchip_remove_change_notifier(Notifier
*n
)
1433 void kvm_irqchip_change_notify(void)
1435 notifier_list_notify(&kvm_irqchip_change_notifiers
, NULL
);
1438 static unsigned int kvm_hash_msi(uint32_t data
)
1440 /* This is optimized for IA32 MSI layout. However, no other arch shall
1441 * repeat the mistake of not providing a direct MSI injection API. */
1445 static void kvm_flush_dynamic_msi_routes(KVMState
*s
)
1447 KVMMSIRoute
*route
, *next
;
1450 for (hash
= 0; hash
< KVM_MSI_HASHTAB_SIZE
; hash
++) {
1451 QTAILQ_FOREACH_SAFE(route
, &s
->msi_hashtab
[hash
], entry
, next
) {
1452 kvm_irqchip_release_virq(s
, route
->kroute
.gsi
);
1453 QTAILQ_REMOVE(&s
->msi_hashtab
[hash
], route
, entry
);
1459 static int kvm_irqchip_get_virq(KVMState
*s
)
1464 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1465 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1466 * number can succeed even though a new route entry cannot be added.
1467 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1469 if (!kvm_direct_msi_allowed
&& s
->irq_routes
->nr
== s
->gsi_count
) {
1470 kvm_flush_dynamic_msi_routes(s
);
1473 /* Return the lowest unused GSI in the bitmap */
1474 next_virq
= find_first_zero_bit(s
->used_gsi_bitmap
, s
->gsi_count
);
1475 if (next_virq
>= s
->gsi_count
) {
1482 static KVMMSIRoute
*kvm_lookup_msi_route(KVMState
*s
, MSIMessage msg
)
1484 unsigned int hash
= kvm_hash_msi(msg
.data
);
1487 QTAILQ_FOREACH(route
, &s
->msi_hashtab
[hash
], entry
) {
1488 if (route
->kroute
.u
.msi
.address_lo
== (uint32_t)msg
.address
&&
1489 route
->kroute
.u
.msi
.address_hi
== (msg
.address
>> 32) &&
1490 route
->kroute
.u
.msi
.data
== le32_to_cpu(msg
.data
)) {
1497 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1502 if (kvm_direct_msi_allowed
) {
1503 msi
.address_lo
= (uint32_t)msg
.address
;
1504 msi
.address_hi
= msg
.address
>> 32;
1505 msi
.data
= le32_to_cpu(msg
.data
);
1507 memset(msi
.pad
, 0, sizeof(msi
.pad
));
1509 return kvm_vm_ioctl(s
, KVM_SIGNAL_MSI
, &msi
);
1512 route
= kvm_lookup_msi_route(s
, msg
);
1516 virq
= kvm_irqchip_get_virq(s
);
1521 route
= g_malloc0(sizeof(KVMMSIRoute
));
1522 route
->kroute
.gsi
= virq
;
1523 route
->kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1524 route
->kroute
.flags
= 0;
1525 route
->kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1526 route
->kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1527 route
->kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1529 kvm_add_routing_entry(s
, &route
->kroute
);
1530 kvm_irqchip_commit_routes(s
);
1532 QTAILQ_INSERT_TAIL(&s
->msi_hashtab
[kvm_hash_msi(msg
.data
)], route
,
1536 assert(route
->kroute
.type
== KVM_IRQ_ROUTING_MSI
);
1538 return kvm_set_irq(s
, route
->kroute
.gsi
, 1);
1541 int kvm_irqchip_add_msi_route(KVMState
*s
, int vector
, PCIDevice
*dev
)
1543 struct kvm_irq_routing_entry kroute
= {};
1545 MSIMessage msg
= {0, 0};
1547 if (pci_available
&& dev
) {
1548 msg
= pci_get_msi_message(dev
, vector
);
1551 if (kvm_gsi_direct_mapping()) {
1552 return kvm_arch_msi_data_to_gsi(msg
.data
);
1555 if (!kvm_gsi_routing_enabled()) {
1559 virq
= kvm_irqchip_get_virq(s
);
1565 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1567 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1568 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1569 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1570 if (pci_available
&& kvm_msi_devid_required()) {
1571 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1572 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1574 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1575 kvm_irqchip_release_virq(s
, virq
);
1579 trace_kvm_irqchip_add_msi_route(dev
? dev
->name
: (char *)"N/A",
1582 kvm_add_routing_entry(s
, &kroute
);
1583 kvm_arch_add_msi_route_post(&kroute
, vector
, dev
);
1584 kvm_irqchip_commit_routes(s
);
1589 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
,
1592 struct kvm_irq_routing_entry kroute
= {};
1594 if (kvm_gsi_direct_mapping()) {
1598 if (!kvm_irqchip_in_kernel()) {
1603 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1605 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1606 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1607 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1608 if (pci_available
&& kvm_msi_devid_required()) {
1609 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1610 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1612 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1616 trace_kvm_irqchip_update_msi_route(virq
);
1618 return kvm_update_routing_entry(s
, &kroute
);
1621 static int kvm_irqchip_assign_irqfd(KVMState
*s
, int fd
, int rfd
, int virq
,
1624 struct kvm_irqfd irqfd
= {
1627 .flags
= assign
? 0 : KVM_IRQFD_FLAG_DEASSIGN
,
1631 irqfd
.flags
|= KVM_IRQFD_FLAG_RESAMPLE
;
1632 irqfd
.resamplefd
= rfd
;
1635 if (!kvm_irqfds_enabled()) {
1639 return kvm_vm_ioctl(s
, KVM_IRQFD
, &irqfd
);
1642 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
1644 struct kvm_irq_routing_entry kroute
= {};
1647 if (!kvm_gsi_routing_enabled()) {
1651 virq
= kvm_irqchip_get_virq(s
);
1657 kroute
.type
= KVM_IRQ_ROUTING_S390_ADAPTER
;
1659 kroute
.u
.adapter
.summary_addr
= adapter
->summary_addr
;
1660 kroute
.u
.adapter
.ind_addr
= adapter
->ind_addr
;
1661 kroute
.u
.adapter
.summary_offset
= adapter
->summary_offset
;
1662 kroute
.u
.adapter
.ind_offset
= adapter
->ind_offset
;
1663 kroute
.u
.adapter
.adapter_id
= adapter
->adapter_id
;
1665 kvm_add_routing_entry(s
, &kroute
);
1670 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
1672 struct kvm_irq_routing_entry kroute
= {};
1675 if (!kvm_gsi_routing_enabled()) {
1678 if (!kvm_check_extension(s
, KVM_CAP_HYPERV_SYNIC
)) {
1681 virq
= kvm_irqchip_get_virq(s
);
1687 kroute
.type
= KVM_IRQ_ROUTING_HV_SINT
;
1689 kroute
.u
.hv_sint
.vcpu
= vcpu
;
1690 kroute
.u
.hv_sint
.sint
= sint
;
1692 kvm_add_routing_entry(s
, &kroute
);
1693 kvm_irqchip_commit_routes(s
);
1698 #else /* !KVM_CAP_IRQ_ROUTING */
1700 void kvm_init_irq_routing(KVMState
*s
)
1704 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
1708 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1713 int kvm_irqchip_add_msi_route(KVMState
*s
, int vector
, PCIDevice
*dev
)
1718 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
1723 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
1728 static int kvm_irqchip_assign_irqfd(KVMState
*s
, int fd
, int virq
, bool assign
)
1733 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
)
1737 #endif /* !KVM_CAP_IRQ_ROUTING */
1739 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
1740 EventNotifier
*rn
, int virq
)
1742 return kvm_irqchip_assign_irqfd(s
, event_notifier_get_fd(n
),
1743 rn
? event_notifier_get_fd(rn
) : -1, virq
, true);
1746 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
1749 return kvm_irqchip_assign_irqfd(s
, event_notifier_get_fd(n
), -1, virq
,
1753 int kvm_irqchip_add_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
1754 EventNotifier
*rn
, qemu_irq irq
)
1757 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
1762 return kvm_irqchip_add_irqfd_notifier_gsi(s
, n
, rn
, GPOINTER_TO_INT(gsi
));
1765 int kvm_irqchip_remove_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
1769 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
1774 return kvm_irqchip_remove_irqfd_notifier_gsi(s
, n
, GPOINTER_TO_INT(gsi
));
1777 void kvm_irqchip_set_qemuirq_gsi(KVMState
*s
, qemu_irq irq
, int gsi
)
1779 g_hash_table_insert(s
->gsimap
, irq
, GINT_TO_POINTER(gsi
));
1782 static void kvm_irqchip_create(KVMState
*s
)
1786 if (kvm_check_extension(s
, KVM_CAP_IRQCHIP
)) {
1788 } else if (kvm_check_extension(s
, KVM_CAP_S390_IRQCHIP
)) {
1789 ret
= kvm_vm_enable_cap(s
, KVM_CAP_S390_IRQCHIP
, 0);
1791 fprintf(stderr
, "Enable kernel irqchip failed: %s\n", strerror(-ret
));
1798 /* First probe and see if there's a arch-specific hook to create the
1799 * in-kernel irqchip for us */
1800 ret
= kvm_arch_irqchip_create(s
);
1802 if (s
->kernel_irqchip_split
) {
1803 perror("Split IRQ chip mode not supported.");
1806 ret
= kvm_vm_ioctl(s
, KVM_CREATE_IRQCHIP
);
1810 fprintf(stderr
, "Create kernel irqchip failed: %s\n", strerror(-ret
));
1814 kvm_kernel_irqchip
= true;
1815 /* If we have an in-kernel IRQ chip then we must have asynchronous
1816 * interrupt delivery (though the reverse is not necessarily true)
1818 kvm_async_interrupts_allowed
= true;
1819 kvm_halt_in_kernel_allowed
= true;
1821 kvm_init_irq_routing(s
);
1823 s
->gsimap
= g_hash_table_new(g_direct_hash
, g_direct_equal
);
1826 /* Find number of supported CPUs using the recommended
1827 * procedure from the kernel API documentation to cope with
1828 * older kernels that may be missing capabilities.
1830 static int kvm_recommended_vcpus(KVMState
*s
)
1832 int ret
= kvm_vm_check_extension(s
, KVM_CAP_NR_VCPUS
);
1833 return (ret
) ? ret
: 4;
1836 static int kvm_max_vcpus(KVMState
*s
)
1838 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPUS
);
1839 return (ret
) ? ret
: kvm_recommended_vcpus(s
);
1842 static int kvm_max_vcpu_id(KVMState
*s
)
1844 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPU_ID
);
1845 return (ret
) ? ret
: kvm_max_vcpus(s
);
1848 bool kvm_vcpu_id_is_valid(int vcpu_id
)
1850 KVMState
*s
= KVM_STATE(current_machine
->accelerator
);
1851 return vcpu_id
>= 0 && vcpu_id
< kvm_max_vcpu_id(s
);
1854 static int kvm_init(MachineState
*ms
)
1856 MachineClass
*mc
= MACHINE_GET_CLASS(ms
);
1857 static const char upgrade_note
[] =
1858 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1859 "(see http://sourceforge.net/projects/kvm).\n";
1864 { "SMP", ms
->smp
.cpus
},
1865 { "hotpluggable", ms
->smp
.max_cpus
},
1868 int soft_vcpus_limit
, hard_vcpus_limit
;
1870 const KVMCapabilityInfo
*missing_cap
;
1873 const char *kvm_type
;
1875 s
= KVM_STATE(ms
->accelerator
);
1878 * On systems where the kernel can support different base page
1879 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1880 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1881 * page size for the system though.
1883 assert(TARGET_PAGE_SIZE
<= qemu_real_host_page_size
);
1887 #ifdef KVM_CAP_SET_GUEST_DEBUG
1888 QTAILQ_INIT(&s
->kvm_sw_breakpoints
);
1890 QLIST_INIT(&s
->kvm_parked_vcpus
);
1892 s
->fd
= qemu_open("/dev/kvm", O_RDWR
);
1894 fprintf(stderr
, "Could not access KVM kernel module: %m\n");
1899 ret
= kvm_ioctl(s
, KVM_GET_API_VERSION
, 0);
1900 if (ret
< KVM_API_VERSION
) {
1904 fprintf(stderr
, "kvm version too old\n");
1908 if (ret
> KVM_API_VERSION
) {
1910 fprintf(stderr
, "kvm version not supported\n");
1914 kvm_immediate_exit
= kvm_check_extension(s
, KVM_CAP_IMMEDIATE_EXIT
);
1915 s
->nr_slots
= kvm_check_extension(s
, KVM_CAP_NR_MEMSLOTS
);
1917 /* If unspecified, use the default value */
1922 s
->nr_as
= kvm_check_extension(s
, KVM_CAP_MULTI_ADDRESS_SPACE
);
1923 if (s
->nr_as
<= 1) {
1926 s
->as
= g_new0(struct KVMAs
, s
->nr_as
);
1928 kvm_type
= qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1930 type
= mc
->kvm_type(ms
, kvm_type
);
1931 } else if (kvm_type
) {
1933 fprintf(stderr
, "Invalid argument kvm-type=%s\n", kvm_type
);
1938 ret
= kvm_ioctl(s
, KVM_CREATE_VM
, type
);
1939 } while (ret
== -EINTR
);
1942 fprintf(stderr
, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret
,
1946 if (ret
== -EINVAL
) {
1948 "Host kernel setup problem detected. Please verify:\n");
1949 fprintf(stderr
, "- for kernels supporting the switch_amode or"
1950 " user_mode parameters, whether\n");
1952 " user space is running in primary address space\n");
1954 "- for kernels supporting the vm.allocate_pgste sysctl, "
1955 "whether it is enabled\n");
1963 /* check the vcpu limits */
1964 soft_vcpus_limit
= kvm_recommended_vcpus(s
);
1965 hard_vcpus_limit
= kvm_max_vcpus(s
);
1968 if (nc
->num
> soft_vcpus_limit
) {
1969 warn_report("Number of %s cpus requested (%d) exceeds "
1970 "the recommended cpus supported by KVM (%d)",
1971 nc
->name
, nc
->num
, soft_vcpus_limit
);
1973 if (nc
->num
> hard_vcpus_limit
) {
1974 fprintf(stderr
, "Number of %s cpus requested (%d) exceeds "
1975 "the maximum cpus supported by KVM (%d)\n",
1976 nc
->name
, nc
->num
, hard_vcpus_limit
);
1983 missing_cap
= kvm_check_extension_list(s
, kvm_required_capabilites
);
1986 kvm_check_extension_list(s
, kvm_arch_required_capabilities
);
1990 fprintf(stderr
, "kvm does not support %s\n%s",
1991 missing_cap
->name
, upgrade_note
);
1995 s
->coalesced_mmio
= kvm_check_extension(s
, KVM_CAP_COALESCED_MMIO
);
1996 s
->coalesced_pio
= s
->coalesced_mmio
&&
1997 kvm_check_extension(s
, KVM_CAP_COALESCED_PIO
);
1999 s
->manual_dirty_log_protect
=
2000 kvm_check_extension(s
, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2
);
2001 if (s
->manual_dirty_log_protect
) {
2002 ret
= kvm_vm_enable_cap(s
, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2
, 0, 1);
2004 warn_report("Trying to enable KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 "
2005 "but failed. Falling back to the legacy mode. ");
2006 s
->manual_dirty_log_protect
= false;
2010 #ifdef KVM_CAP_VCPU_EVENTS
2011 s
->vcpu_events
= kvm_check_extension(s
, KVM_CAP_VCPU_EVENTS
);
2014 s
->robust_singlestep
=
2015 kvm_check_extension(s
, KVM_CAP_X86_ROBUST_SINGLESTEP
);
2017 #ifdef KVM_CAP_DEBUGREGS
2018 s
->debugregs
= kvm_check_extension(s
, KVM_CAP_DEBUGREGS
);
2021 s
->max_nested_state_len
= kvm_check_extension(s
, KVM_CAP_NESTED_STATE
);
2023 #ifdef KVM_CAP_IRQ_ROUTING
2024 kvm_direct_msi_allowed
= (kvm_check_extension(s
, KVM_CAP_SIGNAL_MSI
) > 0);
2027 s
->intx_set_mask
= kvm_check_extension(s
, KVM_CAP_PCI_2_3
);
2029 s
->irq_set_ioctl
= KVM_IRQ_LINE
;
2030 if (kvm_check_extension(s
, KVM_CAP_IRQ_INJECT_STATUS
)) {
2031 s
->irq_set_ioctl
= KVM_IRQ_LINE_STATUS
;
2034 kvm_readonly_mem_allowed
=
2035 (kvm_check_extension(s
, KVM_CAP_READONLY_MEM
) > 0);
2037 kvm_eventfds_allowed
=
2038 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD
) > 0);
2040 kvm_irqfds_allowed
=
2041 (kvm_check_extension(s
, KVM_CAP_IRQFD
) > 0);
2043 kvm_resamplefds_allowed
=
2044 (kvm_check_extension(s
, KVM_CAP_IRQFD_RESAMPLE
) > 0);
2046 kvm_vm_attributes_allowed
=
2047 (kvm_check_extension(s
, KVM_CAP_VM_ATTRIBUTES
) > 0);
2049 kvm_ioeventfd_any_length_allowed
=
2050 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD_ANY_LENGTH
) > 0);
2055 * if memory encryption object is specified then initialize the memory
2056 * encryption context.
2058 if (ms
->memory_encryption
) {
2059 kvm_state
->memcrypt_handle
= sev_guest_init(ms
->memory_encryption
);
2060 if (!kvm_state
->memcrypt_handle
) {
2065 kvm_state
->memcrypt_encrypt_data
= sev_encrypt_data
;
2068 ret
= kvm_arch_init(ms
, s
);
2073 if (s
->kernel_irqchip_allowed
) {
2074 kvm_irqchip_create(s
);
2077 if (kvm_eventfds_allowed
) {
2078 s
->memory_listener
.listener
.eventfd_add
= kvm_mem_ioeventfd_add
;
2079 s
->memory_listener
.listener
.eventfd_del
= kvm_mem_ioeventfd_del
;
2081 s
->memory_listener
.listener
.coalesced_io_add
= kvm_coalesce_mmio_region
;
2082 s
->memory_listener
.listener
.coalesced_io_del
= kvm_uncoalesce_mmio_region
;
2084 kvm_memory_listener_register(s
, &s
->memory_listener
,
2085 &address_space_memory
, 0);
2086 memory_listener_register(&kvm_io_listener
,
2088 memory_listener_register(&kvm_coalesced_pio_listener
,
2091 s
->many_ioeventfds
= kvm_check_many_ioeventfds();
2093 s
->sync_mmu
= !!kvm_vm_check_extension(kvm_state
, KVM_CAP_SYNC_MMU
);
2095 qemu_balloon_inhibit(true);
2108 g_free(s
->memory_listener
.slots
);
2113 void kvm_set_sigmask_len(KVMState
*s
, unsigned int sigmask_len
)
2115 s
->sigmask_len
= sigmask_len
;
2118 static void kvm_handle_io(uint16_t port
, MemTxAttrs attrs
, void *data
, int direction
,
2119 int size
, uint32_t count
)
2122 uint8_t *ptr
= data
;
2124 for (i
= 0; i
< count
; i
++) {
2125 address_space_rw(&address_space_io
, port
, attrs
,
2127 direction
== KVM_EXIT_IO_OUT
);
2132 static int kvm_handle_internal_error(CPUState
*cpu
, struct kvm_run
*run
)
2134 fprintf(stderr
, "KVM internal error. Suberror: %d\n",
2135 run
->internal
.suberror
);
2137 if (kvm_check_extension(kvm_state
, KVM_CAP_INTERNAL_ERROR_DATA
)) {
2140 for (i
= 0; i
< run
->internal
.ndata
; ++i
) {
2141 fprintf(stderr
, "extra data[%d]: %"PRIx64
"\n",
2142 i
, (uint64_t)run
->internal
.data
[i
]);
2145 if (run
->internal
.suberror
== KVM_INTERNAL_ERROR_EMULATION
) {
2146 fprintf(stderr
, "emulation failure\n");
2147 if (!kvm_arch_stop_on_emulation_error(cpu
)) {
2148 cpu_dump_state(cpu
, stderr
, CPU_DUMP_CODE
);
2149 return EXCP_INTERRUPT
;
2152 /* FIXME: Should trigger a qmp message to let management know
2153 * something went wrong.
2158 void kvm_flush_coalesced_mmio_buffer(void)
2160 KVMState
*s
= kvm_state
;
2162 if (s
->coalesced_flush_in_progress
) {
2166 s
->coalesced_flush_in_progress
= true;
2168 if (s
->coalesced_mmio_ring
) {
2169 struct kvm_coalesced_mmio_ring
*ring
= s
->coalesced_mmio_ring
;
2170 while (ring
->first
!= ring
->last
) {
2171 struct kvm_coalesced_mmio
*ent
;
2173 ent
= &ring
->coalesced_mmio
[ring
->first
];
2175 if (ent
->pio
== 1) {
2176 address_space_rw(&address_space_io
, ent
->phys_addr
,
2177 MEMTXATTRS_UNSPECIFIED
, ent
->data
,
2180 cpu_physical_memory_write(ent
->phys_addr
, ent
->data
, ent
->len
);
2183 ring
->first
= (ring
->first
+ 1) % KVM_COALESCED_MMIO_MAX
;
2187 s
->coalesced_flush_in_progress
= false;
2190 static void do_kvm_cpu_synchronize_state(CPUState
*cpu
, run_on_cpu_data arg
)
2192 if (!cpu
->vcpu_dirty
) {
2193 kvm_arch_get_registers(cpu
);
2194 cpu
->vcpu_dirty
= true;
2198 void kvm_cpu_synchronize_state(CPUState
*cpu
)
2200 if (!cpu
->vcpu_dirty
) {
2201 run_on_cpu(cpu
, do_kvm_cpu_synchronize_state
, RUN_ON_CPU_NULL
);
2205 static void do_kvm_cpu_synchronize_post_reset(CPUState
*cpu
, run_on_cpu_data arg
)
2207 kvm_arch_put_registers(cpu
, KVM_PUT_RESET_STATE
);
2208 cpu
->vcpu_dirty
= false;
2211 void kvm_cpu_synchronize_post_reset(CPUState
*cpu
)
2213 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_reset
, RUN_ON_CPU_NULL
);
2216 static void do_kvm_cpu_synchronize_post_init(CPUState
*cpu
, run_on_cpu_data arg
)
2218 kvm_arch_put_registers(cpu
, KVM_PUT_FULL_STATE
);
2219 cpu
->vcpu_dirty
= false;
2222 void kvm_cpu_synchronize_post_init(CPUState
*cpu
)
2224 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_init
, RUN_ON_CPU_NULL
);
2227 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
, run_on_cpu_data arg
)
2229 cpu
->vcpu_dirty
= true;
2232 void kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
)
2234 run_on_cpu(cpu
, do_kvm_cpu_synchronize_pre_loadvm
, RUN_ON_CPU_NULL
);
2237 #ifdef KVM_HAVE_MCE_INJECTION
2238 static __thread
void *pending_sigbus_addr
;
2239 static __thread
int pending_sigbus_code
;
2240 static __thread
bool have_sigbus_pending
;
2243 static void kvm_cpu_kick(CPUState
*cpu
)
2245 atomic_set(&cpu
->kvm_run
->immediate_exit
, 1);
2248 static void kvm_cpu_kick_self(void)
2250 if (kvm_immediate_exit
) {
2251 kvm_cpu_kick(current_cpu
);
2253 qemu_cpu_kick_self();
2257 static void kvm_eat_signals(CPUState
*cpu
)
2259 struct timespec ts
= { 0, 0 };
2265 if (kvm_immediate_exit
) {
2266 atomic_set(&cpu
->kvm_run
->immediate_exit
, 0);
2267 /* Write kvm_run->immediate_exit before the cpu->exit_request
2268 * write in kvm_cpu_exec.
2274 sigemptyset(&waitset
);
2275 sigaddset(&waitset
, SIG_IPI
);
2278 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
2279 if (r
== -1 && !(errno
== EAGAIN
|| errno
== EINTR
)) {
2280 perror("sigtimedwait");
2284 r
= sigpending(&chkset
);
2286 perror("sigpending");
2289 } while (sigismember(&chkset
, SIG_IPI
));
2292 int kvm_cpu_exec(CPUState
*cpu
)
2294 struct kvm_run
*run
= cpu
->kvm_run
;
2297 DPRINTF("kvm_cpu_exec()\n");
2299 if (kvm_arch_process_async_events(cpu
)) {
2300 atomic_set(&cpu
->exit_request
, 0);
2304 qemu_mutex_unlock_iothread();
2305 cpu_exec_start(cpu
);
2310 if (cpu
->vcpu_dirty
) {
2311 kvm_arch_put_registers(cpu
, KVM_PUT_RUNTIME_STATE
);
2312 cpu
->vcpu_dirty
= false;
2315 kvm_arch_pre_run(cpu
, run
);
2316 if (atomic_read(&cpu
->exit_request
)) {
2317 DPRINTF("interrupt exit requested\n");
2319 * KVM requires us to reenter the kernel after IO exits to complete
2320 * instruction emulation. This self-signal will ensure that we
2323 kvm_cpu_kick_self();
2326 /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2327 * Matching barrier in kvm_eat_signals.
2331 run_ret
= kvm_vcpu_ioctl(cpu
, KVM_RUN
, 0);
2333 attrs
= kvm_arch_post_run(cpu
, run
);
2335 #ifdef KVM_HAVE_MCE_INJECTION
2336 if (unlikely(have_sigbus_pending
)) {
2337 qemu_mutex_lock_iothread();
2338 kvm_arch_on_sigbus_vcpu(cpu
, pending_sigbus_code
,
2339 pending_sigbus_addr
);
2340 have_sigbus_pending
= false;
2341 qemu_mutex_unlock_iothread();
2346 if (run_ret
== -EINTR
|| run_ret
== -EAGAIN
) {
2347 DPRINTF("io window exit\n");
2348 kvm_eat_signals(cpu
);
2349 ret
= EXCP_INTERRUPT
;
2352 fprintf(stderr
, "error: kvm run failed %s\n",
2353 strerror(-run_ret
));
2355 if (run_ret
== -EBUSY
) {
2357 "This is probably because your SMT is enabled.\n"
2358 "VCPU can only run on primary threads with all "
2359 "secondary threads offline.\n");
2366 trace_kvm_run_exit(cpu
->cpu_index
, run
->exit_reason
);
2367 switch (run
->exit_reason
) {
2369 DPRINTF("handle_io\n");
2370 /* Called outside BQL */
2371 kvm_handle_io(run
->io
.port
, attrs
,
2372 (uint8_t *)run
+ run
->io
.data_offset
,
2379 DPRINTF("handle_mmio\n");
2380 /* Called outside BQL */
2381 address_space_rw(&address_space_memory
,
2382 run
->mmio
.phys_addr
, attrs
,
2385 run
->mmio
.is_write
);
2388 case KVM_EXIT_IRQ_WINDOW_OPEN
:
2389 DPRINTF("irq_window_open\n");
2390 ret
= EXCP_INTERRUPT
;
2392 case KVM_EXIT_SHUTDOWN
:
2393 DPRINTF("shutdown\n");
2394 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
2395 ret
= EXCP_INTERRUPT
;
2397 case KVM_EXIT_UNKNOWN
:
2398 fprintf(stderr
, "KVM: unknown exit, hardware reason %" PRIx64
"\n",
2399 (uint64_t)run
->hw
.hardware_exit_reason
);
2402 case KVM_EXIT_INTERNAL_ERROR
:
2403 ret
= kvm_handle_internal_error(cpu
, run
);
2405 case KVM_EXIT_SYSTEM_EVENT
:
2406 switch (run
->system_event
.type
) {
2407 case KVM_SYSTEM_EVENT_SHUTDOWN
:
2408 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN
);
2409 ret
= EXCP_INTERRUPT
;
2411 case KVM_SYSTEM_EVENT_RESET
:
2412 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
2413 ret
= EXCP_INTERRUPT
;
2415 case KVM_SYSTEM_EVENT_CRASH
:
2416 kvm_cpu_synchronize_state(cpu
);
2417 qemu_mutex_lock_iothread();
2418 qemu_system_guest_panicked(cpu_get_crash_info(cpu
));
2419 qemu_mutex_unlock_iothread();
2423 DPRINTF("kvm_arch_handle_exit\n");
2424 ret
= kvm_arch_handle_exit(cpu
, run
);
2429 DPRINTF("kvm_arch_handle_exit\n");
2430 ret
= kvm_arch_handle_exit(cpu
, run
);
2436 qemu_mutex_lock_iothread();
2439 cpu_dump_state(cpu
, stderr
, CPU_DUMP_CODE
);
2440 vm_stop(RUN_STATE_INTERNAL_ERROR
);
2443 atomic_set(&cpu
->exit_request
, 0);
2447 int kvm_ioctl(KVMState
*s
, int type
, ...)
2454 arg
= va_arg(ap
, void *);
2457 trace_kvm_ioctl(type
, arg
);
2458 ret
= ioctl(s
->fd
, type
, arg
);
2465 int kvm_vm_ioctl(KVMState
*s
, int type
, ...)
2472 arg
= va_arg(ap
, void *);
2475 trace_kvm_vm_ioctl(type
, arg
);
2476 ret
= ioctl(s
->vmfd
, type
, arg
);
2483 int kvm_vcpu_ioctl(CPUState
*cpu
, int type
, ...)
2490 arg
= va_arg(ap
, void *);
2493 trace_kvm_vcpu_ioctl(cpu
->cpu_index
, type
, arg
);
2494 ret
= ioctl(cpu
->kvm_fd
, type
, arg
);
2501 int kvm_device_ioctl(int fd
, int type
, ...)
2508 arg
= va_arg(ap
, void *);
2511 trace_kvm_device_ioctl(fd
, type
, arg
);
2512 ret
= ioctl(fd
, type
, arg
);
2519 int kvm_vm_check_attr(KVMState
*s
, uint32_t group
, uint64_t attr
)
2522 struct kvm_device_attr attribute
= {
2527 if (!kvm_vm_attributes_allowed
) {
2531 ret
= kvm_vm_ioctl(s
, KVM_HAS_DEVICE_ATTR
, &attribute
);
2532 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2536 int kvm_device_check_attr(int dev_fd
, uint32_t group
, uint64_t attr
)
2538 struct kvm_device_attr attribute
= {
2544 return kvm_device_ioctl(dev_fd
, KVM_HAS_DEVICE_ATTR
, &attribute
) ? 0 : 1;
2547 int kvm_device_access(int fd
, int group
, uint64_t attr
,
2548 void *val
, bool write
, Error
**errp
)
2550 struct kvm_device_attr kvmattr
;
2554 kvmattr
.group
= group
;
2555 kvmattr
.attr
= attr
;
2556 kvmattr
.addr
= (uintptr_t)val
;
2558 err
= kvm_device_ioctl(fd
,
2559 write
? KVM_SET_DEVICE_ATTR
: KVM_GET_DEVICE_ATTR
,
2562 error_setg_errno(errp
, -err
,
2563 "KVM_%s_DEVICE_ATTR failed: Group %d "
2564 "attr 0x%016" PRIx64
,
2565 write
? "SET" : "GET", group
, attr
);
2570 bool kvm_has_sync_mmu(void)
2572 return kvm_state
->sync_mmu
;
2575 int kvm_has_vcpu_events(void)
2577 return kvm_state
->vcpu_events
;
2580 int kvm_has_robust_singlestep(void)
2582 return kvm_state
->robust_singlestep
;
2585 int kvm_has_debugregs(void)
2587 return kvm_state
->debugregs
;
2590 int kvm_max_nested_state_length(void)
2592 return kvm_state
->max_nested_state_len
;
2595 int kvm_has_many_ioeventfds(void)
2597 if (!kvm_enabled()) {
2600 return kvm_state
->many_ioeventfds
;
2603 int kvm_has_gsi_routing(void)
2605 #ifdef KVM_CAP_IRQ_ROUTING
2606 return kvm_check_extension(kvm_state
, KVM_CAP_IRQ_ROUTING
);
2612 int kvm_has_intx_set_mask(void)
2614 return kvm_state
->intx_set_mask
;
2617 bool kvm_arm_supports_user_irq(void)
2619 return kvm_check_extension(kvm_state
, KVM_CAP_ARM_USER_IRQ
);
2622 #ifdef KVM_CAP_SET_GUEST_DEBUG
2623 struct kvm_sw_breakpoint
*kvm_find_sw_breakpoint(CPUState
*cpu
,
2626 struct kvm_sw_breakpoint
*bp
;
2628 QTAILQ_FOREACH(bp
, &cpu
->kvm_state
->kvm_sw_breakpoints
, entry
) {
2636 int kvm_sw_breakpoints_active(CPUState
*cpu
)
2638 return !QTAILQ_EMPTY(&cpu
->kvm_state
->kvm_sw_breakpoints
);
2641 struct kvm_set_guest_debug_data
{
2642 struct kvm_guest_debug dbg
;
2646 static void kvm_invoke_set_guest_debug(CPUState
*cpu
, run_on_cpu_data data
)
2648 struct kvm_set_guest_debug_data
*dbg_data
=
2649 (struct kvm_set_guest_debug_data
*) data
.host_ptr
;
2651 dbg_data
->err
= kvm_vcpu_ioctl(cpu
, KVM_SET_GUEST_DEBUG
,
2655 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
2657 struct kvm_set_guest_debug_data data
;
2659 data
.dbg
.control
= reinject_trap
;
2661 if (cpu
->singlestep_enabled
) {
2662 data
.dbg
.control
|= KVM_GUESTDBG_ENABLE
| KVM_GUESTDBG_SINGLESTEP
;
2664 kvm_arch_update_guest_debug(cpu
, &data
.dbg
);
2666 run_on_cpu(cpu
, kvm_invoke_set_guest_debug
,
2667 RUN_ON_CPU_HOST_PTR(&data
));
2671 int kvm_insert_breakpoint(CPUState
*cpu
, target_ulong addr
,
2672 target_ulong len
, int type
)
2674 struct kvm_sw_breakpoint
*bp
;
2677 if (type
== GDB_BREAKPOINT_SW
) {
2678 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
2684 bp
= g_malloc(sizeof(struct kvm_sw_breakpoint
));
2687 err
= kvm_arch_insert_sw_breakpoint(cpu
, bp
);
2693 QTAILQ_INSERT_HEAD(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
2695 err
= kvm_arch_insert_hw_breakpoint(addr
, len
, type
);
2702 err
= kvm_update_guest_debug(cpu
, 0);
2710 int kvm_remove_breakpoint(CPUState
*cpu
, target_ulong addr
,
2711 target_ulong len
, int type
)
2713 struct kvm_sw_breakpoint
*bp
;
2716 if (type
== GDB_BREAKPOINT_SW
) {
2717 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
2722 if (bp
->use_count
> 1) {
2727 err
= kvm_arch_remove_sw_breakpoint(cpu
, bp
);
2732 QTAILQ_REMOVE(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
2735 err
= kvm_arch_remove_hw_breakpoint(addr
, len
, type
);
2742 err
= kvm_update_guest_debug(cpu
, 0);
2750 void kvm_remove_all_breakpoints(CPUState
*cpu
)
2752 struct kvm_sw_breakpoint
*bp
, *next
;
2753 KVMState
*s
= cpu
->kvm_state
;
2756 QTAILQ_FOREACH_SAFE(bp
, &s
->kvm_sw_breakpoints
, entry
, next
) {
2757 if (kvm_arch_remove_sw_breakpoint(cpu
, bp
) != 0) {
2758 /* Try harder to find a CPU that currently sees the breakpoint. */
2759 CPU_FOREACH(tmpcpu
) {
2760 if (kvm_arch_remove_sw_breakpoint(tmpcpu
, bp
) == 0) {
2765 QTAILQ_REMOVE(&s
->kvm_sw_breakpoints
, bp
, entry
);
2768 kvm_arch_remove_all_hw_breakpoints();
2771 kvm_update_guest_debug(cpu
, 0);
2775 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2777 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
2782 int kvm_insert_breakpoint(CPUState
*cpu
, target_ulong addr
,
2783 target_ulong len
, int type
)
2788 int kvm_remove_breakpoint(CPUState
*cpu
, target_ulong addr
,
2789 target_ulong len
, int type
)
2794 void kvm_remove_all_breakpoints(CPUState
*cpu
)
2797 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2799 static int kvm_set_signal_mask(CPUState
*cpu
, const sigset_t
*sigset
)
2801 KVMState
*s
= kvm_state
;
2802 struct kvm_signal_mask
*sigmask
;
2805 sigmask
= g_malloc(sizeof(*sigmask
) + sizeof(*sigset
));
2807 sigmask
->len
= s
->sigmask_len
;
2808 memcpy(sigmask
->sigset
, sigset
, sizeof(*sigset
));
2809 r
= kvm_vcpu_ioctl(cpu
, KVM_SET_SIGNAL_MASK
, sigmask
);
2815 static void kvm_ipi_signal(int sig
)
2818 assert(kvm_immediate_exit
);
2819 kvm_cpu_kick(current_cpu
);
2823 void kvm_init_cpu_signals(CPUState
*cpu
)
2827 struct sigaction sigact
;
2829 memset(&sigact
, 0, sizeof(sigact
));
2830 sigact
.sa_handler
= kvm_ipi_signal
;
2831 sigaction(SIG_IPI
, &sigact
, NULL
);
2833 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
2834 #if defined KVM_HAVE_MCE_INJECTION
2835 sigdelset(&set
, SIGBUS
);
2836 pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
2838 sigdelset(&set
, SIG_IPI
);
2839 if (kvm_immediate_exit
) {
2840 r
= pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
2842 r
= kvm_set_signal_mask(cpu
, &set
);
2845 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(-r
));
2850 /* Called asynchronously in VCPU thread. */
2851 int kvm_on_sigbus_vcpu(CPUState
*cpu
, int code
, void *addr
)
2853 #ifdef KVM_HAVE_MCE_INJECTION
2854 if (have_sigbus_pending
) {
2857 have_sigbus_pending
= true;
2858 pending_sigbus_addr
= addr
;
2859 pending_sigbus_code
= code
;
2860 atomic_set(&cpu
->exit_request
, 1);
2867 /* Called synchronously (via signalfd) in main thread. */
2868 int kvm_on_sigbus(int code
, void *addr
)
2870 #ifdef KVM_HAVE_MCE_INJECTION
2871 /* Action required MCE kills the process if SIGBUS is blocked. Because
2872 * that's what happens in the I/O thread, where we handle MCE via signalfd,
2873 * we can only get action optional here.
2875 assert(code
!= BUS_MCEERR_AR
);
2876 kvm_arch_on_sigbus_vcpu(first_cpu
, code
, addr
);
2883 int kvm_create_device(KVMState
*s
, uint64_t type
, bool test
)
2886 struct kvm_create_device create_dev
;
2888 create_dev
.type
= type
;
2890 create_dev
.flags
= test
? KVM_CREATE_DEVICE_TEST
: 0;
2892 if (!kvm_check_extension(s
, KVM_CAP_DEVICE_CTRL
)) {
2896 ret
= kvm_vm_ioctl(s
, KVM_CREATE_DEVICE
, &create_dev
);
2901 return test
? 0 : create_dev
.fd
;
2904 bool kvm_device_supported(int vmfd
, uint64_t type
)
2906 struct kvm_create_device create_dev
= {
2909 .flags
= KVM_CREATE_DEVICE_TEST
,
2912 if (ioctl(vmfd
, KVM_CHECK_EXTENSION
, KVM_CAP_DEVICE_CTRL
) <= 0) {
2916 return (ioctl(vmfd
, KVM_CREATE_DEVICE
, &create_dev
) >= 0);
2919 int kvm_set_one_reg(CPUState
*cs
, uint64_t id
, void *source
)
2921 struct kvm_one_reg reg
;
2925 reg
.addr
= (uintptr_t) source
;
2926 r
= kvm_vcpu_ioctl(cs
, KVM_SET_ONE_REG
, ®
);
2928 trace_kvm_failed_reg_set(id
, strerror(-r
));
2933 int kvm_get_one_reg(CPUState
*cs
, uint64_t id
, void *target
)
2935 struct kvm_one_reg reg
;
2939 reg
.addr
= (uintptr_t) target
;
2940 r
= kvm_vcpu_ioctl(cs
, KVM_GET_ONE_REG
, ®
);
2942 trace_kvm_failed_reg_get(id
, strerror(-r
));
2947 static bool kvm_accel_has_memory(MachineState
*ms
, AddressSpace
*as
,
2948 hwaddr start_addr
, hwaddr size
)
2950 KVMState
*kvm
= KVM_STATE(ms
->accelerator
);
2953 for (i
= 0; i
< kvm
->nr_as
; ++i
) {
2954 if (kvm
->as
[i
].as
== as
&& kvm
->as
[i
].ml
) {
2955 size
= MIN(kvm_max_slot_size
, size
);
2956 return NULL
!= kvm_lookup_matching_slot(kvm
->as
[i
].ml
,
2964 static void kvm_get_kvm_shadow_mem(Object
*obj
, Visitor
*v
,
2965 const char *name
, void *opaque
,
2968 KVMState
*s
= KVM_STATE(obj
);
2969 int64_t value
= s
->kvm_shadow_mem
;
2971 visit_type_int(v
, name
, &value
, errp
);
2974 static void kvm_set_kvm_shadow_mem(Object
*obj
, Visitor
*v
,
2975 const char *name
, void *opaque
,
2978 KVMState
*s
= KVM_STATE(obj
);
2979 Error
*error
= NULL
;
2982 visit_type_int(v
, name
, &value
, &error
);
2984 error_propagate(errp
, error
);
2988 s
->kvm_shadow_mem
= value
;
2991 static void kvm_set_kernel_irqchip(Object
*obj
, Visitor
*v
,
2992 const char *name
, void *opaque
,
2996 KVMState
*s
= KVM_STATE(obj
);
2999 visit_type_OnOffSplit(v
, name
, &mode
, &err
);
3001 error_propagate(errp
, err
);
3005 case ON_OFF_SPLIT_ON
:
3006 s
->kernel_irqchip_allowed
= true;
3007 s
->kernel_irqchip_required
= true;
3008 s
->kernel_irqchip_split
= false;
3010 case ON_OFF_SPLIT_OFF
:
3011 s
->kernel_irqchip_allowed
= false;
3012 s
->kernel_irqchip_required
= false;
3013 s
->kernel_irqchip_split
= false;
3015 case ON_OFF_SPLIT_SPLIT
:
3016 s
->kernel_irqchip_allowed
= true;
3017 s
->kernel_irqchip_required
= true;
3018 s
->kernel_irqchip_split
= true;
3021 /* The value was checked in visit_type_OnOffSplit() above. If
3022 * we get here, then something is wrong in QEMU.
3029 bool kvm_kernel_irqchip_allowed(void)
3031 return kvm_state
->kernel_irqchip_allowed
;
3034 bool kvm_kernel_irqchip_required(void)
3036 return kvm_state
->kernel_irqchip_required
;
3039 bool kvm_kernel_irqchip_split(void)
3041 return kvm_state
->kernel_irqchip_split
;
3044 static void kvm_accel_instance_init(Object
*obj
)
3046 KVMState
*s
= KVM_STATE(obj
);
3048 s
->kvm_shadow_mem
= -1;
3051 static void kvm_accel_class_init(ObjectClass
*oc
, void *data
)
3053 AccelClass
*ac
= ACCEL_CLASS(oc
);
3055 ac
->init_machine
= kvm_init
;
3056 ac
->has_memory
= kvm_accel_has_memory
;
3057 ac
->allowed
= &kvm_allowed
;
3059 object_class_property_add(oc
, "kernel-irqchip", "on|off|split",
3060 NULL
, kvm_set_kernel_irqchip
,
3061 NULL
, NULL
, &error_abort
);
3062 object_class_property_set_description(oc
, "kernel-irqchip",
3063 "Configure KVM in-kernel irqchip", &error_abort
);
3065 object_class_property_add(oc
, "kvm-shadow-mem", "int",
3066 kvm_get_kvm_shadow_mem
, kvm_set_kvm_shadow_mem
,
3067 NULL
, NULL
, &error_abort
);
3068 object_class_property_set_description(oc
, "kvm-shadow-mem",
3069 "KVM shadow MMU size", &error_abort
);
3072 static const TypeInfo kvm_accel_type
= {
3073 .name
= TYPE_KVM_ACCEL
,
3074 .parent
= TYPE_ACCEL
,
3075 .instance_init
= kvm_accel_instance_init
,
3076 .class_init
= kvm_accel_class_init
,
3077 .instance_size
= sizeof(KVMState
),
3080 static void kvm_type_init(void)
3082 type_register_static(&kvm_accel_type
);
3085 type_init(kvm_type_init
);