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 "qapi/visitor.h"
43 #include "qapi/qapi-types-common.h"
44 #include "qapi/qapi-visit-common.h"
45 #include "sysemu/reset.h"
46 #include "qemu/guest-random.h"
47 #include "sysemu/hw_accel.h"
50 #include "hw/boards.h"
52 /* This check must be after config-host.h is included */
54 #include <sys/eventfd.h>
57 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
58 * need to use the real host PAGE_SIZE, as that's what KVM will use.
63 #define PAGE_SIZE qemu_real_host_page_size
68 #define DPRINTF(fmt, ...) \
69 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
71 #define DPRINTF(fmt, ...) \
75 #define KVM_MSI_HASHTAB_SIZE 256
77 struct KVMParkedVcpu
{
78 unsigned long vcpu_id
;
80 QLIST_ENTRY(KVMParkedVcpu
) node
;
85 AccelState parent_obj
;
92 struct kvm_coalesced_mmio_ring
*coalesced_mmio_ring
;
93 bool coalesced_flush_in_progress
;
95 int robust_singlestep
;
97 #ifdef KVM_CAP_SET_GUEST_DEBUG
98 QTAILQ_HEAD(, kvm_sw_breakpoint
) kvm_sw_breakpoints
;
100 int max_nested_state_len
;
104 bool kernel_irqchip_allowed
;
105 bool kernel_irqchip_required
;
106 OnOffAuto kernel_irqchip_split
;
108 uint64_t manual_dirty_log_protect
;
109 /* The man page (and posix) say ioctl numbers are signed int, but
110 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
111 * unsigned, and treating them as signed here can break things */
112 unsigned irq_set_ioctl
;
113 unsigned int sigmask_len
;
115 #ifdef KVM_CAP_IRQ_ROUTING
116 struct kvm_irq_routing
*irq_routes
;
117 int nr_allocated_irq_routes
;
118 unsigned long *used_gsi_bitmap
;
119 unsigned int gsi_count
;
120 QTAILQ_HEAD(, KVMMSIRoute
) msi_hashtab
[KVM_MSI_HASHTAB_SIZE
];
122 KVMMemoryListener memory_listener
;
123 QLIST_HEAD(, KVMParkedVcpu
) kvm_parked_vcpus
;
125 /* For "info mtree -f" to tell if an MR is registered in KVM */
128 KVMMemoryListener
*ml
;
134 bool kvm_kernel_irqchip
;
135 bool kvm_split_irqchip
;
136 bool kvm_async_interrupts_allowed
;
137 bool kvm_halt_in_kernel_allowed
;
138 bool kvm_eventfds_allowed
;
139 bool kvm_irqfds_allowed
;
140 bool kvm_resamplefds_allowed
;
141 bool kvm_msi_via_irqfd_allowed
;
142 bool kvm_gsi_routing_allowed
;
143 bool kvm_gsi_direct_mapping
;
145 bool kvm_readonly_mem_allowed
;
146 bool kvm_vm_attributes_allowed
;
147 bool kvm_direct_msi_allowed
;
148 bool kvm_ioeventfd_any_length_allowed
;
149 bool kvm_msi_use_devid
;
150 static bool kvm_immediate_exit
;
151 static hwaddr kvm_max_slot_size
= ~0;
153 static const KVMCapabilityInfo kvm_required_capabilites
[] = {
154 KVM_CAP_INFO(USER_MEMORY
),
155 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS
),
156 KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS
),
160 static NotifierList kvm_irqchip_change_notifiers
=
161 NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers
);
163 struct KVMResampleFd
{
165 EventNotifier
*resample_event
;
166 QLIST_ENTRY(KVMResampleFd
) node
;
168 typedef struct KVMResampleFd KVMResampleFd
;
171 * Only used with split irqchip where we need to do the resample fd
172 * kick for the kernel from userspace.
174 static QLIST_HEAD(, KVMResampleFd
) kvm_resample_fd_list
=
175 QLIST_HEAD_INITIALIZER(kvm_resample_fd_list
);
177 #define kvm_slots_lock(kml) qemu_mutex_lock(&(kml)->slots_lock)
178 #define kvm_slots_unlock(kml) qemu_mutex_unlock(&(kml)->slots_lock)
180 static inline void kvm_resample_fd_remove(int gsi
)
184 QLIST_FOREACH(rfd
, &kvm_resample_fd_list
, node
) {
185 if (rfd
->gsi
== gsi
) {
186 QLIST_REMOVE(rfd
, node
);
193 static inline void kvm_resample_fd_insert(int gsi
, EventNotifier
*event
)
195 KVMResampleFd
*rfd
= g_new0(KVMResampleFd
, 1);
198 rfd
->resample_event
= event
;
200 QLIST_INSERT_HEAD(&kvm_resample_fd_list
, rfd
, node
);
203 void kvm_resample_fd_notify(int gsi
)
207 QLIST_FOREACH(rfd
, &kvm_resample_fd_list
, node
) {
208 if (rfd
->gsi
== gsi
) {
209 event_notifier_set(rfd
->resample_event
);
210 trace_kvm_resample_fd_notify(gsi
);
216 int kvm_get_max_memslots(void)
218 KVMState
*s
= KVM_STATE(current_accel());
223 /* Called with KVMMemoryListener.slots_lock held */
224 static KVMSlot
*kvm_get_free_slot(KVMMemoryListener
*kml
)
226 KVMState
*s
= kvm_state
;
229 for (i
= 0; i
< s
->nr_slots
; i
++) {
230 if (kml
->slots
[i
].memory_size
== 0) {
231 return &kml
->slots
[i
];
238 bool kvm_has_free_slot(MachineState
*ms
)
240 KVMState
*s
= KVM_STATE(ms
->accelerator
);
242 KVMMemoryListener
*kml
= &s
->memory_listener
;
245 result
= !!kvm_get_free_slot(kml
);
246 kvm_slots_unlock(kml
);
251 /* Called with KVMMemoryListener.slots_lock held */
252 static KVMSlot
*kvm_alloc_slot(KVMMemoryListener
*kml
)
254 KVMSlot
*slot
= kvm_get_free_slot(kml
);
260 fprintf(stderr
, "%s: no free slot available\n", __func__
);
264 static KVMSlot
*kvm_lookup_matching_slot(KVMMemoryListener
*kml
,
268 KVMState
*s
= kvm_state
;
271 for (i
= 0; i
< s
->nr_slots
; i
++) {
272 KVMSlot
*mem
= &kml
->slots
[i
];
274 if (start_addr
== mem
->start_addr
&& size
== mem
->memory_size
) {
283 * Calculate and align the start address and the size of the section.
284 * Return the size. If the size is 0, the aligned section is empty.
286 static hwaddr
kvm_align_section(MemoryRegionSection
*section
,
289 hwaddr size
= int128_get64(section
->size
);
290 hwaddr delta
, aligned
;
292 /* kvm works in page size chunks, but the function may be called
293 with sub-page size and unaligned start address. Pad the start
294 address to next and truncate size to previous page boundary. */
295 aligned
= ROUND_UP(section
->offset_within_address_space
,
296 qemu_real_host_page_size
);
297 delta
= aligned
- section
->offset_within_address_space
;
303 return (size
- delta
) & qemu_real_host_page_mask
;
306 int kvm_physical_memory_addr_from_host(KVMState
*s
, void *ram
,
309 KVMMemoryListener
*kml
= &s
->memory_listener
;
313 for (i
= 0; i
< s
->nr_slots
; i
++) {
314 KVMSlot
*mem
= &kml
->slots
[i
];
316 if (ram
>= mem
->ram
&& ram
< mem
->ram
+ mem
->memory_size
) {
317 *phys_addr
= mem
->start_addr
+ (ram
- mem
->ram
);
322 kvm_slots_unlock(kml
);
327 static int kvm_set_user_memory_region(KVMMemoryListener
*kml
, KVMSlot
*slot
, bool new)
329 KVMState
*s
= kvm_state
;
330 struct kvm_userspace_memory_region mem
;
333 mem
.slot
= slot
->slot
| (kml
->as_id
<< 16);
334 mem
.guest_phys_addr
= slot
->start_addr
;
335 mem
.userspace_addr
= (unsigned long)slot
->ram
;
336 mem
.flags
= slot
->flags
;
338 if (slot
->memory_size
&& !new && (mem
.flags
^ slot
->old_flags
) & KVM_MEM_READONLY
) {
339 /* Set the slot size to 0 before setting the slot to the desired
340 * value. This is needed based on KVM commit 75d61fbc. */
342 ret
= kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
347 mem
.memory_size
= slot
->memory_size
;
348 ret
= kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
349 slot
->old_flags
= mem
.flags
;
351 trace_kvm_set_user_memory(mem
.slot
, mem
.flags
, mem
.guest_phys_addr
,
352 mem
.memory_size
, mem
.userspace_addr
, ret
);
354 error_report("%s: KVM_SET_USER_MEMORY_REGION failed, slot=%d,"
355 " start=0x%" PRIx64
", size=0x%" PRIx64
": %s",
356 __func__
, mem
.slot
, slot
->start_addr
,
357 (uint64_t)mem
.memory_size
, strerror(errno
));
362 static int do_kvm_destroy_vcpu(CPUState
*cpu
)
364 KVMState
*s
= kvm_state
;
366 struct KVMParkedVcpu
*vcpu
= NULL
;
369 DPRINTF("kvm_destroy_vcpu\n");
371 ret
= kvm_arch_destroy_vcpu(cpu
);
376 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
379 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
383 ret
= munmap(cpu
->kvm_run
, mmap_size
);
388 vcpu
= g_malloc0(sizeof(*vcpu
));
389 vcpu
->vcpu_id
= kvm_arch_vcpu_id(cpu
);
390 vcpu
->kvm_fd
= cpu
->kvm_fd
;
391 QLIST_INSERT_HEAD(&kvm_state
->kvm_parked_vcpus
, vcpu
, node
);
396 void kvm_destroy_vcpu(CPUState
*cpu
)
398 if (do_kvm_destroy_vcpu(cpu
) < 0) {
399 error_report("kvm_destroy_vcpu failed");
404 static int kvm_get_vcpu(KVMState
*s
, unsigned long vcpu_id
)
406 struct KVMParkedVcpu
*cpu
;
408 QLIST_FOREACH(cpu
, &s
->kvm_parked_vcpus
, node
) {
409 if (cpu
->vcpu_id
== vcpu_id
) {
412 QLIST_REMOVE(cpu
, node
);
413 kvm_fd
= cpu
->kvm_fd
;
419 return kvm_vm_ioctl(s
, KVM_CREATE_VCPU
, (void *)vcpu_id
);
422 int kvm_init_vcpu(CPUState
*cpu
, Error
**errp
)
424 KVMState
*s
= kvm_state
;
428 trace_kvm_init_vcpu(cpu
->cpu_index
, kvm_arch_vcpu_id(cpu
));
430 ret
= kvm_get_vcpu(s
, kvm_arch_vcpu_id(cpu
));
432 error_setg_errno(errp
, -ret
, "kvm_init_vcpu: kvm_get_vcpu failed (%lu)",
433 kvm_arch_vcpu_id(cpu
));
439 cpu
->vcpu_dirty
= true;
441 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
444 error_setg_errno(errp
, -mmap_size
,
445 "kvm_init_vcpu: KVM_GET_VCPU_MMAP_SIZE failed");
449 cpu
->kvm_run
= mmap(NULL
, mmap_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
451 if (cpu
->kvm_run
== MAP_FAILED
) {
453 error_setg_errno(errp
, ret
,
454 "kvm_init_vcpu: mmap'ing vcpu state failed (%lu)",
455 kvm_arch_vcpu_id(cpu
));
459 if (s
->coalesced_mmio
&& !s
->coalesced_mmio_ring
) {
460 s
->coalesced_mmio_ring
=
461 (void *)cpu
->kvm_run
+ s
->coalesced_mmio
* PAGE_SIZE
;
464 ret
= kvm_arch_init_vcpu(cpu
);
466 error_setg_errno(errp
, -ret
,
467 "kvm_init_vcpu: kvm_arch_init_vcpu failed (%lu)",
468 kvm_arch_vcpu_id(cpu
));
475 * dirty pages logging control
478 static int kvm_mem_flags(MemoryRegion
*mr
)
480 bool readonly
= mr
->readonly
|| memory_region_is_romd(mr
);
483 if (memory_region_get_dirty_log_mask(mr
) != 0) {
484 flags
|= KVM_MEM_LOG_DIRTY_PAGES
;
486 if (readonly
&& kvm_readonly_mem_allowed
) {
487 flags
|= KVM_MEM_READONLY
;
492 /* Called with KVMMemoryListener.slots_lock held */
493 static int kvm_slot_update_flags(KVMMemoryListener
*kml
, KVMSlot
*mem
,
496 mem
->flags
= kvm_mem_flags(mr
);
498 /* If nothing changed effectively, no need to issue ioctl */
499 if (mem
->flags
== mem
->old_flags
) {
503 return kvm_set_user_memory_region(kml
, mem
, false);
506 static int kvm_section_update_flags(KVMMemoryListener
*kml
,
507 MemoryRegionSection
*section
)
509 hwaddr start_addr
, size
, slot_size
;
513 size
= kvm_align_section(section
, &start_addr
);
520 while (size
&& !ret
) {
521 slot_size
= MIN(kvm_max_slot_size
, size
);
522 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
524 /* We don't have a slot if we want to trap every access. */
528 ret
= kvm_slot_update_flags(kml
, mem
, section
->mr
);
529 start_addr
+= slot_size
;
534 kvm_slots_unlock(kml
);
538 static void kvm_log_start(MemoryListener
*listener
,
539 MemoryRegionSection
*section
,
542 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
549 r
= kvm_section_update_flags(kml
, section
);
555 static void kvm_log_stop(MemoryListener
*listener
,
556 MemoryRegionSection
*section
,
559 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
566 r
= kvm_section_update_flags(kml
, section
);
572 /* get kvm's dirty pages bitmap and update qemu's */
573 static int kvm_get_dirty_pages_log_range(MemoryRegionSection
*section
,
574 unsigned long *bitmap
)
576 ram_addr_t start
= section
->offset_within_region
+
577 memory_region_get_ram_addr(section
->mr
);
578 ram_addr_t pages
= int128_get64(section
->size
) / qemu_real_host_page_size
;
580 cpu_physical_memory_set_dirty_lebitmap(bitmap
, start
, pages
);
584 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
586 /* Allocate the dirty bitmap for a slot */
587 static void kvm_memslot_init_dirty_bitmap(KVMSlot
*mem
)
590 * XXX bad kernel interface alert
591 * For dirty bitmap, kernel allocates array of size aligned to
592 * bits-per-long. But for case when the kernel is 64bits and
593 * the userspace is 32bits, userspace can't align to the same
594 * bits-per-long, since sizeof(long) is different between kernel
595 * and user space. This way, userspace will provide buffer which
596 * may be 4 bytes less than the kernel will use, resulting in
597 * userspace memory corruption (which is not detectable by valgrind
598 * too, in most cases).
599 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
600 * a hope that sizeof(long) won't become >8 any time soon.
602 * Note: the granule of kvm dirty log is qemu_real_host_page_size.
603 * And mem->memory_size is aligned to it (otherwise this mem can't
604 * be registered to KVM).
606 hwaddr bitmap_size
= ALIGN(mem
->memory_size
/ qemu_real_host_page_size
,
607 /*HOST_LONG_BITS*/ 64) / 8;
608 mem
->dirty_bmap
= g_malloc0(bitmap_size
);
612 * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
614 * This function will first try to fetch dirty bitmap from the kernel,
615 * and then updates qemu's dirty bitmap.
617 * NOTE: caller must be with kml->slots_lock held.
619 * @kml: the KVM memory listener object
620 * @section: the memory section to sync the dirty bitmap with
622 static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener
*kml
,
623 MemoryRegionSection
*section
)
625 KVMState
*s
= kvm_state
;
626 struct kvm_dirty_log d
= {};
628 hwaddr start_addr
, size
;
629 hwaddr slot_size
, slot_offset
= 0;
632 size
= kvm_align_section(section
, &start_addr
);
634 MemoryRegionSection subsection
= *section
;
636 slot_size
= MIN(kvm_max_slot_size
, size
);
637 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
639 /* We don't have a slot if we want to trap every access. */
643 if (!mem
->dirty_bmap
) {
644 /* Allocate on the first log_sync, once and for all */
645 kvm_memslot_init_dirty_bitmap(mem
);
648 d
.dirty_bitmap
= mem
->dirty_bmap
;
649 d
.slot
= mem
->slot
| (kml
->as_id
<< 16);
650 ret
= kvm_vm_ioctl(s
, KVM_GET_DIRTY_LOG
, &d
);
651 if (ret
== -ENOENT
) {
652 /* kernel does not have dirty bitmap in this slot */
654 } else if (ret
< 0) {
655 error_report("ioctl KVM_GET_DIRTY_LOG failed: %d", errno
);
658 subsection
.offset_within_region
+= slot_offset
;
659 subsection
.size
= int128_make64(slot_size
);
660 kvm_get_dirty_pages_log_range(&subsection
, d
.dirty_bitmap
);
663 slot_offset
+= slot_size
;
664 start_addr
+= slot_size
;
671 /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
672 #define KVM_CLEAR_LOG_SHIFT 6
673 #define KVM_CLEAR_LOG_ALIGN (qemu_real_host_page_size << KVM_CLEAR_LOG_SHIFT)
674 #define KVM_CLEAR_LOG_MASK (-KVM_CLEAR_LOG_ALIGN)
677 * As the granule of kvm dirty log is qemu_real_host_page_size,
678 * @start and @size are expected and restricted to align to it.
680 static int kvm_log_clear_one_slot(KVMSlot
*mem
, int as_id
, uint64_t start
,
683 KVMState
*s
= kvm_state
;
684 uint64_t end
, bmap_start
, start_delta
, bmap_npages
;
685 struct kvm_clear_dirty_log d
;
686 unsigned long *bmap_clear
= NULL
, psize
= qemu_real_host_page_size
;
689 /* Make sure start and size are qemu_real_host_page_size aligned */
690 assert(QEMU_IS_ALIGNED(start
| size
, psize
));
693 * We need to extend either the start or the size or both to
694 * satisfy the KVM interface requirement. Firstly, do the start
695 * page alignment on 64 host pages
697 bmap_start
= start
& KVM_CLEAR_LOG_MASK
;
698 start_delta
= start
- bmap_start
;
702 * The kernel interface has restriction on the size too, that either:
704 * (1) the size is 64 host pages aligned (just like the start), or
705 * (2) the size fills up until the end of the KVM memslot.
707 bmap_npages
= DIV_ROUND_UP(size
+ start_delta
, KVM_CLEAR_LOG_ALIGN
)
708 << KVM_CLEAR_LOG_SHIFT
;
709 end
= mem
->memory_size
/ psize
;
710 if (bmap_npages
> end
- bmap_start
) {
711 bmap_npages
= end
- bmap_start
;
713 start_delta
/= psize
;
716 * Prepare the bitmap to clear dirty bits. Here we must guarantee
717 * that we won't clear any unknown dirty bits otherwise we might
718 * accidentally clear some set bits which are not yet synced from
719 * the kernel into QEMU's bitmap, then we'll lose track of the
720 * guest modifications upon those pages (which can directly lead
721 * to guest data loss or panic after migration).
723 * Layout of the KVMSlot.dirty_bmap:
725 * |<-------- bmap_npages -----------..>|
728 * |----------------|-------------|------------------|------------|
731 * start bmap_start (start) end
732 * of memslot of memslot
734 * [1] bmap_npages can be aligned to either 64 pages or the end of slot
737 assert(bmap_start
% BITS_PER_LONG
== 0);
738 /* We should never do log_clear before log_sync */
739 assert(mem
->dirty_bmap
);
740 if (start_delta
|| bmap_npages
- size
/ psize
) {
741 /* Slow path - we need to manipulate a temp bitmap */
742 bmap_clear
= bitmap_new(bmap_npages
);
743 bitmap_copy_with_src_offset(bmap_clear
, mem
->dirty_bmap
,
744 bmap_start
, start_delta
+ size
/ psize
);
746 * We need to fill the holes at start because that was not
747 * specified by the caller and we extended the bitmap only for
750 bitmap_clear(bmap_clear
, 0, start_delta
);
751 d
.dirty_bitmap
= bmap_clear
;
754 * Fast path - both start and size align well with BITS_PER_LONG
755 * (or the end of memory slot)
757 d
.dirty_bitmap
= mem
->dirty_bmap
+ BIT_WORD(bmap_start
);
760 d
.first_page
= bmap_start
;
761 /* It should never overflow. If it happens, say something */
762 assert(bmap_npages
<= UINT32_MAX
);
763 d
.num_pages
= bmap_npages
;
764 d
.slot
= mem
->slot
| (as_id
<< 16);
766 ret
= kvm_vm_ioctl(s
, KVM_CLEAR_DIRTY_LOG
, &d
);
767 if (ret
< 0 && ret
!= -ENOENT
) {
768 error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
769 "start=0x%"PRIx64
", size=0x%"PRIx32
", errno=%d",
770 __func__
, d
.slot
, (uint64_t)d
.first_page
,
771 (uint32_t)d
.num_pages
, ret
);
774 trace_kvm_clear_dirty_log(d
.slot
, d
.first_page
, d
.num_pages
);
778 * After we have updated the remote dirty bitmap, we update the
779 * cached bitmap as well for the memslot, then if another user
780 * clears the same region we know we shouldn't clear it again on
781 * the remote otherwise it's data loss as well.
783 bitmap_clear(mem
->dirty_bmap
, bmap_start
+ start_delta
,
785 /* This handles the NULL case well */
792 * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
794 * NOTE: this will be a no-op if we haven't enabled manual dirty log
795 * protection in the host kernel because in that case this operation
796 * will be done within log_sync().
798 * @kml: the kvm memory listener
799 * @section: the memory range to clear dirty bitmap
801 static int kvm_physical_log_clear(KVMMemoryListener
*kml
,
802 MemoryRegionSection
*section
)
804 KVMState
*s
= kvm_state
;
805 uint64_t start
, size
, offset
, count
;
809 if (!s
->manual_dirty_log_protect
) {
810 /* No need to do explicit clear */
814 start
= section
->offset_within_address_space
;
815 size
= int128_get64(section
->size
);
818 /* Nothing more we can do... */
824 for (i
= 0; i
< s
->nr_slots
; i
++) {
825 mem
= &kml
->slots
[i
];
826 /* Discard slots that are empty or do not overlap the section */
827 if (!mem
->memory_size
||
828 mem
->start_addr
> start
+ size
- 1 ||
829 start
> mem
->start_addr
+ mem
->memory_size
- 1) {
833 if (start
>= mem
->start_addr
) {
834 /* The slot starts before section or is aligned to it. */
835 offset
= start
- mem
->start_addr
;
836 count
= MIN(mem
->memory_size
- offset
, size
);
838 /* The slot starts after section. */
840 count
= MIN(mem
->memory_size
, size
- (mem
->start_addr
- start
));
842 ret
= kvm_log_clear_one_slot(mem
, kml
->as_id
, offset
, count
);
848 kvm_slots_unlock(kml
);
853 static void kvm_coalesce_mmio_region(MemoryListener
*listener
,
854 MemoryRegionSection
*secion
,
855 hwaddr start
, hwaddr size
)
857 KVMState
*s
= kvm_state
;
859 if (s
->coalesced_mmio
) {
860 struct kvm_coalesced_mmio_zone zone
;
866 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
870 static void kvm_uncoalesce_mmio_region(MemoryListener
*listener
,
871 MemoryRegionSection
*secion
,
872 hwaddr start
, hwaddr size
)
874 KVMState
*s
= kvm_state
;
876 if (s
->coalesced_mmio
) {
877 struct kvm_coalesced_mmio_zone zone
;
883 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
887 static void kvm_coalesce_pio_add(MemoryListener
*listener
,
888 MemoryRegionSection
*section
,
889 hwaddr start
, hwaddr size
)
891 KVMState
*s
= kvm_state
;
893 if (s
->coalesced_pio
) {
894 struct kvm_coalesced_mmio_zone zone
;
900 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
904 static void kvm_coalesce_pio_del(MemoryListener
*listener
,
905 MemoryRegionSection
*section
,
906 hwaddr start
, hwaddr size
)
908 KVMState
*s
= kvm_state
;
910 if (s
->coalesced_pio
) {
911 struct kvm_coalesced_mmio_zone zone
;
917 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
921 static MemoryListener kvm_coalesced_pio_listener
= {
922 .coalesced_io_add
= kvm_coalesce_pio_add
,
923 .coalesced_io_del
= kvm_coalesce_pio_del
,
926 int kvm_check_extension(KVMState
*s
, unsigned int extension
)
930 ret
= kvm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
938 int kvm_vm_check_extension(KVMState
*s
, unsigned int extension
)
942 ret
= kvm_vm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
944 /* VM wide version not implemented, use global one instead */
945 ret
= kvm_check_extension(s
, extension
);
951 typedef struct HWPoisonPage
{
953 QLIST_ENTRY(HWPoisonPage
) list
;
956 static QLIST_HEAD(, HWPoisonPage
) hwpoison_page_list
=
957 QLIST_HEAD_INITIALIZER(hwpoison_page_list
);
959 static void kvm_unpoison_all(void *param
)
961 HWPoisonPage
*page
, *next_page
;
963 QLIST_FOREACH_SAFE(page
, &hwpoison_page_list
, list
, next_page
) {
964 QLIST_REMOVE(page
, list
);
965 qemu_ram_remap(page
->ram_addr
, TARGET_PAGE_SIZE
);
970 void kvm_hwpoison_page_add(ram_addr_t ram_addr
)
974 QLIST_FOREACH(page
, &hwpoison_page_list
, list
) {
975 if (page
->ram_addr
== ram_addr
) {
979 page
= g_new(HWPoisonPage
, 1);
980 page
->ram_addr
= ram_addr
;
981 QLIST_INSERT_HEAD(&hwpoison_page_list
, page
, list
);
984 static uint32_t adjust_ioeventfd_endianness(uint32_t val
, uint32_t size
)
986 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
987 /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
988 * endianness, but the memory core hands them in target endianness.
989 * For example, PPC is always treated as big-endian even if running
990 * on KVM and on PPC64LE. Correct here.
1004 static int kvm_set_ioeventfd_mmio(int fd
, hwaddr addr
, uint32_t val
,
1005 bool assign
, uint32_t size
, bool datamatch
)
1008 struct kvm_ioeventfd iofd
= {
1009 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
1016 trace_kvm_set_ioeventfd_mmio(fd
, (uint64_t)addr
, val
, assign
, size
,
1018 if (!kvm_enabled()) {
1023 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
1026 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
1029 ret
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &iofd
);
1038 static int kvm_set_ioeventfd_pio(int fd
, uint16_t addr
, uint16_t val
,
1039 bool assign
, uint32_t size
, bool datamatch
)
1041 struct kvm_ioeventfd kick
= {
1042 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
1044 .flags
= KVM_IOEVENTFD_FLAG_PIO
,
1049 trace_kvm_set_ioeventfd_pio(fd
, addr
, val
, assign
, size
, datamatch
);
1050 if (!kvm_enabled()) {
1054 kick
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
1057 kick
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
1059 r
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &kick
);
1067 static int kvm_check_many_ioeventfds(void)
1069 /* Userspace can use ioeventfd for io notification. This requires a host
1070 * that supports eventfd(2) and an I/O thread; since eventfd does not
1071 * support SIGIO it cannot interrupt the vcpu.
1073 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
1074 * can avoid creating too many ioeventfds.
1076 #if defined(CONFIG_EVENTFD)
1079 for (i
= 0; i
< ARRAY_SIZE(ioeventfds
); i
++) {
1080 ioeventfds
[i
] = eventfd(0, EFD_CLOEXEC
);
1081 if (ioeventfds
[i
] < 0) {
1084 ret
= kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, true, 2, true);
1086 close(ioeventfds
[i
]);
1091 /* Decide whether many devices are supported or not */
1092 ret
= i
== ARRAY_SIZE(ioeventfds
);
1095 kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, false, 2, true);
1096 close(ioeventfds
[i
]);
1104 static const KVMCapabilityInfo
*
1105 kvm_check_extension_list(KVMState
*s
, const KVMCapabilityInfo
*list
)
1107 while (list
->name
) {
1108 if (!kvm_check_extension(s
, list
->value
)) {
1116 void kvm_set_max_memslot_size(hwaddr max_slot_size
)
1119 ROUND_UP(max_slot_size
, qemu_real_host_page_size
) == max_slot_size
1121 kvm_max_slot_size
= max_slot_size
;
1124 static void kvm_set_phys_mem(KVMMemoryListener
*kml
,
1125 MemoryRegionSection
*section
, bool add
)
1129 MemoryRegion
*mr
= section
->mr
;
1130 bool writeable
= !mr
->readonly
&& !mr
->rom_device
;
1131 hwaddr start_addr
, size
, slot_size
;
1134 if (!memory_region_is_ram(mr
)) {
1135 if (writeable
|| !kvm_readonly_mem_allowed
) {
1137 } else if (!mr
->romd_mode
) {
1138 /* If the memory device is not in romd_mode, then we actually want
1139 * to remove the kvm memory slot so all accesses will trap. */
1144 size
= kvm_align_section(section
, &start_addr
);
1149 /* use aligned delta to align the ram address */
1150 ram
= memory_region_get_ram_ptr(mr
) + section
->offset_within_region
+
1151 (start_addr
- section
->offset_within_address_space
);
1153 kvm_slots_lock(kml
);
1157 slot_size
= MIN(kvm_max_slot_size
, size
);
1158 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
1162 if (mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
1163 kvm_physical_sync_dirty_bitmap(kml
, section
);
1166 /* unregister the slot */
1167 g_free(mem
->dirty_bmap
);
1168 mem
->dirty_bmap
= NULL
;
1169 mem
->memory_size
= 0;
1171 err
= kvm_set_user_memory_region(kml
, mem
, false);
1173 fprintf(stderr
, "%s: error unregistering slot: %s\n",
1174 __func__
, strerror(-err
));
1177 start_addr
+= slot_size
;
1183 /* register the new slot */
1185 slot_size
= MIN(kvm_max_slot_size
, size
);
1186 mem
= kvm_alloc_slot(kml
);
1187 mem
->memory_size
= slot_size
;
1188 mem
->start_addr
= start_addr
;
1190 mem
->flags
= kvm_mem_flags(mr
);
1192 if (mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
1194 * Reallocate the bmap; it means it doesn't disappear in
1195 * middle of a migrate.
1197 kvm_memslot_init_dirty_bitmap(mem
);
1199 err
= kvm_set_user_memory_region(kml
, mem
, true);
1201 fprintf(stderr
, "%s: error registering slot: %s\n", __func__
,
1205 start_addr
+= slot_size
;
1211 kvm_slots_unlock(kml
);
1214 static void kvm_region_add(MemoryListener
*listener
,
1215 MemoryRegionSection
*section
)
1217 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1219 memory_region_ref(section
->mr
);
1220 kvm_set_phys_mem(kml
, section
, true);
1223 static void kvm_region_del(MemoryListener
*listener
,
1224 MemoryRegionSection
*section
)
1226 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1228 kvm_set_phys_mem(kml
, section
, false);
1229 memory_region_unref(section
->mr
);
1232 static void kvm_log_sync(MemoryListener
*listener
,
1233 MemoryRegionSection
*section
)
1235 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1238 kvm_slots_lock(kml
);
1239 r
= kvm_physical_sync_dirty_bitmap(kml
, section
);
1240 kvm_slots_unlock(kml
);
1246 static void kvm_log_clear(MemoryListener
*listener
,
1247 MemoryRegionSection
*section
)
1249 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1252 r
= kvm_physical_log_clear(kml
, section
);
1254 error_report_once("%s: kvm log clear failed: mr=%s "
1255 "offset=%"HWADDR_PRIx
" size=%"PRIx64
, __func__
,
1256 section
->mr
->name
, section
->offset_within_region
,
1257 int128_get64(section
->size
));
1262 static void kvm_mem_ioeventfd_add(MemoryListener
*listener
,
1263 MemoryRegionSection
*section
,
1264 bool match_data
, uint64_t data
,
1267 int fd
= event_notifier_get_fd(e
);
1270 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
1271 data
, true, int128_get64(section
->size
),
1274 fprintf(stderr
, "%s: error adding ioeventfd: %s (%d)\n",
1275 __func__
, strerror(-r
), -r
);
1280 static void kvm_mem_ioeventfd_del(MemoryListener
*listener
,
1281 MemoryRegionSection
*section
,
1282 bool match_data
, uint64_t data
,
1285 int fd
= event_notifier_get_fd(e
);
1288 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
1289 data
, false, int128_get64(section
->size
),
1292 fprintf(stderr
, "%s: error deleting ioeventfd: %s (%d)\n",
1293 __func__
, strerror(-r
), -r
);
1298 static void kvm_io_ioeventfd_add(MemoryListener
*listener
,
1299 MemoryRegionSection
*section
,
1300 bool match_data
, uint64_t data
,
1303 int fd
= event_notifier_get_fd(e
);
1306 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
1307 data
, true, int128_get64(section
->size
),
1310 fprintf(stderr
, "%s: error adding ioeventfd: %s (%d)\n",
1311 __func__
, strerror(-r
), -r
);
1316 static void kvm_io_ioeventfd_del(MemoryListener
*listener
,
1317 MemoryRegionSection
*section
,
1318 bool match_data
, uint64_t data
,
1322 int fd
= event_notifier_get_fd(e
);
1325 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
1326 data
, false, int128_get64(section
->size
),
1329 fprintf(stderr
, "%s: error deleting ioeventfd: %s (%d)\n",
1330 __func__
, strerror(-r
), -r
);
1335 void kvm_memory_listener_register(KVMState
*s
, KVMMemoryListener
*kml
,
1336 AddressSpace
*as
, int as_id
)
1340 qemu_mutex_init(&kml
->slots_lock
);
1341 kml
->slots
= g_malloc0(s
->nr_slots
* sizeof(KVMSlot
));
1344 for (i
= 0; i
< s
->nr_slots
; i
++) {
1345 kml
->slots
[i
].slot
= i
;
1348 kml
->listener
.region_add
= kvm_region_add
;
1349 kml
->listener
.region_del
= kvm_region_del
;
1350 kml
->listener
.log_start
= kvm_log_start
;
1351 kml
->listener
.log_stop
= kvm_log_stop
;
1352 kml
->listener
.log_sync
= kvm_log_sync
;
1353 kml
->listener
.log_clear
= kvm_log_clear
;
1354 kml
->listener
.priority
= 10;
1356 memory_listener_register(&kml
->listener
, as
);
1358 for (i
= 0; i
< s
->nr_as
; ++i
) {
1367 static MemoryListener kvm_io_listener
= {
1368 .eventfd_add
= kvm_io_ioeventfd_add
,
1369 .eventfd_del
= kvm_io_ioeventfd_del
,
1373 int kvm_set_irq(KVMState
*s
, int irq
, int level
)
1375 struct kvm_irq_level event
;
1378 assert(kvm_async_interrupts_enabled());
1380 event
.level
= level
;
1382 ret
= kvm_vm_ioctl(s
, s
->irq_set_ioctl
, &event
);
1384 perror("kvm_set_irq");
1388 return (s
->irq_set_ioctl
== KVM_IRQ_LINE
) ? 1 : event
.status
;
1391 #ifdef KVM_CAP_IRQ_ROUTING
1392 typedef struct KVMMSIRoute
{
1393 struct kvm_irq_routing_entry kroute
;
1394 QTAILQ_ENTRY(KVMMSIRoute
) entry
;
1397 static void set_gsi(KVMState
*s
, unsigned int gsi
)
1399 set_bit(gsi
, s
->used_gsi_bitmap
);
1402 static void clear_gsi(KVMState
*s
, unsigned int gsi
)
1404 clear_bit(gsi
, s
->used_gsi_bitmap
);
1407 void kvm_init_irq_routing(KVMState
*s
)
1411 gsi_count
= kvm_check_extension(s
, KVM_CAP_IRQ_ROUTING
) - 1;
1412 if (gsi_count
> 0) {
1413 /* Round up so we can search ints using ffs */
1414 s
->used_gsi_bitmap
= bitmap_new(gsi_count
);
1415 s
->gsi_count
= gsi_count
;
1418 s
->irq_routes
= g_malloc0(sizeof(*s
->irq_routes
));
1419 s
->nr_allocated_irq_routes
= 0;
1421 if (!kvm_direct_msi_allowed
) {
1422 for (i
= 0; i
< KVM_MSI_HASHTAB_SIZE
; i
++) {
1423 QTAILQ_INIT(&s
->msi_hashtab
[i
]);
1427 kvm_arch_init_irq_routing(s
);
1430 void kvm_irqchip_commit_routes(KVMState
*s
)
1434 if (kvm_gsi_direct_mapping()) {
1438 if (!kvm_gsi_routing_enabled()) {
1442 s
->irq_routes
->flags
= 0;
1443 trace_kvm_irqchip_commit_routes();
1444 ret
= kvm_vm_ioctl(s
, KVM_SET_GSI_ROUTING
, s
->irq_routes
);
1448 static void kvm_add_routing_entry(KVMState
*s
,
1449 struct kvm_irq_routing_entry
*entry
)
1451 struct kvm_irq_routing_entry
*new;
1454 if (s
->irq_routes
->nr
== s
->nr_allocated_irq_routes
) {
1455 n
= s
->nr_allocated_irq_routes
* 2;
1459 size
= sizeof(struct kvm_irq_routing
);
1460 size
+= n
* sizeof(*new);
1461 s
->irq_routes
= g_realloc(s
->irq_routes
, size
);
1462 s
->nr_allocated_irq_routes
= n
;
1464 n
= s
->irq_routes
->nr
++;
1465 new = &s
->irq_routes
->entries
[n
];
1469 set_gsi(s
, entry
->gsi
);
1472 static int kvm_update_routing_entry(KVMState
*s
,
1473 struct kvm_irq_routing_entry
*new_entry
)
1475 struct kvm_irq_routing_entry
*entry
;
1478 for (n
= 0; n
< s
->irq_routes
->nr
; n
++) {
1479 entry
= &s
->irq_routes
->entries
[n
];
1480 if (entry
->gsi
!= new_entry
->gsi
) {
1484 if(!memcmp(entry
, new_entry
, sizeof *entry
)) {
1488 *entry
= *new_entry
;
1496 void kvm_irqchip_add_irq_route(KVMState
*s
, int irq
, int irqchip
, int pin
)
1498 struct kvm_irq_routing_entry e
= {};
1500 assert(pin
< s
->gsi_count
);
1503 e
.type
= KVM_IRQ_ROUTING_IRQCHIP
;
1505 e
.u
.irqchip
.irqchip
= irqchip
;
1506 e
.u
.irqchip
.pin
= pin
;
1507 kvm_add_routing_entry(s
, &e
);
1510 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
1512 struct kvm_irq_routing_entry
*e
;
1515 if (kvm_gsi_direct_mapping()) {
1519 for (i
= 0; i
< s
->irq_routes
->nr
; i
++) {
1520 e
= &s
->irq_routes
->entries
[i
];
1521 if (e
->gsi
== virq
) {
1522 s
->irq_routes
->nr
--;
1523 *e
= s
->irq_routes
->entries
[s
->irq_routes
->nr
];
1527 kvm_arch_release_virq_post(virq
);
1528 trace_kvm_irqchip_release_virq(virq
);
1531 void kvm_irqchip_add_change_notifier(Notifier
*n
)
1533 notifier_list_add(&kvm_irqchip_change_notifiers
, n
);
1536 void kvm_irqchip_remove_change_notifier(Notifier
*n
)
1541 void kvm_irqchip_change_notify(void)
1543 notifier_list_notify(&kvm_irqchip_change_notifiers
, NULL
);
1546 static unsigned int kvm_hash_msi(uint32_t data
)
1548 /* This is optimized for IA32 MSI layout. However, no other arch shall
1549 * repeat the mistake of not providing a direct MSI injection API. */
1553 static void kvm_flush_dynamic_msi_routes(KVMState
*s
)
1555 KVMMSIRoute
*route
, *next
;
1558 for (hash
= 0; hash
< KVM_MSI_HASHTAB_SIZE
; hash
++) {
1559 QTAILQ_FOREACH_SAFE(route
, &s
->msi_hashtab
[hash
], entry
, next
) {
1560 kvm_irqchip_release_virq(s
, route
->kroute
.gsi
);
1561 QTAILQ_REMOVE(&s
->msi_hashtab
[hash
], route
, entry
);
1567 static int kvm_irqchip_get_virq(KVMState
*s
)
1572 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1573 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1574 * number can succeed even though a new route entry cannot be added.
1575 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1577 if (!kvm_direct_msi_allowed
&& s
->irq_routes
->nr
== s
->gsi_count
) {
1578 kvm_flush_dynamic_msi_routes(s
);
1581 /* Return the lowest unused GSI in the bitmap */
1582 next_virq
= find_first_zero_bit(s
->used_gsi_bitmap
, s
->gsi_count
);
1583 if (next_virq
>= s
->gsi_count
) {
1590 static KVMMSIRoute
*kvm_lookup_msi_route(KVMState
*s
, MSIMessage msg
)
1592 unsigned int hash
= kvm_hash_msi(msg
.data
);
1595 QTAILQ_FOREACH(route
, &s
->msi_hashtab
[hash
], entry
) {
1596 if (route
->kroute
.u
.msi
.address_lo
== (uint32_t)msg
.address
&&
1597 route
->kroute
.u
.msi
.address_hi
== (msg
.address
>> 32) &&
1598 route
->kroute
.u
.msi
.data
== le32_to_cpu(msg
.data
)) {
1605 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1610 if (kvm_direct_msi_allowed
) {
1611 msi
.address_lo
= (uint32_t)msg
.address
;
1612 msi
.address_hi
= msg
.address
>> 32;
1613 msi
.data
= le32_to_cpu(msg
.data
);
1615 memset(msi
.pad
, 0, sizeof(msi
.pad
));
1617 return kvm_vm_ioctl(s
, KVM_SIGNAL_MSI
, &msi
);
1620 route
= kvm_lookup_msi_route(s
, msg
);
1624 virq
= kvm_irqchip_get_virq(s
);
1629 route
= g_malloc0(sizeof(KVMMSIRoute
));
1630 route
->kroute
.gsi
= virq
;
1631 route
->kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1632 route
->kroute
.flags
= 0;
1633 route
->kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1634 route
->kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1635 route
->kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1637 kvm_add_routing_entry(s
, &route
->kroute
);
1638 kvm_irqchip_commit_routes(s
);
1640 QTAILQ_INSERT_TAIL(&s
->msi_hashtab
[kvm_hash_msi(msg
.data
)], route
,
1644 assert(route
->kroute
.type
== KVM_IRQ_ROUTING_MSI
);
1646 return kvm_set_irq(s
, route
->kroute
.gsi
, 1);
1649 int kvm_irqchip_add_msi_route(KVMState
*s
, int vector
, PCIDevice
*dev
)
1651 struct kvm_irq_routing_entry kroute
= {};
1653 MSIMessage msg
= {0, 0};
1655 if (pci_available
&& dev
) {
1656 msg
= pci_get_msi_message(dev
, vector
);
1659 if (kvm_gsi_direct_mapping()) {
1660 return kvm_arch_msi_data_to_gsi(msg
.data
);
1663 if (!kvm_gsi_routing_enabled()) {
1667 virq
= kvm_irqchip_get_virq(s
);
1673 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1675 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1676 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1677 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1678 if (pci_available
&& kvm_msi_devid_required()) {
1679 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1680 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1682 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1683 kvm_irqchip_release_virq(s
, virq
);
1687 trace_kvm_irqchip_add_msi_route(dev
? dev
->name
: (char *)"N/A",
1690 kvm_add_routing_entry(s
, &kroute
);
1691 kvm_arch_add_msi_route_post(&kroute
, vector
, dev
);
1692 kvm_irqchip_commit_routes(s
);
1697 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
,
1700 struct kvm_irq_routing_entry kroute
= {};
1702 if (kvm_gsi_direct_mapping()) {
1706 if (!kvm_irqchip_in_kernel()) {
1711 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1713 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1714 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1715 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1716 if (pci_available
&& kvm_msi_devid_required()) {
1717 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1718 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1720 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1724 trace_kvm_irqchip_update_msi_route(virq
);
1726 return kvm_update_routing_entry(s
, &kroute
);
1729 static int kvm_irqchip_assign_irqfd(KVMState
*s
, EventNotifier
*event
,
1730 EventNotifier
*resample
, int virq
,
1733 int fd
= event_notifier_get_fd(event
);
1734 int rfd
= resample
? event_notifier_get_fd(resample
) : -1;
1736 struct kvm_irqfd irqfd
= {
1739 .flags
= assign
? 0 : KVM_IRQFD_FLAG_DEASSIGN
,
1744 if (kvm_irqchip_is_split()) {
1746 * When the slow irqchip (e.g. IOAPIC) is in the
1747 * userspace, KVM kernel resamplefd will not work because
1748 * the EOI of the interrupt will be delivered to userspace
1749 * instead, so the KVM kernel resamplefd kick will be
1750 * skipped. The userspace here mimics what the kernel
1751 * provides with resamplefd, remember the resamplefd and
1752 * kick it when we receive EOI of this IRQ.
1754 * This is hackery because IOAPIC is mostly bypassed
1755 * (except EOI broadcasts) when irqfd is used. However
1756 * this can bring much performance back for split irqchip
1757 * with INTx IRQs (for VFIO, this gives 93% perf of the
1758 * full fast path, which is 46% perf boost comparing to
1759 * the INTx slow path).
1761 kvm_resample_fd_insert(virq
, resample
);
1763 irqfd
.flags
|= KVM_IRQFD_FLAG_RESAMPLE
;
1764 irqfd
.resamplefd
= rfd
;
1766 } else if (!assign
) {
1767 if (kvm_irqchip_is_split()) {
1768 kvm_resample_fd_remove(virq
);
1772 if (!kvm_irqfds_enabled()) {
1776 return kvm_vm_ioctl(s
, KVM_IRQFD
, &irqfd
);
1779 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
1781 struct kvm_irq_routing_entry kroute
= {};
1784 if (!kvm_gsi_routing_enabled()) {
1788 virq
= kvm_irqchip_get_virq(s
);
1794 kroute
.type
= KVM_IRQ_ROUTING_S390_ADAPTER
;
1796 kroute
.u
.adapter
.summary_addr
= adapter
->summary_addr
;
1797 kroute
.u
.adapter
.ind_addr
= adapter
->ind_addr
;
1798 kroute
.u
.adapter
.summary_offset
= adapter
->summary_offset
;
1799 kroute
.u
.adapter
.ind_offset
= adapter
->ind_offset
;
1800 kroute
.u
.adapter
.adapter_id
= adapter
->adapter_id
;
1802 kvm_add_routing_entry(s
, &kroute
);
1807 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
1809 struct kvm_irq_routing_entry kroute
= {};
1812 if (!kvm_gsi_routing_enabled()) {
1815 if (!kvm_check_extension(s
, KVM_CAP_HYPERV_SYNIC
)) {
1818 virq
= kvm_irqchip_get_virq(s
);
1824 kroute
.type
= KVM_IRQ_ROUTING_HV_SINT
;
1826 kroute
.u
.hv_sint
.vcpu
= vcpu
;
1827 kroute
.u
.hv_sint
.sint
= sint
;
1829 kvm_add_routing_entry(s
, &kroute
);
1830 kvm_irqchip_commit_routes(s
);
1835 #else /* !KVM_CAP_IRQ_ROUTING */
1837 void kvm_init_irq_routing(KVMState
*s
)
1841 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
1845 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1850 int kvm_irqchip_add_msi_route(KVMState
*s
, int vector
, PCIDevice
*dev
)
1855 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
1860 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
1865 static int kvm_irqchip_assign_irqfd(KVMState
*s
, EventNotifier
*event
,
1866 EventNotifier
*resample
, int virq
,
1872 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
)
1876 #endif /* !KVM_CAP_IRQ_ROUTING */
1878 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
1879 EventNotifier
*rn
, int virq
)
1881 return kvm_irqchip_assign_irqfd(s
, n
, rn
, virq
, true);
1884 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
1887 return kvm_irqchip_assign_irqfd(s
, n
, NULL
, virq
, false);
1890 int kvm_irqchip_add_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
1891 EventNotifier
*rn
, qemu_irq irq
)
1894 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
1899 return kvm_irqchip_add_irqfd_notifier_gsi(s
, n
, rn
, GPOINTER_TO_INT(gsi
));
1902 int kvm_irqchip_remove_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
1906 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
1911 return kvm_irqchip_remove_irqfd_notifier_gsi(s
, n
, GPOINTER_TO_INT(gsi
));
1914 void kvm_irqchip_set_qemuirq_gsi(KVMState
*s
, qemu_irq irq
, int gsi
)
1916 g_hash_table_insert(s
->gsimap
, irq
, GINT_TO_POINTER(gsi
));
1919 static void kvm_irqchip_create(KVMState
*s
)
1923 assert(s
->kernel_irqchip_split
!= ON_OFF_AUTO_AUTO
);
1924 if (kvm_check_extension(s
, KVM_CAP_IRQCHIP
)) {
1926 } else if (kvm_check_extension(s
, KVM_CAP_S390_IRQCHIP
)) {
1927 ret
= kvm_vm_enable_cap(s
, KVM_CAP_S390_IRQCHIP
, 0);
1929 fprintf(stderr
, "Enable kernel irqchip failed: %s\n", strerror(-ret
));
1936 /* First probe and see if there's a arch-specific hook to create the
1937 * in-kernel irqchip for us */
1938 ret
= kvm_arch_irqchip_create(s
);
1940 if (s
->kernel_irqchip_split
== ON_OFF_AUTO_ON
) {
1941 perror("Split IRQ chip mode not supported.");
1944 ret
= kvm_vm_ioctl(s
, KVM_CREATE_IRQCHIP
);
1948 fprintf(stderr
, "Create kernel irqchip failed: %s\n", strerror(-ret
));
1952 kvm_kernel_irqchip
= true;
1953 /* If we have an in-kernel IRQ chip then we must have asynchronous
1954 * interrupt delivery (though the reverse is not necessarily true)
1956 kvm_async_interrupts_allowed
= true;
1957 kvm_halt_in_kernel_allowed
= true;
1959 kvm_init_irq_routing(s
);
1961 s
->gsimap
= g_hash_table_new(g_direct_hash
, g_direct_equal
);
1964 /* Find number of supported CPUs using the recommended
1965 * procedure from the kernel API documentation to cope with
1966 * older kernels that may be missing capabilities.
1968 static int kvm_recommended_vcpus(KVMState
*s
)
1970 int ret
= kvm_vm_check_extension(s
, KVM_CAP_NR_VCPUS
);
1971 return (ret
) ? ret
: 4;
1974 static int kvm_max_vcpus(KVMState
*s
)
1976 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPUS
);
1977 return (ret
) ? ret
: kvm_recommended_vcpus(s
);
1980 static int kvm_max_vcpu_id(KVMState
*s
)
1982 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPU_ID
);
1983 return (ret
) ? ret
: kvm_max_vcpus(s
);
1986 bool kvm_vcpu_id_is_valid(int vcpu_id
)
1988 KVMState
*s
= KVM_STATE(current_accel());
1989 return vcpu_id
>= 0 && vcpu_id
< kvm_max_vcpu_id(s
);
1992 static int kvm_init(MachineState
*ms
)
1994 MachineClass
*mc
= MACHINE_GET_CLASS(ms
);
1995 static const char upgrade_note
[] =
1996 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1997 "(see http://sourceforge.net/projects/kvm).\n";
2002 { "SMP", ms
->smp
.cpus
},
2003 { "hotpluggable", ms
->smp
.max_cpus
},
2006 int soft_vcpus_limit
, hard_vcpus_limit
;
2008 const KVMCapabilityInfo
*missing_cap
;
2011 uint64_t dirty_log_manual_caps
;
2013 s
= KVM_STATE(ms
->accelerator
);
2016 * On systems where the kernel can support different base page
2017 * sizes, host page size may be different from TARGET_PAGE_SIZE,
2018 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
2019 * page size for the system though.
2021 assert(TARGET_PAGE_SIZE
<= qemu_real_host_page_size
);
2025 #ifdef KVM_CAP_SET_GUEST_DEBUG
2026 QTAILQ_INIT(&s
->kvm_sw_breakpoints
);
2028 QLIST_INIT(&s
->kvm_parked_vcpus
);
2030 s
->fd
= qemu_open_old("/dev/kvm", O_RDWR
);
2032 fprintf(stderr
, "Could not access KVM kernel module: %m\n");
2037 ret
= kvm_ioctl(s
, KVM_GET_API_VERSION
, 0);
2038 if (ret
< KVM_API_VERSION
) {
2042 fprintf(stderr
, "kvm version too old\n");
2046 if (ret
> KVM_API_VERSION
) {
2048 fprintf(stderr
, "kvm version not supported\n");
2052 kvm_immediate_exit
= kvm_check_extension(s
, KVM_CAP_IMMEDIATE_EXIT
);
2053 s
->nr_slots
= kvm_check_extension(s
, KVM_CAP_NR_MEMSLOTS
);
2055 /* If unspecified, use the default value */
2060 s
->nr_as
= kvm_check_extension(s
, KVM_CAP_MULTI_ADDRESS_SPACE
);
2061 if (s
->nr_as
<= 1) {
2064 s
->as
= g_new0(struct KVMAs
, s
->nr_as
);
2066 if (object_property_find(OBJECT(current_machine
), "kvm-type")) {
2067 g_autofree
char *kvm_type
= object_property_get_str(OBJECT(current_machine
),
2070 type
= mc
->kvm_type(ms
, kvm_type
);
2074 ret
= kvm_ioctl(s
, KVM_CREATE_VM
, type
);
2075 } while (ret
== -EINTR
);
2078 fprintf(stderr
, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret
,
2082 if (ret
== -EINVAL
) {
2084 "Host kernel setup problem detected. Please verify:\n");
2085 fprintf(stderr
, "- for kernels supporting the switch_amode or"
2086 " user_mode parameters, whether\n");
2088 " user space is running in primary address space\n");
2090 "- for kernels supporting the vm.allocate_pgste sysctl, "
2091 "whether it is enabled\n");
2099 /* check the vcpu limits */
2100 soft_vcpus_limit
= kvm_recommended_vcpus(s
);
2101 hard_vcpus_limit
= kvm_max_vcpus(s
);
2104 if (nc
->num
> soft_vcpus_limit
) {
2105 warn_report("Number of %s cpus requested (%d) exceeds "
2106 "the recommended cpus supported by KVM (%d)",
2107 nc
->name
, nc
->num
, soft_vcpus_limit
);
2109 if (nc
->num
> hard_vcpus_limit
) {
2110 fprintf(stderr
, "Number of %s cpus requested (%d) exceeds "
2111 "the maximum cpus supported by KVM (%d)\n",
2112 nc
->name
, nc
->num
, hard_vcpus_limit
);
2119 missing_cap
= kvm_check_extension_list(s
, kvm_required_capabilites
);
2122 kvm_check_extension_list(s
, kvm_arch_required_capabilities
);
2126 fprintf(stderr
, "kvm does not support %s\n%s",
2127 missing_cap
->name
, upgrade_note
);
2131 s
->coalesced_mmio
= kvm_check_extension(s
, KVM_CAP_COALESCED_MMIO
);
2132 s
->coalesced_pio
= s
->coalesced_mmio
&&
2133 kvm_check_extension(s
, KVM_CAP_COALESCED_PIO
);
2135 dirty_log_manual_caps
=
2136 kvm_check_extension(s
, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2
);
2137 dirty_log_manual_caps
&= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE
|
2138 KVM_DIRTY_LOG_INITIALLY_SET
);
2139 s
->manual_dirty_log_protect
= dirty_log_manual_caps
;
2140 if (dirty_log_manual_caps
) {
2141 ret
= kvm_vm_enable_cap(s
, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2
, 0,
2142 dirty_log_manual_caps
);
2144 warn_report("Trying to enable capability %"PRIu64
" of "
2145 "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
2146 "Falling back to the legacy mode. ",
2147 dirty_log_manual_caps
);
2148 s
->manual_dirty_log_protect
= 0;
2152 #ifdef KVM_CAP_VCPU_EVENTS
2153 s
->vcpu_events
= kvm_check_extension(s
, KVM_CAP_VCPU_EVENTS
);
2156 s
->robust_singlestep
=
2157 kvm_check_extension(s
, KVM_CAP_X86_ROBUST_SINGLESTEP
);
2159 #ifdef KVM_CAP_DEBUGREGS
2160 s
->debugregs
= kvm_check_extension(s
, KVM_CAP_DEBUGREGS
);
2163 s
->max_nested_state_len
= kvm_check_extension(s
, KVM_CAP_NESTED_STATE
);
2165 #ifdef KVM_CAP_IRQ_ROUTING
2166 kvm_direct_msi_allowed
= (kvm_check_extension(s
, KVM_CAP_SIGNAL_MSI
) > 0);
2169 s
->intx_set_mask
= kvm_check_extension(s
, KVM_CAP_PCI_2_3
);
2171 s
->irq_set_ioctl
= KVM_IRQ_LINE
;
2172 if (kvm_check_extension(s
, KVM_CAP_IRQ_INJECT_STATUS
)) {
2173 s
->irq_set_ioctl
= KVM_IRQ_LINE_STATUS
;
2176 kvm_readonly_mem_allowed
=
2177 (kvm_check_extension(s
, KVM_CAP_READONLY_MEM
) > 0);
2179 kvm_eventfds_allowed
=
2180 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD
) > 0);
2182 kvm_irqfds_allowed
=
2183 (kvm_check_extension(s
, KVM_CAP_IRQFD
) > 0);
2185 kvm_resamplefds_allowed
=
2186 (kvm_check_extension(s
, KVM_CAP_IRQFD_RESAMPLE
) > 0);
2188 kvm_vm_attributes_allowed
=
2189 (kvm_check_extension(s
, KVM_CAP_VM_ATTRIBUTES
) > 0);
2191 kvm_ioeventfd_any_length_allowed
=
2192 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD_ANY_LENGTH
) > 0);
2196 ret
= kvm_arch_init(ms
, s
);
2201 if (s
->kernel_irqchip_split
== ON_OFF_AUTO_AUTO
) {
2202 s
->kernel_irqchip_split
= mc
->default_kernel_irqchip_split
? ON_OFF_AUTO_ON
: ON_OFF_AUTO_OFF
;
2205 qemu_register_reset(kvm_unpoison_all
, NULL
);
2207 if (s
->kernel_irqchip_allowed
) {
2208 kvm_irqchip_create(s
);
2211 if (kvm_eventfds_allowed
) {
2212 s
->memory_listener
.listener
.eventfd_add
= kvm_mem_ioeventfd_add
;
2213 s
->memory_listener
.listener
.eventfd_del
= kvm_mem_ioeventfd_del
;
2215 s
->memory_listener
.listener
.coalesced_io_add
= kvm_coalesce_mmio_region
;
2216 s
->memory_listener
.listener
.coalesced_io_del
= kvm_uncoalesce_mmio_region
;
2218 kvm_memory_listener_register(s
, &s
->memory_listener
,
2219 &address_space_memory
, 0);
2220 if (kvm_eventfds_allowed
) {
2221 memory_listener_register(&kvm_io_listener
,
2224 memory_listener_register(&kvm_coalesced_pio_listener
,
2227 s
->many_ioeventfds
= kvm_check_many_ioeventfds();
2229 s
->sync_mmu
= !!kvm_vm_check_extension(kvm_state
, KVM_CAP_SYNC_MMU
);
2231 ret
= ram_block_discard_disable(true);
2244 g_free(s
->memory_listener
.slots
);
2249 void kvm_set_sigmask_len(KVMState
*s
, unsigned int sigmask_len
)
2251 s
->sigmask_len
= sigmask_len
;
2254 static void kvm_handle_io(uint16_t port
, MemTxAttrs attrs
, void *data
, int direction
,
2255 int size
, uint32_t count
)
2258 uint8_t *ptr
= data
;
2260 for (i
= 0; i
< count
; i
++) {
2261 address_space_rw(&address_space_io
, port
, attrs
,
2263 direction
== KVM_EXIT_IO_OUT
);
2268 static int kvm_handle_internal_error(CPUState
*cpu
, struct kvm_run
*run
)
2270 fprintf(stderr
, "KVM internal error. Suberror: %d\n",
2271 run
->internal
.suberror
);
2273 if (kvm_check_extension(kvm_state
, KVM_CAP_INTERNAL_ERROR_DATA
)) {
2276 for (i
= 0; i
< run
->internal
.ndata
; ++i
) {
2277 fprintf(stderr
, "extra data[%d]: %"PRIx64
"\n",
2278 i
, (uint64_t)run
->internal
.data
[i
]);
2281 if (run
->internal
.suberror
== KVM_INTERNAL_ERROR_EMULATION
) {
2282 fprintf(stderr
, "emulation failure\n");
2283 if (!kvm_arch_stop_on_emulation_error(cpu
)) {
2284 cpu_dump_state(cpu
, stderr
, CPU_DUMP_CODE
);
2285 return EXCP_INTERRUPT
;
2288 /* FIXME: Should trigger a qmp message to let management know
2289 * something went wrong.
2294 void kvm_flush_coalesced_mmio_buffer(void)
2296 KVMState
*s
= kvm_state
;
2298 if (s
->coalesced_flush_in_progress
) {
2302 s
->coalesced_flush_in_progress
= true;
2304 if (s
->coalesced_mmio_ring
) {
2305 struct kvm_coalesced_mmio_ring
*ring
= s
->coalesced_mmio_ring
;
2306 while (ring
->first
!= ring
->last
) {
2307 struct kvm_coalesced_mmio
*ent
;
2309 ent
= &ring
->coalesced_mmio
[ring
->first
];
2311 if (ent
->pio
== 1) {
2312 address_space_write(&address_space_io
, ent
->phys_addr
,
2313 MEMTXATTRS_UNSPECIFIED
, ent
->data
,
2316 cpu_physical_memory_write(ent
->phys_addr
, ent
->data
, ent
->len
);
2319 ring
->first
= (ring
->first
+ 1) % KVM_COALESCED_MMIO_MAX
;
2323 s
->coalesced_flush_in_progress
= false;
2326 bool kvm_cpu_check_are_resettable(void)
2328 return kvm_arch_cpu_check_are_resettable();
2331 static void do_kvm_cpu_synchronize_state(CPUState
*cpu
, run_on_cpu_data arg
)
2333 if (!cpu
->vcpu_dirty
) {
2334 kvm_arch_get_registers(cpu
);
2335 cpu
->vcpu_dirty
= true;
2339 void kvm_cpu_synchronize_state(CPUState
*cpu
)
2341 if (!cpu
->vcpu_dirty
) {
2342 run_on_cpu(cpu
, do_kvm_cpu_synchronize_state
, RUN_ON_CPU_NULL
);
2346 static void do_kvm_cpu_synchronize_post_reset(CPUState
*cpu
, run_on_cpu_data arg
)
2348 kvm_arch_put_registers(cpu
, KVM_PUT_RESET_STATE
);
2349 cpu
->vcpu_dirty
= false;
2352 void kvm_cpu_synchronize_post_reset(CPUState
*cpu
)
2354 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_reset
, RUN_ON_CPU_NULL
);
2357 static void do_kvm_cpu_synchronize_post_init(CPUState
*cpu
, run_on_cpu_data arg
)
2359 kvm_arch_put_registers(cpu
, KVM_PUT_FULL_STATE
);
2360 cpu
->vcpu_dirty
= false;
2363 void kvm_cpu_synchronize_post_init(CPUState
*cpu
)
2365 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_init
, RUN_ON_CPU_NULL
);
2368 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
, run_on_cpu_data arg
)
2370 cpu
->vcpu_dirty
= true;
2373 void kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
)
2375 run_on_cpu(cpu
, do_kvm_cpu_synchronize_pre_loadvm
, RUN_ON_CPU_NULL
);
2378 #ifdef KVM_HAVE_MCE_INJECTION
2379 static __thread
void *pending_sigbus_addr
;
2380 static __thread
int pending_sigbus_code
;
2381 static __thread
bool have_sigbus_pending
;
2384 static void kvm_cpu_kick(CPUState
*cpu
)
2386 qatomic_set(&cpu
->kvm_run
->immediate_exit
, 1);
2389 static void kvm_cpu_kick_self(void)
2391 if (kvm_immediate_exit
) {
2392 kvm_cpu_kick(current_cpu
);
2394 qemu_cpu_kick_self();
2398 static void kvm_eat_signals(CPUState
*cpu
)
2400 struct timespec ts
= { 0, 0 };
2406 if (kvm_immediate_exit
) {
2407 qatomic_set(&cpu
->kvm_run
->immediate_exit
, 0);
2408 /* Write kvm_run->immediate_exit before the cpu->exit_request
2409 * write in kvm_cpu_exec.
2415 sigemptyset(&waitset
);
2416 sigaddset(&waitset
, SIG_IPI
);
2419 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
2420 if (r
== -1 && !(errno
== EAGAIN
|| errno
== EINTR
)) {
2421 perror("sigtimedwait");
2425 r
= sigpending(&chkset
);
2427 perror("sigpending");
2430 } while (sigismember(&chkset
, SIG_IPI
));
2433 int kvm_cpu_exec(CPUState
*cpu
)
2435 struct kvm_run
*run
= cpu
->kvm_run
;
2438 DPRINTF("kvm_cpu_exec()\n");
2440 if (kvm_arch_process_async_events(cpu
)) {
2441 qatomic_set(&cpu
->exit_request
, 0);
2445 qemu_mutex_unlock_iothread();
2446 cpu_exec_start(cpu
);
2451 if (cpu
->vcpu_dirty
) {
2452 kvm_arch_put_registers(cpu
, KVM_PUT_RUNTIME_STATE
);
2453 cpu
->vcpu_dirty
= false;
2456 kvm_arch_pre_run(cpu
, run
);
2457 if (qatomic_read(&cpu
->exit_request
)) {
2458 DPRINTF("interrupt exit requested\n");
2460 * KVM requires us to reenter the kernel after IO exits to complete
2461 * instruction emulation. This self-signal will ensure that we
2464 kvm_cpu_kick_self();
2467 /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2468 * Matching barrier in kvm_eat_signals.
2472 run_ret
= kvm_vcpu_ioctl(cpu
, KVM_RUN
, 0);
2474 attrs
= kvm_arch_post_run(cpu
, run
);
2476 #ifdef KVM_HAVE_MCE_INJECTION
2477 if (unlikely(have_sigbus_pending
)) {
2478 qemu_mutex_lock_iothread();
2479 kvm_arch_on_sigbus_vcpu(cpu
, pending_sigbus_code
,
2480 pending_sigbus_addr
);
2481 have_sigbus_pending
= false;
2482 qemu_mutex_unlock_iothread();
2487 if (run_ret
== -EINTR
|| run_ret
== -EAGAIN
) {
2488 DPRINTF("io window exit\n");
2489 kvm_eat_signals(cpu
);
2490 ret
= EXCP_INTERRUPT
;
2493 fprintf(stderr
, "error: kvm run failed %s\n",
2494 strerror(-run_ret
));
2496 if (run_ret
== -EBUSY
) {
2498 "This is probably because your SMT is enabled.\n"
2499 "VCPU can only run on primary threads with all "
2500 "secondary threads offline.\n");
2507 trace_kvm_run_exit(cpu
->cpu_index
, run
->exit_reason
);
2508 switch (run
->exit_reason
) {
2510 DPRINTF("handle_io\n");
2511 /* Called outside BQL */
2512 kvm_handle_io(run
->io
.port
, attrs
,
2513 (uint8_t *)run
+ run
->io
.data_offset
,
2520 DPRINTF("handle_mmio\n");
2521 /* Called outside BQL */
2522 address_space_rw(&address_space_memory
,
2523 run
->mmio
.phys_addr
, attrs
,
2526 run
->mmio
.is_write
);
2529 case KVM_EXIT_IRQ_WINDOW_OPEN
:
2530 DPRINTF("irq_window_open\n");
2531 ret
= EXCP_INTERRUPT
;
2533 case KVM_EXIT_SHUTDOWN
:
2534 DPRINTF("shutdown\n");
2535 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
2536 ret
= EXCP_INTERRUPT
;
2538 case KVM_EXIT_UNKNOWN
:
2539 fprintf(stderr
, "KVM: unknown exit, hardware reason %" PRIx64
"\n",
2540 (uint64_t)run
->hw
.hardware_exit_reason
);
2543 case KVM_EXIT_INTERNAL_ERROR
:
2544 ret
= kvm_handle_internal_error(cpu
, run
);
2546 case KVM_EXIT_SYSTEM_EVENT
:
2547 switch (run
->system_event
.type
) {
2548 case KVM_SYSTEM_EVENT_SHUTDOWN
:
2549 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN
);
2550 ret
= EXCP_INTERRUPT
;
2552 case KVM_SYSTEM_EVENT_RESET
:
2553 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
2554 ret
= EXCP_INTERRUPT
;
2556 case KVM_SYSTEM_EVENT_CRASH
:
2557 kvm_cpu_synchronize_state(cpu
);
2558 qemu_mutex_lock_iothread();
2559 qemu_system_guest_panicked(cpu_get_crash_info(cpu
));
2560 qemu_mutex_unlock_iothread();
2564 DPRINTF("kvm_arch_handle_exit\n");
2565 ret
= kvm_arch_handle_exit(cpu
, run
);
2570 DPRINTF("kvm_arch_handle_exit\n");
2571 ret
= kvm_arch_handle_exit(cpu
, run
);
2577 qemu_mutex_lock_iothread();
2580 cpu_dump_state(cpu
, stderr
, CPU_DUMP_CODE
);
2581 vm_stop(RUN_STATE_INTERNAL_ERROR
);
2584 qatomic_set(&cpu
->exit_request
, 0);
2588 int kvm_ioctl(KVMState
*s
, int type
, ...)
2595 arg
= va_arg(ap
, void *);
2598 trace_kvm_ioctl(type
, arg
);
2599 ret
= ioctl(s
->fd
, type
, arg
);
2606 int kvm_vm_ioctl(KVMState
*s
, int type
, ...)
2613 arg
= va_arg(ap
, void *);
2616 trace_kvm_vm_ioctl(type
, arg
);
2617 ret
= ioctl(s
->vmfd
, type
, arg
);
2624 int kvm_vcpu_ioctl(CPUState
*cpu
, int type
, ...)
2631 arg
= va_arg(ap
, void *);
2634 trace_kvm_vcpu_ioctl(cpu
->cpu_index
, type
, arg
);
2635 ret
= ioctl(cpu
->kvm_fd
, type
, arg
);
2642 int kvm_device_ioctl(int fd
, int type
, ...)
2649 arg
= va_arg(ap
, void *);
2652 trace_kvm_device_ioctl(fd
, type
, arg
);
2653 ret
= ioctl(fd
, type
, arg
);
2660 int kvm_vm_check_attr(KVMState
*s
, uint32_t group
, uint64_t attr
)
2663 struct kvm_device_attr attribute
= {
2668 if (!kvm_vm_attributes_allowed
) {
2672 ret
= kvm_vm_ioctl(s
, KVM_HAS_DEVICE_ATTR
, &attribute
);
2673 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2677 int kvm_device_check_attr(int dev_fd
, uint32_t group
, uint64_t attr
)
2679 struct kvm_device_attr attribute
= {
2685 return kvm_device_ioctl(dev_fd
, KVM_HAS_DEVICE_ATTR
, &attribute
) ? 0 : 1;
2688 int kvm_device_access(int fd
, int group
, uint64_t attr
,
2689 void *val
, bool write
, Error
**errp
)
2691 struct kvm_device_attr kvmattr
;
2695 kvmattr
.group
= group
;
2696 kvmattr
.attr
= attr
;
2697 kvmattr
.addr
= (uintptr_t)val
;
2699 err
= kvm_device_ioctl(fd
,
2700 write
? KVM_SET_DEVICE_ATTR
: KVM_GET_DEVICE_ATTR
,
2703 error_setg_errno(errp
, -err
,
2704 "KVM_%s_DEVICE_ATTR failed: Group %d "
2705 "attr 0x%016" PRIx64
,
2706 write
? "SET" : "GET", group
, attr
);
2711 bool kvm_has_sync_mmu(void)
2713 return kvm_state
->sync_mmu
;
2716 int kvm_has_vcpu_events(void)
2718 return kvm_state
->vcpu_events
;
2721 int kvm_has_robust_singlestep(void)
2723 return kvm_state
->robust_singlestep
;
2726 int kvm_has_debugregs(void)
2728 return kvm_state
->debugregs
;
2731 int kvm_max_nested_state_length(void)
2733 return kvm_state
->max_nested_state_len
;
2736 int kvm_has_many_ioeventfds(void)
2738 if (!kvm_enabled()) {
2741 return kvm_state
->many_ioeventfds
;
2744 int kvm_has_gsi_routing(void)
2746 #ifdef KVM_CAP_IRQ_ROUTING
2747 return kvm_check_extension(kvm_state
, KVM_CAP_IRQ_ROUTING
);
2753 int kvm_has_intx_set_mask(void)
2755 return kvm_state
->intx_set_mask
;
2758 bool kvm_arm_supports_user_irq(void)
2760 return kvm_check_extension(kvm_state
, KVM_CAP_ARM_USER_IRQ
);
2763 #ifdef KVM_CAP_SET_GUEST_DEBUG
2764 struct kvm_sw_breakpoint
*kvm_find_sw_breakpoint(CPUState
*cpu
,
2767 struct kvm_sw_breakpoint
*bp
;
2769 QTAILQ_FOREACH(bp
, &cpu
->kvm_state
->kvm_sw_breakpoints
, entry
) {
2777 int kvm_sw_breakpoints_active(CPUState
*cpu
)
2779 return !QTAILQ_EMPTY(&cpu
->kvm_state
->kvm_sw_breakpoints
);
2782 struct kvm_set_guest_debug_data
{
2783 struct kvm_guest_debug dbg
;
2787 static void kvm_invoke_set_guest_debug(CPUState
*cpu
, run_on_cpu_data data
)
2789 struct kvm_set_guest_debug_data
*dbg_data
=
2790 (struct kvm_set_guest_debug_data
*) data
.host_ptr
;
2792 dbg_data
->err
= kvm_vcpu_ioctl(cpu
, KVM_SET_GUEST_DEBUG
,
2796 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
2798 struct kvm_set_guest_debug_data data
;
2800 data
.dbg
.control
= reinject_trap
;
2802 if (cpu
->singlestep_enabled
) {
2803 data
.dbg
.control
|= KVM_GUESTDBG_ENABLE
| KVM_GUESTDBG_SINGLESTEP
;
2805 kvm_arch_update_guest_debug(cpu
, &data
.dbg
);
2807 run_on_cpu(cpu
, kvm_invoke_set_guest_debug
,
2808 RUN_ON_CPU_HOST_PTR(&data
));
2812 int kvm_insert_breakpoint(CPUState
*cpu
, target_ulong addr
,
2813 target_ulong len
, int type
)
2815 struct kvm_sw_breakpoint
*bp
;
2818 if (type
== GDB_BREAKPOINT_SW
) {
2819 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
2825 bp
= g_malloc(sizeof(struct kvm_sw_breakpoint
));
2828 err
= kvm_arch_insert_sw_breakpoint(cpu
, bp
);
2834 QTAILQ_INSERT_HEAD(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
2836 err
= kvm_arch_insert_hw_breakpoint(addr
, len
, type
);
2843 err
= kvm_update_guest_debug(cpu
, 0);
2851 int kvm_remove_breakpoint(CPUState
*cpu
, target_ulong addr
,
2852 target_ulong len
, int type
)
2854 struct kvm_sw_breakpoint
*bp
;
2857 if (type
== GDB_BREAKPOINT_SW
) {
2858 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
2863 if (bp
->use_count
> 1) {
2868 err
= kvm_arch_remove_sw_breakpoint(cpu
, bp
);
2873 QTAILQ_REMOVE(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
2876 err
= kvm_arch_remove_hw_breakpoint(addr
, len
, type
);
2883 err
= kvm_update_guest_debug(cpu
, 0);
2891 void kvm_remove_all_breakpoints(CPUState
*cpu
)
2893 struct kvm_sw_breakpoint
*bp
, *next
;
2894 KVMState
*s
= cpu
->kvm_state
;
2897 QTAILQ_FOREACH_SAFE(bp
, &s
->kvm_sw_breakpoints
, entry
, next
) {
2898 if (kvm_arch_remove_sw_breakpoint(cpu
, bp
) != 0) {
2899 /* Try harder to find a CPU that currently sees the breakpoint. */
2900 CPU_FOREACH(tmpcpu
) {
2901 if (kvm_arch_remove_sw_breakpoint(tmpcpu
, bp
) == 0) {
2906 QTAILQ_REMOVE(&s
->kvm_sw_breakpoints
, bp
, entry
);
2909 kvm_arch_remove_all_hw_breakpoints();
2912 kvm_update_guest_debug(cpu
, 0);
2916 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2918 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
2923 int kvm_insert_breakpoint(CPUState
*cpu
, target_ulong addr
,
2924 target_ulong len
, int type
)
2929 int kvm_remove_breakpoint(CPUState
*cpu
, target_ulong addr
,
2930 target_ulong len
, int type
)
2935 void kvm_remove_all_breakpoints(CPUState
*cpu
)
2938 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2940 static int kvm_set_signal_mask(CPUState
*cpu
, const sigset_t
*sigset
)
2942 KVMState
*s
= kvm_state
;
2943 struct kvm_signal_mask
*sigmask
;
2946 sigmask
= g_malloc(sizeof(*sigmask
) + sizeof(*sigset
));
2948 sigmask
->len
= s
->sigmask_len
;
2949 memcpy(sigmask
->sigset
, sigset
, sizeof(*sigset
));
2950 r
= kvm_vcpu_ioctl(cpu
, KVM_SET_SIGNAL_MASK
, sigmask
);
2956 static void kvm_ipi_signal(int sig
)
2959 assert(kvm_immediate_exit
);
2960 kvm_cpu_kick(current_cpu
);
2964 void kvm_init_cpu_signals(CPUState
*cpu
)
2968 struct sigaction sigact
;
2970 memset(&sigact
, 0, sizeof(sigact
));
2971 sigact
.sa_handler
= kvm_ipi_signal
;
2972 sigaction(SIG_IPI
, &sigact
, NULL
);
2974 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
2975 #if defined KVM_HAVE_MCE_INJECTION
2976 sigdelset(&set
, SIGBUS
);
2977 pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
2979 sigdelset(&set
, SIG_IPI
);
2980 if (kvm_immediate_exit
) {
2981 r
= pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
2983 r
= kvm_set_signal_mask(cpu
, &set
);
2986 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(-r
));
2991 /* Called asynchronously in VCPU thread. */
2992 int kvm_on_sigbus_vcpu(CPUState
*cpu
, int code
, void *addr
)
2994 #ifdef KVM_HAVE_MCE_INJECTION
2995 if (have_sigbus_pending
) {
2998 have_sigbus_pending
= true;
2999 pending_sigbus_addr
= addr
;
3000 pending_sigbus_code
= code
;
3001 qatomic_set(&cpu
->exit_request
, 1);
3008 /* Called synchronously (via signalfd) in main thread. */
3009 int kvm_on_sigbus(int code
, void *addr
)
3011 #ifdef KVM_HAVE_MCE_INJECTION
3012 /* Action required MCE kills the process if SIGBUS is blocked. Because
3013 * that's what happens in the I/O thread, where we handle MCE via signalfd,
3014 * we can only get action optional here.
3016 assert(code
!= BUS_MCEERR_AR
);
3017 kvm_arch_on_sigbus_vcpu(first_cpu
, code
, addr
);
3024 int kvm_create_device(KVMState
*s
, uint64_t type
, bool test
)
3027 struct kvm_create_device create_dev
;
3029 create_dev
.type
= type
;
3031 create_dev
.flags
= test
? KVM_CREATE_DEVICE_TEST
: 0;
3033 if (!kvm_check_extension(s
, KVM_CAP_DEVICE_CTRL
)) {
3037 ret
= kvm_vm_ioctl(s
, KVM_CREATE_DEVICE
, &create_dev
);
3042 return test
? 0 : create_dev
.fd
;
3045 bool kvm_device_supported(int vmfd
, uint64_t type
)
3047 struct kvm_create_device create_dev
= {
3050 .flags
= KVM_CREATE_DEVICE_TEST
,
3053 if (ioctl(vmfd
, KVM_CHECK_EXTENSION
, KVM_CAP_DEVICE_CTRL
) <= 0) {
3057 return (ioctl(vmfd
, KVM_CREATE_DEVICE
, &create_dev
) >= 0);
3060 int kvm_set_one_reg(CPUState
*cs
, uint64_t id
, void *source
)
3062 struct kvm_one_reg reg
;
3066 reg
.addr
= (uintptr_t) source
;
3067 r
= kvm_vcpu_ioctl(cs
, KVM_SET_ONE_REG
, ®
);
3069 trace_kvm_failed_reg_set(id
, strerror(-r
));
3074 int kvm_get_one_reg(CPUState
*cs
, uint64_t id
, void *target
)
3076 struct kvm_one_reg reg
;
3080 reg
.addr
= (uintptr_t) target
;
3081 r
= kvm_vcpu_ioctl(cs
, KVM_GET_ONE_REG
, ®
);
3083 trace_kvm_failed_reg_get(id
, strerror(-r
));
3088 static bool kvm_accel_has_memory(MachineState
*ms
, AddressSpace
*as
,
3089 hwaddr start_addr
, hwaddr size
)
3091 KVMState
*kvm
= KVM_STATE(ms
->accelerator
);
3094 for (i
= 0; i
< kvm
->nr_as
; ++i
) {
3095 if (kvm
->as
[i
].as
== as
&& kvm
->as
[i
].ml
) {
3096 size
= MIN(kvm_max_slot_size
, size
);
3097 return NULL
!= kvm_lookup_matching_slot(kvm
->as
[i
].ml
,
3105 static void kvm_get_kvm_shadow_mem(Object
*obj
, Visitor
*v
,
3106 const char *name
, void *opaque
,
3109 KVMState
*s
= KVM_STATE(obj
);
3110 int64_t value
= s
->kvm_shadow_mem
;
3112 visit_type_int(v
, name
, &value
, errp
);
3115 static void kvm_set_kvm_shadow_mem(Object
*obj
, Visitor
*v
,
3116 const char *name
, void *opaque
,
3119 KVMState
*s
= KVM_STATE(obj
);
3122 if (!visit_type_int(v
, name
, &value
, errp
)) {
3126 s
->kvm_shadow_mem
= value
;
3129 static void kvm_set_kernel_irqchip(Object
*obj
, Visitor
*v
,
3130 const char *name
, void *opaque
,
3133 KVMState
*s
= KVM_STATE(obj
);
3136 if (!visit_type_OnOffSplit(v
, name
, &mode
, errp
)) {
3140 case ON_OFF_SPLIT_ON
:
3141 s
->kernel_irqchip_allowed
= true;
3142 s
->kernel_irqchip_required
= true;
3143 s
->kernel_irqchip_split
= ON_OFF_AUTO_OFF
;
3145 case ON_OFF_SPLIT_OFF
:
3146 s
->kernel_irqchip_allowed
= false;
3147 s
->kernel_irqchip_required
= false;
3148 s
->kernel_irqchip_split
= ON_OFF_AUTO_OFF
;
3150 case ON_OFF_SPLIT_SPLIT
:
3151 s
->kernel_irqchip_allowed
= true;
3152 s
->kernel_irqchip_required
= true;
3153 s
->kernel_irqchip_split
= ON_OFF_AUTO_ON
;
3156 /* The value was checked in visit_type_OnOffSplit() above. If
3157 * we get here, then something is wrong in QEMU.
3163 bool kvm_kernel_irqchip_allowed(void)
3165 return kvm_state
->kernel_irqchip_allowed
;
3168 bool kvm_kernel_irqchip_required(void)
3170 return kvm_state
->kernel_irqchip_required
;
3173 bool kvm_kernel_irqchip_split(void)
3175 return kvm_state
->kernel_irqchip_split
== ON_OFF_AUTO_ON
;
3178 static void kvm_accel_instance_init(Object
*obj
)
3180 KVMState
*s
= KVM_STATE(obj
);
3182 s
->kvm_shadow_mem
= -1;
3183 s
->kernel_irqchip_allowed
= true;
3184 s
->kernel_irqchip_split
= ON_OFF_AUTO_AUTO
;
3187 static void kvm_accel_class_init(ObjectClass
*oc
, void *data
)
3189 AccelClass
*ac
= ACCEL_CLASS(oc
);
3191 ac
->init_machine
= kvm_init
;
3192 ac
->has_memory
= kvm_accel_has_memory
;
3193 ac
->allowed
= &kvm_allowed
;
3195 object_class_property_add(oc
, "kernel-irqchip", "on|off|split",
3196 NULL
, kvm_set_kernel_irqchip
,
3198 object_class_property_set_description(oc
, "kernel-irqchip",
3199 "Configure KVM in-kernel irqchip");
3201 object_class_property_add(oc
, "kvm-shadow-mem", "int",
3202 kvm_get_kvm_shadow_mem
, kvm_set_kvm_shadow_mem
,
3204 object_class_property_set_description(oc
, "kvm-shadow-mem",
3205 "KVM shadow MMU size");
3208 static const TypeInfo kvm_accel_type
= {
3209 .name
= TYPE_KVM_ACCEL
,
3210 .parent
= TYPE_ACCEL
,
3211 .instance_init
= kvm_accel_instance_init
,
3212 .class_init
= kvm_accel_class_init
,
3213 .instance_size
= sizeof(KVMState
),
3216 static void kvm_type_init(void)
3218 type_register_static(&kvm_accel_type
);
3221 type_init(kvm_type_init
);