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 "qemu/bswap.h"
34 #include "exec/memory.h"
35 #include "exec/ram_addr.h"
36 #include "qemu/event_notifier.h"
37 #include "qemu/main-loop.h"
40 #include "qapi/visitor.h"
41 #include "qapi/qapi-types-common.h"
42 #include "qapi/qapi-visit-common.h"
43 #include "sysemu/reset.h"
44 #include "qemu/guest-random.h"
45 #include "sysemu/hw_accel.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.
61 #define PAGE_SIZE qemu_real_host_page_size
66 #define DPRINTF(fmt, ...) \
67 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
69 #define DPRINTF(fmt, ...) \
73 #define KVM_MSI_HASHTAB_SIZE 256
75 struct KVMParkedVcpu
{
76 unsigned long vcpu_id
;
78 QLIST_ENTRY(KVMParkedVcpu
) node
;
83 AccelState parent_obj
;
90 struct kvm_coalesced_mmio_ring
*coalesced_mmio_ring
;
91 bool coalesced_flush_in_progress
;
93 int robust_singlestep
;
95 #ifdef KVM_CAP_SET_GUEST_DEBUG
96 QTAILQ_HEAD(, kvm_sw_breakpoint
) kvm_sw_breakpoints
;
98 int max_nested_state_len
;
102 bool kernel_irqchip_allowed
;
103 bool kernel_irqchip_required
;
104 OnOffAuto kernel_irqchip_split
;
106 uint64_t manual_dirty_log_protect
;
107 /* The man page (and posix) say ioctl numbers are signed int, but
108 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
109 * unsigned, and treating them as signed here can break things */
110 unsigned irq_set_ioctl
;
111 unsigned int sigmask_len
;
113 #ifdef KVM_CAP_IRQ_ROUTING
114 struct kvm_irq_routing
*irq_routes
;
115 int nr_allocated_irq_routes
;
116 unsigned long *used_gsi_bitmap
;
117 unsigned int gsi_count
;
118 QTAILQ_HEAD(, KVMMSIRoute
) msi_hashtab
[KVM_MSI_HASHTAB_SIZE
];
120 KVMMemoryListener memory_listener
;
121 QLIST_HEAD(, KVMParkedVcpu
) kvm_parked_vcpus
;
123 /* For "info mtree -f" to tell if an MR is registered in KVM */
126 KVMMemoryListener
*ml
;
132 bool kvm_kernel_irqchip
;
133 bool kvm_split_irqchip
;
134 bool kvm_async_interrupts_allowed
;
135 bool kvm_halt_in_kernel_allowed
;
136 bool kvm_eventfds_allowed
;
137 bool kvm_irqfds_allowed
;
138 bool kvm_resamplefds_allowed
;
139 bool kvm_msi_via_irqfd_allowed
;
140 bool kvm_gsi_routing_allowed
;
141 bool kvm_gsi_direct_mapping
;
143 bool kvm_readonly_mem_allowed
;
144 bool kvm_vm_attributes_allowed
;
145 bool kvm_direct_msi_allowed
;
146 bool kvm_ioeventfd_any_length_allowed
;
147 bool kvm_msi_use_devid
;
148 static bool kvm_immediate_exit
;
149 static hwaddr kvm_max_slot_size
= ~0;
151 static const KVMCapabilityInfo kvm_required_capabilites
[] = {
152 KVM_CAP_INFO(USER_MEMORY
),
153 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS
),
154 KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS
),
158 static NotifierList kvm_irqchip_change_notifiers
=
159 NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers
);
161 struct KVMResampleFd
{
163 EventNotifier
*resample_event
;
164 QLIST_ENTRY(KVMResampleFd
) node
;
166 typedef struct KVMResampleFd KVMResampleFd
;
169 * Only used with split irqchip where we need to do the resample fd
170 * kick for the kernel from userspace.
172 static QLIST_HEAD(, KVMResampleFd
) kvm_resample_fd_list
=
173 QLIST_HEAD_INITIALIZER(kvm_resample_fd_list
);
175 #define kvm_slots_lock(kml) qemu_mutex_lock(&(kml)->slots_lock)
176 #define kvm_slots_unlock(kml) qemu_mutex_unlock(&(kml)->slots_lock)
178 static inline void kvm_resample_fd_remove(int gsi
)
182 QLIST_FOREACH(rfd
, &kvm_resample_fd_list
, node
) {
183 if (rfd
->gsi
== gsi
) {
184 QLIST_REMOVE(rfd
, node
);
191 static inline void kvm_resample_fd_insert(int gsi
, EventNotifier
*event
)
193 KVMResampleFd
*rfd
= g_new0(KVMResampleFd
, 1);
196 rfd
->resample_event
= event
;
198 QLIST_INSERT_HEAD(&kvm_resample_fd_list
, rfd
, node
);
201 void kvm_resample_fd_notify(int gsi
)
205 QLIST_FOREACH(rfd
, &kvm_resample_fd_list
, node
) {
206 if (rfd
->gsi
== gsi
) {
207 event_notifier_set(rfd
->resample_event
);
208 trace_kvm_resample_fd_notify(gsi
);
214 int kvm_get_max_memslots(void)
216 KVMState
*s
= KVM_STATE(current_accel());
221 /* Called with KVMMemoryListener.slots_lock held */
222 static KVMSlot
*kvm_get_free_slot(KVMMemoryListener
*kml
)
224 KVMState
*s
= kvm_state
;
227 for (i
= 0; i
< s
->nr_slots
; i
++) {
228 if (kml
->slots
[i
].memory_size
== 0) {
229 return &kml
->slots
[i
];
236 bool kvm_has_free_slot(MachineState
*ms
)
238 KVMState
*s
= KVM_STATE(ms
->accelerator
);
240 KVMMemoryListener
*kml
= &s
->memory_listener
;
243 result
= !!kvm_get_free_slot(kml
);
244 kvm_slots_unlock(kml
);
249 /* Called with KVMMemoryListener.slots_lock held */
250 static KVMSlot
*kvm_alloc_slot(KVMMemoryListener
*kml
)
252 KVMSlot
*slot
= kvm_get_free_slot(kml
);
258 fprintf(stderr
, "%s: no free slot available\n", __func__
);
262 static KVMSlot
*kvm_lookup_matching_slot(KVMMemoryListener
*kml
,
266 KVMState
*s
= kvm_state
;
269 for (i
= 0; i
< s
->nr_slots
; i
++) {
270 KVMSlot
*mem
= &kml
->slots
[i
];
272 if (start_addr
== mem
->start_addr
&& size
== mem
->memory_size
) {
281 * Calculate and align the start address and the size of the section.
282 * Return the size. If the size is 0, the aligned section is empty.
284 static hwaddr
kvm_align_section(MemoryRegionSection
*section
,
287 hwaddr size
= int128_get64(section
->size
);
288 hwaddr delta
, aligned
;
290 /* kvm works in page size chunks, but the function may be called
291 with sub-page size and unaligned start address. Pad the start
292 address to next and truncate size to previous page boundary. */
293 aligned
= ROUND_UP(section
->offset_within_address_space
,
294 qemu_real_host_page_size
);
295 delta
= aligned
- section
->offset_within_address_space
;
301 return (size
- delta
) & qemu_real_host_page_mask
;
304 int kvm_physical_memory_addr_from_host(KVMState
*s
, void *ram
,
307 KVMMemoryListener
*kml
= &s
->memory_listener
;
311 for (i
= 0; i
< s
->nr_slots
; i
++) {
312 KVMSlot
*mem
= &kml
->slots
[i
];
314 if (ram
>= mem
->ram
&& ram
< mem
->ram
+ mem
->memory_size
) {
315 *phys_addr
= mem
->start_addr
+ (ram
- mem
->ram
);
320 kvm_slots_unlock(kml
);
325 static int kvm_set_user_memory_region(KVMMemoryListener
*kml
, KVMSlot
*slot
, bool new)
327 KVMState
*s
= kvm_state
;
328 struct kvm_userspace_memory_region mem
;
331 mem
.slot
= slot
->slot
| (kml
->as_id
<< 16);
332 mem
.guest_phys_addr
= slot
->start_addr
;
333 mem
.userspace_addr
= (unsigned long)slot
->ram
;
334 mem
.flags
= slot
->flags
;
336 if (slot
->memory_size
&& !new && (mem
.flags
^ slot
->old_flags
) & KVM_MEM_READONLY
) {
337 /* Set the slot size to 0 before setting the slot to the desired
338 * value. This is needed based on KVM commit 75d61fbc. */
340 ret
= kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
345 mem
.memory_size
= slot
->memory_size
;
346 ret
= kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
347 slot
->old_flags
= mem
.flags
;
349 trace_kvm_set_user_memory(mem
.slot
, mem
.flags
, mem
.guest_phys_addr
,
350 mem
.memory_size
, mem
.userspace_addr
, ret
);
352 error_report("%s: KVM_SET_USER_MEMORY_REGION failed, slot=%d,"
353 " start=0x%" PRIx64
", size=0x%" PRIx64
": %s",
354 __func__
, mem
.slot
, slot
->start_addr
,
355 (uint64_t)mem
.memory_size
, strerror(errno
));
360 static int do_kvm_destroy_vcpu(CPUState
*cpu
)
362 KVMState
*s
= kvm_state
;
364 struct KVMParkedVcpu
*vcpu
= NULL
;
367 DPRINTF("kvm_destroy_vcpu\n");
369 ret
= kvm_arch_destroy_vcpu(cpu
);
374 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
377 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
381 ret
= munmap(cpu
->kvm_run
, mmap_size
);
386 vcpu
= g_malloc0(sizeof(*vcpu
));
387 vcpu
->vcpu_id
= kvm_arch_vcpu_id(cpu
);
388 vcpu
->kvm_fd
= cpu
->kvm_fd
;
389 QLIST_INSERT_HEAD(&kvm_state
->kvm_parked_vcpus
, vcpu
, node
);
394 void kvm_destroy_vcpu(CPUState
*cpu
)
396 if (do_kvm_destroy_vcpu(cpu
) < 0) {
397 error_report("kvm_destroy_vcpu failed");
402 static int kvm_get_vcpu(KVMState
*s
, unsigned long vcpu_id
)
404 struct KVMParkedVcpu
*cpu
;
406 QLIST_FOREACH(cpu
, &s
->kvm_parked_vcpus
, node
) {
407 if (cpu
->vcpu_id
== vcpu_id
) {
410 QLIST_REMOVE(cpu
, node
);
411 kvm_fd
= cpu
->kvm_fd
;
417 return kvm_vm_ioctl(s
, KVM_CREATE_VCPU
, (void *)vcpu_id
);
420 int kvm_init_vcpu(CPUState
*cpu
, Error
**errp
)
422 KVMState
*s
= kvm_state
;
426 trace_kvm_init_vcpu(cpu
->cpu_index
, kvm_arch_vcpu_id(cpu
));
428 ret
= kvm_get_vcpu(s
, kvm_arch_vcpu_id(cpu
));
430 error_setg_errno(errp
, -ret
, "kvm_init_vcpu: kvm_get_vcpu failed (%lu)",
431 kvm_arch_vcpu_id(cpu
));
437 cpu
->vcpu_dirty
= true;
439 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
442 error_setg_errno(errp
, -mmap_size
,
443 "kvm_init_vcpu: KVM_GET_VCPU_MMAP_SIZE failed");
447 cpu
->kvm_run
= mmap(NULL
, mmap_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
449 if (cpu
->kvm_run
== MAP_FAILED
) {
451 error_setg_errno(errp
, ret
,
452 "kvm_init_vcpu: mmap'ing vcpu state failed (%lu)",
453 kvm_arch_vcpu_id(cpu
));
457 if (s
->coalesced_mmio
&& !s
->coalesced_mmio_ring
) {
458 s
->coalesced_mmio_ring
=
459 (void *)cpu
->kvm_run
+ s
->coalesced_mmio
* PAGE_SIZE
;
462 ret
= kvm_arch_init_vcpu(cpu
);
464 error_setg_errno(errp
, -ret
,
465 "kvm_init_vcpu: kvm_arch_init_vcpu failed (%lu)",
466 kvm_arch_vcpu_id(cpu
));
473 * dirty pages logging control
476 static int kvm_mem_flags(MemoryRegion
*mr
)
478 bool readonly
= mr
->readonly
|| memory_region_is_romd(mr
);
481 if (memory_region_get_dirty_log_mask(mr
) != 0) {
482 flags
|= KVM_MEM_LOG_DIRTY_PAGES
;
484 if (readonly
&& kvm_readonly_mem_allowed
) {
485 flags
|= KVM_MEM_READONLY
;
490 /* Called with KVMMemoryListener.slots_lock held */
491 static int kvm_slot_update_flags(KVMMemoryListener
*kml
, KVMSlot
*mem
,
494 mem
->flags
= kvm_mem_flags(mr
);
496 /* If nothing changed effectively, no need to issue ioctl */
497 if (mem
->flags
== mem
->old_flags
) {
501 return kvm_set_user_memory_region(kml
, mem
, false);
504 static int kvm_section_update_flags(KVMMemoryListener
*kml
,
505 MemoryRegionSection
*section
)
507 hwaddr start_addr
, size
, slot_size
;
511 size
= kvm_align_section(section
, &start_addr
);
518 while (size
&& !ret
) {
519 slot_size
= MIN(kvm_max_slot_size
, size
);
520 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
522 /* We don't have a slot if we want to trap every access. */
526 ret
= kvm_slot_update_flags(kml
, mem
, section
->mr
);
527 start_addr
+= slot_size
;
532 kvm_slots_unlock(kml
);
536 static void kvm_log_start(MemoryListener
*listener
,
537 MemoryRegionSection
*section
,
540 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
547 r
= kvm_section_update_flags(kml
, section
);
553 static void kvm_log_stop(MemoryListener
*listener
,
554 MemoryRegionSection
*section
,
557 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
564 r
= kvm_section_update_flags(kml
, section
);
570 /* get kvm's dirty pages bitmap and update qemu's */
571 static int kvm_get_dirty_pages_log_range(MemoryRegionSection
*section
,
572 unsigned long *bitmap
)
574 ram_addr_t start
= section
->offset_within_region
+
575 memory_region_get_ram_addr(section
->mr
);
576 ram_addr_t pages
= int128_get64(section
->size
) / qemu_real_host_page_size
;
578 cpu_physical_memory_set_dirty_lebitmap(bitmap
, start
, pages
);
582 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
584 /* Allocate the dirty bitmap for a slot */
585 static void kvm_memslot_init_dirty_bitmap(KVMSlot
*mem
)
588 * XXX bad kernel interface alert
589 * For dirty bitmap, kernel allocates array of size aligned to
590 * bits-per-long. But for case when the kernel is 64bits and
591 * the userspace is 32bits, userspace can't align to the same
592 * bits-per-long, since sizeof(long) is different between kernel
593 * and user space. This way, userspace will provide buffer which
594 * may be 4 bytes less than the kernel will use, resulting in
595 * userspace memory corruption (which is not detectable by valgrind
596 * too, in most cases).
597 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
598 * a hope that sizeof(long) won't become >8 any time soon.
600 * Note: the granule of kvm dirty log is qemu_real_host_page_size.
601 * And mem->memory_size is aligned to it (otherwise this mem can't
602 * be registered to KVM).
604 hwaddr bitmap_size
= ALIGN(mem
->memory_size
/ qemu_real_host_page_size
,
605 /*HOST_LONG_BITS*/ 64) / 8;
606 mem
->dirty_bmap
= g_malloc0(bitmap_size
);
610 * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
612 * This function will first try to fetch dirty bitmap from the kernel,
613 * and then updates qemu's dirty bitmap.
615 * NOTE: caller must be with kml->slots_lock held.
617 * @kml: the KVM memory listener object
618 * @section: the memory section to sync the dirty bitmap with
620 static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener
*kml
,
621 MemoryRegionSection
*section
)
623 KVMState
*s
= kvm_state
;
624 struct kvm_dirty_log d
= {};
626 hwaddr start_addr
, size
;
627 hwaddr slot_size
, slot_offset
= 0;
630 size
= kvm_align_section(section
, &start_addr
);
632 MemoryRegionSection subsection
= *section
;
634 slot_size
= MIN(kvm_max_slot_size
, size
);
635 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
637 /* We don't have a slot if we want to trap every access. */
641 if (!mem
->dirty_bmap
) {
642 /* Allocate on the first log_sync, once and for all */
643 kvm_memslot_init_dirty_bitmap(mem
);
646 d
.dirty_bitmap
= mem
->dirty_bmap
;
647 d
.slot
= mem
->slot
| (kml
->as_id
<< 16);
648 ret
= kvm_vm_ioctl(s
, KVM_GET_DIRTY_LOG
, &d
);
649 if (ret
== -ENOENT
) {
650 /* kernel does not have dirty bitmap in this slot */
652 } else if (ret
< 0) {
653 error_report("ioctl KVM_GET_DIRTY_LOG failed: %d", errno
);
656 subsection
.offset_within_region
+= slot_offset
;
657 subsection
.size
= int128_make64(slot_size
);
658 kvm_get_dirty_pages_log_range(&subsection
, d
.dirty_bitmap
);
661 slot_offset
+= slot_size
;
662 start_addr
+= slot_size
;
669 /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
670 #define KVM_CLEAR_LOG_SHIFT 6
671 #define KVM_CLEAR_LOG_ALIGN (qemu_real_host_page_size << KVM_CLEAR_LOG_SHIFT)
672 #define KVM_CLEAR_LOG_MASK (-KVM_CLEAR_LOG_ALIGN)
674 static int kvm_log_clear_one_slot(KVMSlot
*mem
, int as_id
, uint64_t start
,
677 KVMState
*s
= kvm_state
;
678 uint64_t end
, bmap_start
, start_delta
, bmap_npages
;
679 struct kvm_clear_dirty_log d
;
680 unsigned long *bmap_clear
= NULL
, psize
= qemu_real_host_page_size
;
684 * We need to extend either the start or the size or both to
685 * satisfy the KVM interface requirement. Firstly, do the start
686 * page alignment on 64 host pages
688 bmap_start
= start
& KVM_CLEAR_LOG_MASK
;
689 start_delta
= start
- bmap_start
;
693 * The kernel interface has restriction on the size too, that either:
695 * (1) the size is 64 host pages aligned (just like the start), or
696 * (2) the size fills up until the end of the KVM memslot.
698 bmap_npages
= DIV_ROUND_UP(size
+ start_delta
, KVM_CLEAR_LOG_ALIGN
)
699 << KVM_CLEAR_LOG_SHIFT
;
700 end
= mem
->memory_size
/ psize
;
701 if (bmap_npages
> end
- bmap_start
) {
702 bmap_npages
= end
- bmap_start
;
704 start_delta
/= psize
;
707 * Prepare the bitmap to clear dirty bits. Here we must guarantee
708 * that we won't clear any unknown dirty bits otherwise we might
709 * accidentally clear some set bits which are not yet synced from
710 * the kernel into QEMU's bitmap, then we'll lose track of the
711 * guest modifications upon those pages (which can directly lead
712 * to guest data loss or panic after migration).
714 * Layout of the KVMSlot.dirty_bmap:
716 * |<-------- bmap_npages -----------..>|
719 * |----------------|-------------|------------------|------------|
722 * start bmap_start (start) end
723 * of memslot of memslot
725 * [1] bmap_npages can be aligned to either 64 pages or the end of slot
728 assert(bmap_start
% BITS_PER_LONG
== 0);
729 /* We should never do log_clear before log_sync */
730 assert(mem
->dirty_bmap
);
731 if (start_delta
|| bmap_npages
- size
/ psize
) {
732 /* Slow path - we need to manipulate a temp bitmap */
733 bmap_clear
= bitmap_new(bmap_npages
);
734 bitmap_copy_with_src_offset(bmap_clear
, mem
->dirty_bmap
,
735 bmap_start
, start_delta
+ size
/ psize
);
737 * We need to fill the holes at start because that was not
738 * specified by the caller and we extended the bitmap only for
741 bitmap_clear(bmap_clear
, 0, start_delta
);
742 d
.dirty_bitmap
= bmap_clear
;
745 * Fast path - both start and size align well with BITS_PER_LONG
746 * (or the end of memory slot)
748 d
.dirty_bitmap
= mem
->dirty_bmap
+ BIT_WORD(bmap_start
);
751 d
.first_page
= bmap_start
;
752 /* It should never overflow. If it happens, say something */
753 assert(bmap_npages
<= UINT32_MAX
);
754 d
.num_pages
= bmap_npages
;
755 d
.slot
= mem
->slot
| (as_id
<< 16);
757 ret
= kvm_vm_ioctl(s
, KVM_CLEAR_DIRTY_LOG
, &d
);
758 if (ret
< 0 && ret
!= -ENOENT
) {
759 error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
760 "start=0x%"PRIx64
", size=0x%"PRIx32
", errno=%d",
761 __func__
, d
.slot
, (uint64_t)d
.first_page
,
762 (uint32_t)d
.num_pages
, ret
);
765 trace_kvm_clear_dirty_log(d
.slot
, d
.first_page
, d
.num_pages
);
769 * After we have updated the remote dirty bitmap, we update the
770 * cached bitmap as well for the memslot, then if another user
771 * clears the same region we know we shouldn't clear it again on
772 * the remote otherwise it's data loss as well.
774 bitmap_clear(mem
->dirty_bmap
, bmap_start
+ start_delta
,
776 /* This handles the NULL case well */
783 * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
785 * NOTE: this will be a no-op if we haven't enabled manual dirty log
786 * protection in the host kernel because in that case this operation
787 * will be done within log_sync().
789 * @kml: the kvm memory listener
790 * @section: the memory range to clear dirty bitmap
792 static int kvm_physical_log_clear(KVMMemoryListener
*kml
,
793 MemoryRegionSection
*section
)
795 KVMState
*s
= kvm_state
;
796 uint64_t start
, size
, offset
, count
;
800 if (!s
->manual_dirty_log_protect
) {
801 /* No need to do explicit clear */
805 start
= section
->offset_within_address_space
;
806 size
= int128_get64(section
->size
);
809 /* Nothing more we can do... */
815 for (i
= 0; i
< s
->nr_slots
; i
++) {
816 mem
= &kml
->slots
[i
];
817 /* Discard slots that are empty or do not overlap the section */
818 if (!mem
->memory_size
||
819 mem
->start_addr
> start
+ size
- 1 ||
820 start
> mem
->start_addr
+ mem
->memory_size
- 1) {
824 if (start
>= mem
->start_addr
) {
825 /* The slot starts before section or is aligned to it. */
826 offset
= start
- mem
->start_addr
;
827 count
= MIN(mem
->memory_size
- offset
, size
);
829 /* The slot starts after section. */
831 count
= MIN(mem
->memory_size
, size
- (mem
->start_addr
- start
));
833 ret
= kvm_log_clear_one_slot(mem
, kml
->as_id
, offset
, count
);
839 kvm_slots_unlock(kml
);
844 static void kvm_coalesce_mmio_region(MemoryListener
*listener
,
845 MemoryRegionSection
*secion
,
846 hwaddr start
, hwaddr size
)
848 KVMState
*s
= kvm_state
;
850 if (s
->coalesced_mmio
) {
851 struct kvm_coalesced_mmio_zone zone
;
857 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
861 static void kvm_uncoalesce_mmio_region(MemoryListener
*listener
,
862 MemoryRegionSection
*secion
,
863 hwaddr start
, hwaddr size
)
865 KVMState
*s
= kvm_state
;
867 if (s
->coalesced_mmio
) {
868 struct kvm_coalesced_mmio_zone zone
;
874 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
878 static void kvm_coalesce_pio_add(MemoryListener
*listener
,
879 MemoryRegionSection
*section
,
880 hwaddr start
, hwaddr size
)
882 KVMState
*s
= kvm_state
;
884 if (s
->coalesced_pio
) {
885 struct kvm_coalesced_mmio_zone zone
;
891 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
895 static void kvm_coalesce_pio_del(MemoryListener
*listener
,
896 MemoryRegionSection
*section
,
897 hwaddr start
, hwaddr size
)
899 KVMState
*s
= kvm_state
;
901 if (s
->coalesced_pio
) {
902 struct kvm_coalesced_mmio_zone zone
;
908 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
912 static MemoryListener kvm_coalesced_pio_listener
= {
913 .coalesced_io_add
= kvm_coalesce_pio_add
,
914 .coalesced_io_del
= kvm_coalesce_pio_del
,
917 int kvm_check_extension(KVMState
*s
, unsigned int extension
)
921 ret
= kvm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
929 int kvm_vm_check_extension(KVMState
*s
, unsigned int extension
)
933 ret
= kvm_vm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
935 /* VM wide version not implemented, use global one instead */
936 ret
= kvm_check_extension(s
, extension
);
942 typedef struct HWPoisonPage
{
944 QLIST_ENTRY(HWPoisonPage
) list
;
947 static QLIST_HEAD(, HWPoisonPage
) hwpoison_page_list
=
948 QLIST_HEAD_INITIALIZER(hwpoison_page_list
);
950 static void kvm_unpoison_all(void *param
)
952 HWPoisonPage
*page
, *next_page
;
954 QLIST_FOREACH_SAFE(page
, &hwpoison_page_list
, list
, next_page
) {
955 QLIST_REMOVE(page
, list
);
956 qemu_ram_remap(page
->ram_addr
, TARGET_PAGE_SIZE
);
961 void kvm_hwpoison_page_add(ram_addr_t ram_addr
)
965 QLIST_FOREACH(page
, &hwpoison_page_list
, list
) {
966 if (page
->ram_addr
== ram_addr
) {
970 page
= g_new(HWPoisonPage
, 1);
971 page
->ram_addr
= ram_addr
;
972 QLIST_INSERT_HEAD(&hwpoison_page_list
, page
, list
);
975 static uint32_t adjust_ioeventfd_endianness(uint32_t val
, uint32_t size
)
977 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
978 /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
979 * endianness, but the memory core hands them in target endianness.
980 * For example, PPC is always treated as big-endian even if running
981 * on KVM and on PPC64LE. Correct here.
995 static int kvm_set_ioeventfd_mmio(int fd
, hwaddr addr
, uint32_t val
,
996 bool assign
, uint32_t size
, bool datamatch
)
999 struct kvm_ioeventfd iofd
= {
1000 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
1007 trace_kvm_set_ioeventfd_mmio(fd
, (uint64_t)addr
, val
, assign
, size
,
1009 if (!kvm_enabled()) {
1014 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
1017 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
1020 ret
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &iofd
);
1029 static int kvm_set_ioeventfd_pio(int fd
, uint16_t addr
, uint16_t val
,
1030 bool assign
, uint32_t size
, bool datamatch
)
1032 struct kvm_ioeventfd kick
= {
1033 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
1035 .flags
= KVM_IOEVENTFD_FLAG_PIO
,
1040 trace_kvm_set_ioeventfd_pio(fd
, addr
, val
, assign
, size
, datamatch
);
1041 if (!kvm_enabled()) {
1045 kick
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
1048 kick
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
1050 r
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &kick
);
1058 static int kvm_check_many_ioeventfds(void)
1060 /* Userspace can use ioeventfd for io notification. This requires a host
1061 * that supports eventfd(2) and an I/O thread; since eventfd does not
1062 * support SIGIO it cannot interrupt the vcpu.
1064 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
1065 * can avoid creating too many ioeventfds.
1067 #if defined(CONFIG_EVENTFD)
1070 for (i
= 0; i
< ARRAY_SIZE(ioeventfds
); i
++) {
1071 ioeventfds
[i
] = eventfd(0, EFD_CLOEXEC
);
1072 if (ioeventfds
[i
] < 0) {
1075 ret
= kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, true, 2, true);
1077 close(ioeventfds
[i
]);
1082 /* Decide whether many devices are supported or not */
1083 ret
= i
== ARRAY_SIZE(ioeventfds
);
1086 kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, false, 2, true);
1087 close(ioeventfds
[i
]);
1095 static const KVMCapabilityInfo
*
1096 kvm_check_extension_list(KVMState
*s
, const KVMCapabilityInfo
*list
)
1098 while (list
->name
) {
1099 if (!kvm_check_extension(s
, list
->value
)) {
1107 void kvm_set_max_memslot_size(hwaddr max_slot_size
)
1110 ROUND_UP(max_slot_size
, qemu_real_host_page_size
) == max_slot_size
1112 kvm_max_slot_size
= max_slot_size
;
1115 static void kvm_set_phys_mem(KVMMemoryListener
*kml
,
1116 MemoryRegionSection
*section
, bool add
)
1120 MemoryRegion
*mr
= section
->mr
;
1121 bool writeable
= !mr
->readonly
&& !mr
->rom_device
;
1122 hwaddr start_addr
, size
, slot_size
;
1125 if (!memory_region_is_ram(mr
)) {
1126 if (writeable
|| !kvm_readonly_mem_allowed
) {
1128 } else if (!mr
->romd_mode
) {
1129 /* If the memory device is not in romd_mode, then we actually want
1130 * to remove the kvm memory slot so all accesses will trap. */
1135 size
= kvm_align_section(section
, &start_addr
);
1140 /* use aligned delta to align the ram address */
1141 ram
= memory_region_get_ram_ptr(mr
) + section
->offset_within_region
+
1142 (start_addr
- section
->offset_within_address_space
);
1144 kvm_slots_lock(kml
);
1148 slot_size
= MIN(kvm_max_slot_size
, size
);
1149 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
1153 if (mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
1154 kvm_physical_sync_dirty_bitmap(kml
, section
);
1157 /* unregister the slot */
1158 g_free(mem
->dirty_bmap
);
1159 mem
->dirty_bmap
= NULL
;
1160 mem
->memory_size
= 0;
1162 err
= kvm_set_user_memory_region(kml
, mem
, false);
1164 fprintf(stderr
, "%s: error unregistering slot: %s\n",
1165 __func__
, strerror(-err
));
1168 start_addr
+= slot_size
;
1174 /* register the new slot */
1176 slot_size
= MIN(kvm_max_slot_size
, size
);
1177 mem
= kvm_alloc_slot(kml
);
1178 mem
->memory_size
= slot_size
;
1179 mem
->start_addr
= start_addr
;
1181 mem
->flags
= kvm_mem_flags(mr
);
1183 if (mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
1185 * Reallocate the bmap; it means it doesn't disappear in
1186 * middle of a migrate.
1188 kvm_memslot_init_dirty_bitmap(mem
);
1190 err
= kvm_set_user_memory_region(kml
, mem
, true);
1192 fprintf(stderr
, "%s: error registering slot: %s\n", __func__
,
1196 start_addr
+= slot_size
;
1202 kvm_slots_unlock(kml
);
1205 static void kvm_region_add(MemoryListener
*listener
,
1206 MemoryRegionSection
*section
)
1208 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1210 memory_region_ref(section
->mr
);
1211 kvm_set_phys_mem(kml
, section
, true);
1214 static void kvm_region_del(MemoryListener
*listener
,
1215 MemoryRegionSection
*section
)
1217 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1219 kvm_set_phys_mem(kml
, section
, false);
1220 memory_region_unref(section
->mr
);
1223 static void kvm_log_sync(MemoryListener
*listener
,
1224 MemoryRegionSection
*section
)
1226 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1229 kvm_slots_lock(kml
);
1230 r
= kvm_physical_sync_dirty_bitmap(kml
, section
);
1231 kvm_slots_unlock(kml
);
1237 static void kvm_log_clear(MemoryListener
*listener
,
1238 MemoryRegionSection
*section
)
1240 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1243 r
= kvm_physical_log_clear(kml
, section
);
1245 error_report_once("%s: kvm log clear failed: mr=%s "
1246 "offset=%"HWADDR_PRIx
" size=%"PRIx64
, __func__
,
1247 section
->mr
->name
, section
->offset_within_region
,
1248 int128_get64(section
->size
));
1253 static void kvm_mem_ioeventfd_add(MemoryListener
*listener
,
1254 MemoryRegionSection
*section
,
1255 bool match_data
, uint64_t data
,
1258 int fd
= event_notifier_get_fd(e
);
1261 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
1262 data
, true, int128_get64(section
->size
),
1265 fprintf(stderr
, "%s: error adding ioeventfd: %s (%d)\n",
1266 __func__
, strerror(-r
), -r
);
1271 static void kvm_mem_ioeventfd_del(MemoryListener
*listener
,
1272 MemoryRegionSection
*section
,
1273 bool match_data
, uint64_t data
,
1276 int fd
= event_notifier_get_fd(e
);
1279 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
1280 data
, false, int128_get64(section
->size
),
1283 fprintf(stderr
, "%s: error deleting ioeventfd: %s (%d)\n",
1284 __func__
, strerror(-r
), -r
);
1289 static void kvm_io_ioeventfd_add(MemoryListener
*listener
,
1290 MemoryRegionSection
*section
,
1291 bool match_data
, uint64_t data
,
1294 int fd
= event_notifier_get_fd(e
);
1297 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
1298 data
, true, int128_get64(section
->size
),
1301 fprintf(stderr
, "%s: error adding ioeventfd: %s (%d)\n",
1302 __func__
, strerror(-r
), -r
);
1307 static void kvm_io_ioeventfd_del(MemoryListener
*listener
,
1308 MemoryRegionSection
*section
,
1309 bool match_data
, uint64_t data
,
1313 int fd
= event_notifier_get_fd(e
);
1316 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
1317 data
, false, int128_get64(section
->size
),
1320 fprintf(stderr
, "%s: error deleting ioeventfd: %s (%d)\n",
1321 __func__
, strerror(-r
), -r
);
1326 void kvm_memory_listener_register(KVMState
*s
, KVMMemoryListener
*kml
,
1327 AddressSpace
*as
, int as_id
)
1331 qemu_mutex_init(&kml
->slots_lock
);
1332 kml
->slots
= g_malloc0(s
->nr_slots
* sizeof(KVMSlot
));
1335 for (i
= 0; i
< s
->nr_slots
; i
++) {
1336 kml
->slots
[i
].slot
= i
;
1339 kml
->listener
.region_add
= kvm_region_add
;
1340 kml
->listener
.region_del
= kvm_region_del
;
1341 kml
->listener
.log_start
= kvm_log_start
;
1342 kml
->listener
.log_stop
= kvm_log_stop
;
1343 kml
->listener
.log_sync
= kvm_log_sync
;
1344 kml
->listener
.log_clear
= kvm_log_clear
;
1345 kml
->listener
.priority
= 10;
1347 memory_listener_register(&kml
->listener
, as
);
1349 for (i
= 0; i
< s
->nr_as
; ++i
) {
1358 static MemoryListener kvm_io_listener
= {
1359 .eventfd_add
= kvm_io_ioeventfd_add
,
1360 .eventfd_del
= kvm_io_ioeventfd_del
,
1364 int kvm_set_irq(KVMState
*s
, int irq
, int level
)
1366 struct kvm_irq_level event
;
1369 assert(kvm_async_interrupts_enabled());
1371 event
.level
= level
;
1373 ret
= kvm_vm_ioctl(s
, s
->irq_set_ioctl
, &event
);
1375 perror("kvm_set_irq");
1379 return (s
->irq_set_ioctl
== KVM_IRQ_LINE
) ? 1 : event
.status
;
1382 #ifdef KVM_CAP_IRQ_ROUTING
1383 typedef struct KVMMSIRoute
{
1384 struct kvm_irq_routing_entry kroute
;
1385 QTAILQ_ENTRY(KVMMSIRoute
) entry
;
1388 static void set_gsi(KVMState
*s
, unsigned int gsi
)
1390 set_bit(gsi
, s
->used_gsi_bitmap
);
1393 static void clear_gsi(KVMState
*s
, unsigned int gsi
)
1395 clear_bit(gsi
, s
->used_gsi_bitmap
);
1398 void kvm_init_irq_routing(KVMState
*s
)
1402 gsi_count
= kvm_check_extension(s
, KVM_CAP_IRQ_ROUTING
) - 1;
1403 if (gsi_count
> 0) {
1404 /* Round up so we can search ints using ffs */
1405 s
->used_gsi_bitmap
= bitmap_new(gsi_count
);
1406 s
->gsi_count
= gsi_count
;
1409 s
->irq_routes
= g_malloc0(sizeof(*s
->irq_routes
));
1410 s
->nr_allocated_irq_routes
= 0;
1412 if (!kvm_direct_msi_allowed
) {
1413 for (i
= 0; i
< KVM_MSI_HASHTAB_SIZE
; i
++) {
1414 QTAILQ_INIT(&s
->msi_hashtab
[i
]);
1418 kvm_arch_init_irq_routing(s
);
1421 void kvm_irqchip_commit_routes(KVMState
*s
)
1425 if (kvm_gsi_direct_mapping()) {
1429 if (!kvm_gsi_routing_enabled()) {
1433 s
->irq_routes
->flags
= 0;
1434 trace_kvm_irqchip_commit_routes();
1435 ret
= kvm_vm_ioctl(s
, KVM_SET_GSI_ROUTING
, s
->irq_routes
);
1439 static void kvm_add_routing_entry(KVMState
*s
,
1440 struct kvm_irq_routing_entry
*entry
)
1442 struct kvm_irq_routing_entry
*new;
1445 if (s
->irq_routes
->nr
== s
->nr_allocated_irq_routes
) {
1446 n
= s
->nr_allocated_irq_routes
* 2;
1450 size
= sizeof(struct kvm_irq_routing
);
1451 size
+= n
* sizeof(*new);
1452 s
->irq_routes
= g_realloc(s
->irq_routes
, size
);
1453 s
->nr_allocated_irq_routes
= n
;
1455 n
= s
->irq_routes
->nr
++;
1456 new = &s
->irq_routes
->entries
[n
];
1460 set_gsi(s
, entry
->gsi
);
1463 static int kvm_update_routing_entry(KVMState
*s
,
1464 struct kvm_irq_routing_entry
*new_entry
)
1466 struct kvm_irq_routing_entry
*entry
;
1469 for (n
= 0; n
< s
->irq_routes
->nr
; n
++) {
1470 entry
= &s
->irq_routes
->entries
[n
];
1471 if (entry
->gsi
!= new_entry
->gsi
) {
1475 if(!memcmp(entry
, new_entry
, sizeof *entry
)) {
1479 *entry
= *new_entry
;
1487 void kvm_irqchip_add_irq_route(KVMState
*s
, int irq
, int irqchip
, int pin
)
1489 struct kvm_irq_routing_entry e
= {};
1491 assert(pin
< s
->gsi_count
);
1494 e
.type
= KVM_IRQ_ROUTING_IRQCHIP
;
1496 e
.u
.irqchip
.irqchip
= irqchip
;
1497 e
.u
.irqchip
.pin
= pin
;
1498 kvm_add_routing_entry(s
, &e
);
1501 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
1503 struct kvm_irq_routing_entry
*e
;
1506 if (kvm_gsi_direct_mapping()) {
1510 for (i
= 0; i
< s
->irq_routes
->nr
; i
++) {
1511 e
= &s
->irq_routes
->entries
[i
];
1512 if (e
->gsi
== virq
) {
1513 s
->irq_routes
->nr
--;
1514 *e
= s
->irq_routes
->entries
[s
->irq_routes
->nr
];
1518 kvm_arch_release_virq_post(virq
);
1519 trace_kvm_irqchip_release_virq(virq
);
1522 void kvm_irqchip_add_change_notifier(Notifier
*n
)
1524 notifier_list_add(&kvm_irqchip_change_notifiers
, n
);
1527 void kvm_irqchip_remove_change_notifier(Notifier
*n
)
1532 void kvm_irqchip_change_notify(void)
1534 notifier_list_notify(&kvm_irqchip_change_notifiers
, NULL
);
1537 static unsigned int kvm_hash_msi(uint32_t data
)
1539 /* This is optimized for IA32 MSI layout. However, no other arch shall
1540 * repeat the mistake of not providing a direct MSI injection API. */
1544 static void kvm_flush_dynamic_msi_routes(KVMState
*s
)
1546 KVMMSIRoute
*route
, *next
;
1549 for (hash
= 0; hash
< KVM_MSI_HASHTAB_SIZE
; hash
++) {
1550 QTAILQ_FOREACH_SAFE(route
, &s
->msi_hashtab
[hash
], entry
, next
) {
1551 kvm_irqchip_release_virq(s
, route
->kroute
.gsi
);
1552 QTAILQ_REMOVE(&s
->msi_hashtab
[hash
], route
, entry
);
1558 static int kvm_irqchip_get_virq(KVMState
*s
)
1563 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1564 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1565 * number can succeed even though a new route entry cannot be added.
1566 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1568 if (!kvm_direct_msi_allowed
&& s
->irq_routes
->nr
== s
->gsi_count
) {
1569 kvm_flush_dynamic_msi_routes(s
);
1572 /* Return the lowest unused GSI in the bitmap */
1573 next_virq
= find_first_zero_bit(s
->used_gsi_bitmap
, s
->gsi_count
);
1574 if (next_virq
>= s
->gsi_count
) {
1581 static KVMMSIRoute
*kvm_lookup_msi_route(KVMState
*s
, MSIMessage msg
)
1583 unsigned int hash
= kvm_hash_msi(msg
.data
);
1586 QTAILQ_FOREACH(route
, &s
->msi_hashtab
[hash
], entry
) {
1587 if (route
->kroute
.u
.msi
.address_lo
== (uint32_t)msg
.address
&&
1588 route
->kroute
.u
.msi
.address_hi
== (msg
.address
>> 32) &&
1589 route
->kroute
.u
.msi
.data
== le32_to_cpu(msg
.data
)) {
1596 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1601 if (kvm_direct_msi_allowed
) {
1602 msi
.address_lo
= (uint32_t)msg
.address
;
1603 msi
.address_hi
= msg
.address
>> 32;
1604 msi
.data
= le32_to_cpu(msg
.data
);
1606 memset(msi
.pad
, 0, sizeof(msi
.pad
));
1608 return kvm_vm_ioctl(s
, KVM_SIGNAL_MSI
, &msi
);
1611 route
= kvm_lookup_msi_route(s
, msg
);
1615 virq
= kvm_irqchip_get_virq(s
);
1620 route
= g_malloc0(sizeof(KVMMSIRoute
));
1621 route
->kroute
.gsi
= virq
;
1622 route
->kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1623 route
->kroute
.flags
= 0;
1624 route
->kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1625 route
->kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1626 route
->kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1628 kvm_add_routing_entry(s
, &route
->kroute
);
1629 kvm_irqchip_commit_routes(s
);
1631 QTAILQ_INSERT_TAIL(&s
->msi_hashtab
[kvm_hash_msi(msg
.data
)], route
,
1635 assert(route
->kroute
.type
== KVM_IRQ_ROUTING_MSI
);
1637 return kvm_set_irq(s
, route
->kroute
.gsi
, 1);
1640 int kvm_irqchip_add_msi_route(KVMState
*s
, int vector
, PCIDevice
*dev
)
1642 struct kvm_irq_routing_entry kroute
= {};
1644 MSIMessage msg
= {0, 0};
1646 if (pci_available
&& dev
) {
1647 msg
= pci_get_msi_message(dev
, vector
);
1650 if (kvm_gsi_direct_mapping()) {
1651 return kvm_arch_msi_data_to_gsi(msg
.data
);
1654 if (!kvm_gsi_routing_enabled()) {
1658 virq
= kvm_irqchip_get_virq(s
);
1664 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1666 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1667 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1668 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1669 if (pci_available
&& kvm_msi_devid_required()) {
1670 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1671 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1673 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1674 kvm_irqchip_release_virq(s
, virq
);
1678 trace_kvm_irqchip_add_msi_route(dev
? dev
->name
: (char *)"N/A",
1681 kvm_add_routing_entry(s
, &kroute
);
1682 kvm_arch_add_msi_route_post(&kroute
, vector
, dev
);
1683 kvm_irqchip_commit_routes(s
);
1688 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
,
1691 struct kvm_irq_routing_entry kroute
= {};
1693 if (kvm_gsi_direct_mapping()) {
1697 if (!kvm_irqchip_in_kernel()) {
1702 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1704 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1705 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1706 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1707 if (pci_available
&& kvm_msi_devid_required()) {
1708 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1709 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1711 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1715 trace_kvm_irqchip_update_msi_route(virq
);
1717 return kvm_update_routing_entry(s
, &kroute
);
1720 static int kvm_irqchip_assign_irqfd(KVMState
*s
, EventNotifier
*event
,
1721 EventNotifier
*resample
, int virq
,
1724 int fd
= event_notifier_get_fd(event
);
1725 int rfd
= resample
? event_notifier_get_fd(resample
) : -1;
1727 struct kvm_irqfd irqfd
= {
1730 .flags
= assign
? 0 : KVM_IRQFD_FLAG_DEASSIGN
,
1735 if (kvm_irqchip_is_split()) {
1737 * When the slow irqchip (e.g. IOAPIC) is in the
1738 * userspace, KVM kernel resamplefd will not work because
1739 * the EOI of the interrupt will be delivered to userspace
1740 * instead, so the KVM kernel resamplefd kick will be
1741 * skipped. The userspace here mimics what the kernel
1742 * provides with resamplefd, remember the resamplefd and
1743 * kick it when we receive EOI of this IRQ.
1745 * This is hackery because IOAPIC is mostly bypassed
1746 * (except EOI broadcasts) when irqfd is used. However
1747 * this can bring much performance back for split irqchip
1748 * with INTx IRQs (for VFIO, this gives 93% perf of the
1749 * full fast path, which is 46% perf boost comparing to
1750 * the INTx slow path).
1752 kvm_resample_fd_insert(virq
, resample
);
1754 irqfd
.flags
|= KVM_IRQFD_FLAG_RESAMPLE
;
1755 irqfd
.resamplefd
= rfd
;
1757 } else if (!assign
) {
1758 if (kvm_irqchip_is_split()) {
1759 kvm_resample_fd_remove(virq
);
1763 if (!kvm_irqfds_enabled()) {
1767 return kvm_vm_ioctl(s
, KVM_IRQFD
, &irqfd
);
1770 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
1772 struct kvm_irq_routing_entry kroute
= {};
1775 if (!kvm_gsi_routing_enabled()) {
1779 virq
= kvm_irqchip_get_virq(s
);
1785 kroute
.type
= KVM_IRQ_ROUTING_S390_ADAPTER
;
1787 kroute
.u
.adapter
.summary_addr
= adapter
->summary_addr
;
1788 kroute
.u
.adapter
.ind_addr
= adapter
->ind_addr
;
1789 kroute
.u
.adapter
.summary_offset
= adapter
->summary_offset
;
1790 kroute
.u
.adapter
.ind_offset
= adapter
->ind_offset
;
1791 kroute
.u
.adapter
.adapter_id
= adapter
->adapter_id
;
1793 kvm_add_routing_entry(s
, &kroute
);
1798 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
1800 struct kvm_irq_routing_entry kroute
= {};
1803 if (!kvm_gsi_routing_enabled()) {
1806 if (!kvm_check_extension(s
, KVM_CAP_HYPERV_SYNIC
)) {
1809 virq
= kvm_irqchip_get_virq(s
);
1815 kroute
.type
= KVM_IRQ_ROUTING_HV_SINT
;
1817 kroute
.u
.hv_sint
.vcpu
= vcpu
;
1818 kroute
.u
.hv_sint
.sint
= sint
;
1820 kvm_add_routing_entry(s
, &kroute
);
1821 kvm_irqchip_commit_routes(s
);
1826 #else /* !KVM_CAP_IRQ_ROUTING */
1828 void kvm_init_irq_routing(KVMState
*s
)
1832 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
1836 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1841 int kvm_irqchip_add_msi_route(KVMState
*s
, int vector
, PCIDevice
*dev
)
1846 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
1851 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
1856 static int kvm_irqchip_assign_irqfd(KVMState
*s
, EventNotifier
*event
,
1857 EventNotifier
*resample
, int virq
,
1863 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
)
1867 #endif /* !KVM_CAP_IRQ_ROUTING */
1869 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
1870 EventNotifier
*rn
, int virq
)
1872 return kvm_irqchip_assign_irqfd(s
, n
, rn
, virq
, true);
1875 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
1878 return kvm_irqchip_assign_irqfd(s
, n
, NULL
, virq
, false);
1881 int kvm_irqchip_add_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
1882 EventNotifier
*rn
, qemu_irq irq
)
1885 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
1890 return kvm_irqchip_add_irqfd_notifier_gsi(s
, n
, rn
, GPOINTER_TO_INT(gsi
));
1893 int kvm_irqchip_remove_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
1897 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
1902 return kvm_irqchip_remove_irqfd_notifier_gsi(s
, n
, GPOINTER_TO_INT(gsi
));
1905 void kvm_irqchip_set_qemuirq_gsi(KVMState
*s
, qemu_irq irq
, int gsi
)
1907 g_hash_table_insert(s
->gsimap
, irq
, GINT_TO_POINTER(gsi
));
1910 static void kvm_irqchip_create(KVMState
*s
)
1914 assert(s
->kernel_irqchip_split
!= ON_OFF_AUTO_AUTO
);
1915 if (kvm_check_extension(s
, KVM_CAP_IRQCHIP
)) {
1917 } else if (kvm_check_extension(s
, KVM_CAP_S390_IRQCHIP
)) {
1918 ret
= kvm_vm_enable_cap(s
, KVM_CAP_S390_IRQCHIP
, 0);
1920 fprintf(stderr
, "Enable kernel irqchip failed: %s\n", strerror(-ret
));
1927 /* First probe and see if there's a arch-specific hook to create the
1928 * in-kernel irqchip for us */
1929 ret
= kvm_arch_irqchip_create(s
);
1931 if (s
->kernel_irqchip_split
== ON_OFF_AUTO_ON
) {
1932 perror("Split IRQ chip mode not supported.");
1935 ret
= kvm_vm_ioctl(s
, KVM_CREATE_IRQCHIP
);
1939 fprintf(stderr
, "Create kernel irqchip failed: %s\n", strerror(-ret
));
1943 kvm_kernel_irqchip
= true;
1944 /* If we have an in-kernel IRQ chip then we must have asynchronous
1945 * interrupt delivery (though the reverse is not necessarily true)
1947 kvm_async_interrupts_allowed
= true;
1948 kvm_halt_in_kernel_allowed
= true;
1950 kvm_init_irq_routing(s
);
1952 s
->gsimap
= g_hash_table_new(g_direct_hash
, g_direct_equal
);
1955 /* Find number of supported CPUs using the recommended
1956 * procedure from the kernel API documentation to cope with
1957 * older kernels that may be missing capabilities.
1959 static int kvm_recommended_vcpus(KVMState
*s
)
1961 int ret
= kvm_vm_check_extension(s
, KVM_CAP_NR_VCPUS
);
1962 return (ret
) ? ret
: 4;
1965 static int kvm_max_vcpus(KVMState
*s
)
1967 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPUS
);
1968 return (ret
) ? ret
: kvm_recommended_vcpus(s
);
1971 static int kvm_max_vcpu_id(KVMState
*s
)
1973 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPU_ID
);
1974 return (ret
) ? ret
: kvm_max_vcpus(s
);
1977 bool kvm_vcpu_id_is_valid(int vcpu_id
)
1979 KVMState
*s
= KVM_STATE(current_accel());
1980 return vcpu_id
>= 0 && vcpu_id
< kvm_max_vcpu_id(s
);
1983 static int kvm_init(MachineState
*ms
)
1985 MachineClass
*mc
= MACHINE_GET_CLASS(ms
);
1986 static const char upgrade_note
[] =
1987 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1988 "(see http://sourceforge.net/projects/kvm).\n";
1993 { "SMP", ms
->smp
.cpus
},
1994 { "hotpluggable", ms
->smp
.max_cpus
},
1997 int soft_vcpus_limit
, hard_vcpus_limit
;
1999 const KVMCapabilityInfo
*missing_cap
;
2002 uint64_t dirty_log_manual_caps
;
2004 s
= KVM_STATE(ms
->accelerator
);
2007 * On systems where the kernel can support different base page
2008 * sizes, host page size may be different from TARGET_PAGE_SIZE,
2009 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
2010 * page size for the system though.
2012 assert(TARGET_PAGE_SIZE
<= qemu_real_host_page_size
);
2016 #ifdef KVM_CAP_SET_GUEST_DEBUG
2017 QTAILQ_INIT(&s
->kvm_sw_breakpoints
);
2019 QLIST_INIT(&s
->kvm_parked_vcpus
);
2021 s
->fd
= qemu_open_old("/dev/kvm", O_RDWR
);
2023 fprintf(stderr
, "Could not access KVM kernel module: %m\n");
2028 ret
= kvm_ioctl(s
, KVM_GET_API_VERSION
, 0);
2029 if (ret
< KVM_API_VERSION
) {
2033 fprintf(stderr
, "kvm version too old\n");
2037 if (ret
> KVM_API_VERSION
) {
2039 fprintf(stderr
, "kvm version not supported\n");
2043 kvm_immediate_exit
= kvm_check_extension(s
, KVM_CAP_IMMEDIATE_EXIT
);
2044 s
->nr_slots
= kvm_check_extension(s
, KVM_CAP_NR_MEMSLOTS
);
2046 /* If unspecified, use the default value */
2051 s
->nr_as
= kvm_check_extension(s
, KVM_CAP_MULTI_ADDRESS_SPACE
);
2052 if (s
->nr_as
<= 1) {
2055 s
->as
= g_new0(struct KVMAs
, s
->nr_as
);
2057 if (object_property_find(OBJECT(current_machine
), "kvm-type")) {
2058 g_autofree
char *kvm_type
= object_property_get_str(OBJECT(current_machine
),
2061 type
= mc
->kvm_type(ms
, kvm_type
);
2062 } else if (mc
->kvm_type
) {
2063 type
= mc
->kvm_type(ms
, NULL
);
2067 ret
= kvm_ioctl(s
, KVM_CREATE_VM
, type
);
2068 } while (ret
== -EINTR
);
2071 fprintf(stderr
, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret
,
2075 if (ret
== -EINVAL
) {
2077 "Host kernel setup problem detected. Please verify:\n");
2078 fprintf(stderr
, "- for kernels supporting the switch_amode or"
2079 " user_mode parameters, whether\n");
2081 " user space is running in primary address space\n");
2083 "- for kernels supporting the vm.allocate_pgste sysctl, "
2084 "whether it is enabled\n");
2092 /* check the vcpu limits */
2093 soft_vcpus_limit
= kvm_recommended_vcpus(s
);
2094 hard_vcpus_limit
= kvm_max_vcpus(s
);
2097 if (nc
->num
> soft_vcpus_limit
) {
2098 warn_report("Number of %s cpus requested (%d) exceeds "
2099 "the recommended cpus supported by KVM (%d)",
2100 nc
->name
, nc
->num
, soft_vcpus_limit
);
2102 if (nc
->num
> hard_vcpus_limit
) {
2103 fprintf(stderr
, "Number of %s cpus requested (%d) exceeds "
2104 "the maximum cpus supported by KVM (%d)\n",
2105 nc
->name
, nc
->num
, hard_vcpus_limit
);
2112 missing_cap
= kvm_check_extension_list(s
, kvm_required_capabilites
);
2115 kvm_check_extension_list(s
, kvm_arch_required_capabilities
);
2119 fprintf(stderr
, "kvm does not support %s\n%s",
2120 missing_cap
->name
, upgrade_note
);
2124 s
->coalesced_mmio
= kvm_check_extension(s
, KVM_CAP_COALESCED_MMIO
);
2125 s
->coalesced_pio
= s
->coalesced_mmio
&&
2126 kvm_check_extension(s
, KVM_CAP_COALESCED_PIO
);
2128 dirty_log_manual_caps
=
2129 kvm_check_extension(s
, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2
);
2130 dirty_log_manual_caps
&= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE
|
2131 KVM_DIRTY_LOG_INITIALLY_SET
);
2132 s
->manual_dirty_log_protect
= dirty_log_manual_caps
;
2133 if (dirty_log_manual_caps
) {
2134 ret
= kvm_vm_enable_cap(s
, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2
, 0,
2135 dirty_log_manual_caps
);
2137 warn_report("Trying to enable capability %"PRIu64
" of "
2138 "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
2139 "Falling back to the legacy mode. ",
2140 dirty_log_manual_caps
);
2141 s
->manual_dirty_log_protect
= 0;
2145 #ifdef KVM_CAP_VCPU_EVENTS
2146 s
->vcpu_events
= kvm_check_extension(s
, KVM_CAP_VCPU_EVENTS
);
2149 s
->robust_singlestep
=
2150 kvm_check_extension(s
, KVM_CAP_X86_ROBUST_SINGLESTEP
);
2152 #ifdef KVM_CAP_DEBUGREGS
2153 s
->debugregs
= kvm_check_extension(s
, KVM_CAP_DEBUGREGS
);
2156 s
->max_nested_state_len
= kvm_check_extension(s
, KVM_CAP_NESTED_STATE
);
2158 #ifdef KVM_CAP_IRQ_ROUTING
2159 kvm_direct_msi_allowed
= (kvm_check_extension(s
, KVM_CAP_SIGNAL_MSI
) > 0);
2162 s
->intx_set_mask
= kvm_check_extension(s
, KVM_CAP_PCI_2_3
);
2164 s
->irq_set_ioctl
= KVM_IRQ_LINE
;
2165 if (kvm_check_extension(s
, KVM_CAP_IRQ_INJECT_STATUS
)) {
2166 s
->irq_set_ioctl
= KVM_IRQ_LINE_STATUS
;
2169 kvm_readonly_mem_allowed
=
2170 (kvm_check_extension(s
, KVM_CAP_READONLY_MEM
) > 0);
2172 kvm_eventfds_allowed
=
2173 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD
) > 0);
2175 kvm_irqfds_allowed
=
2176 (kvm_check_extension(s
, KVM_CAP_IRQFD
) > 0);
2178 kvm_resamplefds_allowed
=
2179 (kvm_check_extension(s
, KVM_CAP_IRQFD_RESAMPLE
) > 0);
2181 kvm_vm_attributes_allowed
=
2182 (kvm_check_extension(s
, KVM_CAP_VM_ATTRIBUTES
) > 0);
2184 kvm_ioeventfd_any_length_allowed
=
2185 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD_ANY_LENGTH
) > 0);
2189 ret
= kvm_arch_init(ms
, s
);
2194 if (s
->kernel_irqchip_split
== ON_OFF_AUTO_AUTO
) {
2195 s
->kernel_irqchip_split
= mc
->default_kernel_irqchip_split
? ON_OFF_AUTO_ON
: ON_OFF_AUTO_OFF
;
2198 qemu_register_reset(kvm_unpoison_all
, NULL
);
2200 if (s
->kernel_irqchip_allowed
) {
2201 kvm_irqchip_create(s
);
2204 if (kvm_eventfds_allowed
) {
2205 s
->memory_listener
.listener
.eventfd_add
= kvm_mem_ioeventfd_add
;
2206 s
->memory_listener
.listener
.eventfd_del
= kvm_mem_ioeventfd_del
;
2208 s
->memory_listener
.listener
.coalesced_io_add
= kvm_coalesce_mmio_region
;
2209 s
->memory_listener
.listener
.coalesced_io_del
= kvm_uncoalesce_mmio_region
;
2211 kvm_memory_listener_register(s
, &s
->memory_listener
,
2212 &address_space_memory
, 0);
2213 if (kvm_eventfds_allowed
) {
2214 memory_listener_register(&kvm_io_listener
,
2217 memory_listener_register(&kvm_coalesced_pio_listener
,
2220 s
->many_ioeventfds
= kvm_check_many_ioeventfds();
2222 s
->sync_mmu
= !!kvm_vm_check_extension(kvm_state
, KVM_CAP_SYNC_MMU
);
2224 ret
= ram_block_discard_disable(true);
2237 g_free(s
->memory_listener
.slots
);
2242 void kvm_set_sigmask_len(KVMState
*s
, unsigned int sigmask_len
)
2244 s
->sigmask_len
= sigmask_len
;
2247 static void kvm_handle_io(uint16_t port
, MemTxAttrs attrs
, void *data
, int direction
,
2248 int size
, uint32_t count
)
2251 uint8_t *ptr
= data
;
2253 for (i
= 0; i
< count
; i
++) {
2254 address_space_rw(&address_space_io
, port
, attrs
,
2256 direction
== KVM_EXIT_IO_OUT
);
2261 static int kvm_handle_internal_error(CPUState
*cpu
, struct kvm_run
*run
)
2263 fprintf(stderr
, "KVM internal error. Suberror: %d\n",
2264 run
->internal
.suberror
);
2266 if (kvm_check_extension(kvm_state
, KVM_CAP_INTERNAL_ERROR_DATA
)) {
2269 for (i
= 0; i
< run
->internal
.ndata
; ++i
) {
2270 fprintf(stderr
, "extra data[%d]: 0x%016"PRIx64
"\n",
2271 i
, (uint64_t)run
->internal
.data
[i
]);
2274 if (run
->internal
.suberror
== KVM_INTERNAL_ERROR_EMULATION
) {
2275 fprintf(stderr
, "emulation failure\n");
2276 if (!kvm_arch_stop_on_emulation_error(cpu
)) {
2277 cpu_dump_state(cpu
, stderr
, CPU_DUMP_CODE
);
2278 return EXCP_INTERRUPT
;
2281 /* FIXME: Should trigger a qmp message to let management know
2282 * something went wrong.
2287 void kvm_flush_coalesced_mmio_buffer(void)
2289 KVMState
*s
= kvm_state
;
2291 if (s
->coalesced_flush_in_progress
) {
2295 s
->coalesced_flush_in_progress
= true;
2297 if (s
->coalesced_mmio_ring
) {
2298 struct kvm_coalesced_mmio_ring
*ring
= s
->coalesced_mmio_ring
;
2299 while (ring
->first
!= ring
->last
) {
2300 struct kvm_coalesced_mmio
*ent
;
2302 ent
= &ring
->coalesced_mmio
[ring
->first
];
2304 if (ent
->pio
== 1) {
2305 address_space_write(&address_space_io
, ent
->phys_addr
,
2306 MEMTXATTRS_UNSPECIFIED
, ent
->data
,
2309 cpu_physical_memory_write(ent
->phys_addr
, ent
->data
, ent
->len
);
2312 ring
->first
= (ring
->first
+ 1) % KVM_COALESCED_MMIO_MAX
;
2316 s
->coalesced_flush_in_progress
= false;
2319 bool kvm_cpu_check_are_resettable(void)
2321 return kvm_arch_cpu_check_are_resettable();
2324 static void do_kvm_cpu_synchronize_state(CPUState
*cpu
, run_on_cpu_data arg
)
2326 if (!cpu
->vcpu_dirty
) {
2327 kvm_arch_get_registers(cpu
);
2328 cpu
->vcpu_dirty
= true;
2332 void kvm_cpu_synchronize_state(CPUState
*cpu
)
2334 if (!cpu
->vcpu_dirty
) {
2335 run_on_cpu(cpu
, do_kvm_cpu_synchronize_state
, RUN_ON_CPU_NULL
);
2339 static void do_kvm_cpu_synchronize_post_reset(CPUState
*cpu
, run_on_cpu_data arg
)
2341 kvm_arch_put_registers(cpu
, KVM_PUT_RESET_STATE
);
2342 cpu
->vcpu_dirty
= false;
2345 void kvm_cpu_synchronize_post_reset(CPUState
*cpu
)
2347 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_reset
, RUN_ON_CPU_NULL
);
2350 static void do_kvm_cpu_synchronize_post_init(CPUState
*cpu
, run_on_cpu_data arg
)
2352 kvm_arch_put_registers(cpu
, KVM_PUT_FULL_STATE
);
2353 cpu
->vcpu_dirty
= false;
2356 void kvm_cpu_synchronize_post_init(CPUState
*cpu
)
2358 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_init
, RUN_ON_CPU_NULL
);
2361 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
, run_on_cpu_data arg
)
2363 cpu
->vcpu_dirty
= true;
2366 void kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
)
2368 run_on_cpu(cpu
, do_kvm_cpu_synchronize_pre_loadvm
, RUN_ON_CPU_NULL
);
2371 #ifdef KVM_HAVE_MCE_INJECTION
2372 static __thread
void *pending_sigbus_addr
;
2373 static __thread
int pending_sigbus_code
;
2374 static __thread
bool have_sigbus_pending
;
2377 static void kvm_cpu_kick(CPUState
*cpu
)
2379 qatomic_set(&cpu
->kvm_run
->immediate_exit
, 1);
2382 static void kvm_cpu_kick_self(void)
2384 if (kvm_immediate_exit
) {
2385 kvm_cpu_kick(current_cpu
);
2387 qemu_cpu_kick_self();
2391 static void kvm_eat_signals(CPUState
*cpu
)
2393 struct timespec ts
= { 0, 0 };
2399 if (kvm_immediate_exit
) {
2400 qatomic_set(&cpu
->kvm_run
->immediate_exit
, 0);
2401 /* Write kvm_run->immediate_exit before the cpu->exit_request
2402 * write in kvm_cpu_exec.
2408 sigemptyset(&waitset
);
2409 sigaddset(&waitset
, SIG_IPI
);
2412 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
2413 if (r
== -1 && !(errno
== EAGAIN
|| errno
== EINTR
)) {
2414 perror("sigtimedwait");
2418 r
= sigpending(&chkset
);
2420 perror("sigpending");
2423 } while (sigismember(&chkset
, SIG_IPI
));
2426 int kvm_cpu_exec(CPUState
*cpu
)
2428 struct kvm_run
*run
= cpu
->kvm_run
;
2431 DPRINTF("kvm_cpu_exec()\n");
2433 if (kvm_arch_process_async_events(cpu
)) {
2434 qatomic_set(&cpu
->exit_request
, 0);
2438 qemu_mutex_unlock_iothread();
2439 cpu_exec_start(cpu
);
2444 if (cpu
->vcpu_dirty
) {
2445 kvm_arch_put_registers(cpu
, KVM_PUT_RUNTIME_STATE
);
2446 cpu
->vcpu_dirty
= false;
2449 kvm_arch_pre_run(cpu
, run
);
2450 if (qatomic_read(&cpu
->exit_request
)) {
2451 DPRINTF("interrupt exit requested\n");
2453 * KVM requires us to reenter the kernel after IO exits to complete
2454 * instruction emulation. This self-signal will ensure that we
2457 kvm_cpu_kick_self();
2460 /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2461 * Matching barrier in kvm_eat_signals.
2465 run_ret
= kvm_vcpu_ioctl(cpu
, KVM_RUN
, 0);
2467 attrs
= kvm_arch_post_run(cpu
, run
);
2469 #ifdef KVM_HAVE_MCE_INJECTION
2470 if (unlikely(have_sigbus_pending
)) {
2471 qemu_mutex_lock_iothread();
2472 kvm_arch_on_sigbus_vcpu(cpu
, pending_sigbus_code
,
2473 pending_sigbus_addr
);
2474 have_sigbus_pending
= false;
2475 qemu_mutex_unlock_iothread();
2480 if (run_ret
== -EINTR
|| run_ret
== -EAGAIN
) {
2481 DPRINTF("io window exit\n");
2482 kvm_eat_signals(cpu
);
2483 ret
= EXCP_INTERRUPT
;
2486 fprintf(stderr
, "error: kvm run failed %s\n",
2487 strerror(-run_ret
));
2489 if (run_ret
== -EBUSY
) {
2491 "This is probably because your SMT is enabled.\n"
2492 "VCPU can only run on primary threads with all "
2493 "secondary threads offline.\n");
2500 trace_kvm_run_exit(cpu
->cpu_index
, run
->exit_reason
);
2501 switch (run
->exit_reason
) {
2503 DPRINTF("handle_io\n");
2504 /* Called outside BQL */
2505 kvm_handle_io(run
->io
.port
, attrs
,
2506 (uint8_t *)run
+ run
->io
.data_offset
,
2513 DPRINTF("handle_mmio\n");
2514 /* Called outside BQL */
2515 address_space_rw(&address_space_memory
,
2516 run
->mmio
.phys_addr
, attrs
,
2519 run
->mmio
.is_write
);
2522 case KVM_EXIT_IRQ_WINDOW_OPEN
:
2523 DPRINTF("irq_window_open\n");
2524 ret
= EXCP_INTERRUPT
;
2526 case KVM_EXIT_SHUTDOWN
:
2527 DPRINTF("shutdown\n");
2528 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
2529 ret
= EXCP_INTERRUPT
;
2531 case KVM_EXIT_UNKNOWN
:
2532 fprintf(stderr
, "KVM: unknown exit, hardware reason %" PRIx64
"\n",
2533 (uint64_t)run
->hw
.hardware_exit_reason
);
2536 case KVM_EXIT_INTERNAL_ERROR
:
2537 ret
= kvm_handle_internal_error(cpu
, run
);
2539 case KVM_EXIT_SYSTEM_EVENT
:
2540 switch (run
->system_event
.type
) {
2541 case KVM_SYSTEM_EVENT_SHUTDOWN
:
2542 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN
);
2543 ret
= EXCP_INTERRUPT
;
2545 case KVM_SYSTEM_EVENT_RESET
:
2546 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
2547 ret
= EXCP_INTERRUPT
;
2549 case KVM_SYSTEM_EVENT_CRASH
:
2550 kvm_cpu_synchronize_state(cpu
);
2551 qemu_mutex_lock_iothread();
2552 qemu_system_guest_panicked(cpu_get_crash_info(cpu
));
2553 qemu_mutex_unlock_iothread();
2557 DPRINTF("kvm_arch_handle_exit\n");
2558 ret
= kvm_arch_handle_exit(cpu
, run
);
2563 DPRINTF("kvm_arch_handle_exit\n");
2564 ret
= kvm_arch_handle_exit(cpu
, run
);
2570 qemu_mutex_lock_iothread();
2573 cpu_dump_state(cpu
, stderr
, CPU_DUMP_CODE
);
2574 vm_stop(RUN_STATE_INTERNAL_ERROR
);
2577 qatomic_set(&cpu
->exit_request
, 0);
2581 int kvm_ioctl(KVMState
*s
, int type
, ...)
2588 arg
= va_arg(ap
, void *);
2591 trace_kvm_ioctl(type
, arg
);
2592 ret
= ioctl(s
->fd
, type
, arg
);
2599 int kvm_vm_ioctl(KVMState
*s
, int type
, ...)
2606 arg
= va_arg(ap
, void *);
2609 trace_kvm_vm_ioctl(type
, arg
);
2610 ret
= ioctl(s
->vmfd
, type
, arg
);
2617 int kvm_vcpu_ioctl(CPUState
*cpu
, int type
, ...)
2624 arg
= va_arg(ap
, void *);
2627 trace_kvm_vcpu_ioctl(cpu
->cpu_index
, type
, arg
);
2628 ret
= ioctl(cpu
->kvm_fd
, type
, arg
);
2635 int kvm_device_ioctl(int fd
, int type
, ...)
2642 arg
= va_arg(ap
, void *);
2645 trace_kvm_device_ioctl(fd
, type
, arg
);
2646 ret
= ioctl(fd
, type
, arg
);
2653 int kvm_vm_check_attr(KVMState
*s
, uint32_t group
, uint64_t attr
)
2656 struct kvm_device_attr attribute
= {
2661 if (!kvm_vm_attributes_allowed
) {
2665 ret
= kvm_vm_ioctl(s
, KVM_HAS_DEVICE_ATTR
, &attribute
);
2666 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2670 int kvm_device_check_attr(int dev_fd
, uint32_t group
, uint64_t attr
)
2672 struct kvm_device_attr attribute
= {
2678 return kvm_device_ioctl(dev_fd
, KVM_HAS_DEVICE_ATTR
, &attribute
) ? 0 : 1;
2681 int kvm_device_access(int fd
, int group
, uint64_t attr
,
2682 void *val
, bool write
, Error
**errp
)
2684 struct kvm_device_attr kvmattr
;
2688 kvmattr
.group
= group
;
2689 kvmattr
.attr
= attr
;
2690 kvmattr
.addr
= (uintptr_t)val
;
2692 err
= kvm_device_ioctl(fd
,
2693 write
? KVM_SET_DEVICE_ATTR
: KVM_GET_DEVICE_ATTR
,
2696 error_setg_errno(errp
, -err
,
2697 "KVM_%s_DEVICE_ATTR failed: Group %d "
2698 "attr 0x%016" PRIx64
,
2699 write
? "SET" : "GET", group
, attr
);
2704 bool kvm_has_sync_mmu(void)
2706 return kvm_state
->sync_mmu
;
2709 int kvm_has_vcpu_events(void)
2711 return kvm_state
->vcpu_events
;
2714 int kvm_has_robust_singlestep(void)
2716 return kvm_state
->robust_singlestep
;
2719 int kvm_has_debugregs(void)
2721 return kvm_state
->debugregs
;
2724 int kvm_max_nested_state_length(void)
2726 return kvm_state
->max_nested_state_len
;
2729 int kvm_has_many_ioeventfds(void)
2731 if (!kvm_enabled()) {
2734 return kvm_state
->many_ioeventfds
;
2737 int kvm_has_gsi_routing(void)
2739 #ifdef KVM_CAP_IRQ_ROUTING
2740 return kvm_check_extension(kvm_state
, KVM_CAP_IRQ_ROUTING
);
2746 int kvm_has_intx_set_mask(void)
2748 return kvm_state
->intx_set_mask
;
2751 bool kvm_arm_supports_user_irq(void)
2753 return kvm_check_extension(kvm_state
, KVM_CAP_ARM_USER_IRQ
);
2756 #ifdef KVM_CAP_SET_GUEST_DEBUG
2757 struct kvm_sw_breakpoint
*kvm_find_sw_breakpoint(CPUState
*cpu
,
2760 struct kvm_sw_breakpoint
*bp
;
2762 QTAILQ_FOREACH(bp
, &cpu
->kvm_state
->kvm_sw_breakpoints
, entry
) {
2770 int kvm_sw_breakpoints_active(CPUState
*cpu
)
2772 return !QTAILQ_EMPTY(&cpu
->kvm_state
->kvm_sw_breakpoints
);
2775 struct kvm_set_guest_debug_data
{
2776 struct kvm_guest_debug dbg
;
2780 static void kvm_invoke_set_guest_debug(CPUState
*cpu
, run_on_cpu_data data
)
2782 struct kvm_set_guest_debug_data
*dbg_data
=
2783 (struct kvm_set_guest_debug_data
*) data
.host_ptr
;
2785 dbg_data
->err
= kvm_vcpu_ioctl(cpu
, KVM_SET_GUEST_DEBUG
,
2789 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
2791 struct kvm_set_guest_debug_data data
;
2793 data
.dbg
.control
= reinject_trap
;
2795 if (cpu
->singlestep_enabled
) {
2796 data
.dbg
.control
|= KVM_GUESTDBG_ENABLE
| KVM_GUESTDBG_SINGLESTEP
;
2798 kvm_arch_update_guest_debug(cpu
, &data
.dbg
);
2800 run_on_cpu(cpu
, kvm_invoke_set_guest_debug
,
2801 RUN_ON_CPU_HOST_PTR(&data
));
2805 int kvm_insert_breakpoint(CPUState
*cpu
, target_ulong addr
,
2806 target_ulong len
, int type
)
2808 struct kvm_sw_breakpoint
*bp
;
2811 if (type
== GDB_BREAKPOINT_SW
) {
2812 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
2818 bp
= g_malloc(sizeof(struct kvm_sw_breakpoint
));
2821 err
= kvm_arch_insert_sw_breakpoint(cpu
, bp
);
2827 QTAILQ_INSERT_HEAD(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
2829 err
= kvm_arch_insert_hw_breakpoint(addr
, len
, type
);
2836 err
= kvm_update_guest_debug(cpu
, 0);
2844 int kvm_remove_breakpoint(CPUState
*cpu
, target_ulong addr
,
2845 target_ulong len
, int type
)
2847 struct kvm_sw_breakpoint
*bp
;
2850 if (type
== GDB_BREAKPOINT_SW
) {
2851 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
2856 if (bp
->use_count
> 1) {
2861 err
= kvm_arch_remove_sw_breakpoint(cpu
, bp
);
2866 QTAILQ_REMOVE(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
2869 err
= kvm_arch_remove_hw_breakpoint(addr
, len
, type
);
2876 err
= kvm_update_guest_debug(cpu
, 0);
2884 void kvm_remove_all_breakpoints(CPUState
*cpu
)
2886 struct kvm_sw_breakpoint
*bp
, *next
;
2887 KVMState
*s
= cpu
->kvm_state
;
2890 QTAILQ_FOREACH_SAFE(bp
, &s
->kvm_sw_breakpoints
, entry
, next
) {
2891 if (kvm_arch_remove_sw_breakpoint(cpu
, bp
) != 0) {
2892 /* Try harder to find a CPU that currently sees the breakpoint. */
2893 CPU_FOREACH(tmpcpu
) {
2894 if (kvm_arch_remove_sw_breakpoint(tmpcpu
, bp
) == 0) {
2899 QTAILQ_REMOVE(&s
->kvm_sw_breakpoints
, bp
, entry
);
2902 kvm_arch_remove_all_hw_breakpoints();
2905 kvm_update_guest_debug(cpu
, 0);
2909 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2911 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
2916 int kvm_insert_breakpoint(CPUState
*cpu
, target_ulong addr
,
2917 target_ulong len
, int type
)
2922 int kvm_remove_breakpoint(CPUState
*cpu
, target_ulong addr
,
2923 target_ulong len
, int type
)
2928 void kvm_remove_all_breakpoints(CPUState
*cpu
)
2931 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2933 static int kvm_set_signal_mask(CPUState
*cpu
, const sigset_t
*sigset
)
2935 KVMState
*s
= kvm_state
;
2936 struct kvm_signal_mask
*sigmask
;
2939 sigmask
= g_malloc(sizeof(*sigmask
) + sizeof(*sigset
));
2941 sigmask
->len
= s
->sigmask_len
;
2942 memcpy(sigmask
->sigset
, sigset
, sizeof(*sigset
));
2943 r
= kvm_vcpu_ioctl(cpu
, KVM_SET_SIGNAL_MASK
, sigmask
);
2949 static void kvm_ipi_signal(int sig
)
2952 assert(kvm_immediate_exit
);
2953 kvm_cpu_kick(current_cpu
);
2957 void kvm_init_cpu_signals(CPUState
*cpu
)
2961 struct sigaction sigact
;
2963 memset(&sigact
, 0, sizeof(sigact
));
2964 sigact
.sa_handler
= kvm_ipi_signal
;
2965 sigaction(SIG_IPI
, &sigact
, NULL
);
2967 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
2968 #if defined KVM_HAVE_MCE_INJECTION
2969 sigdelset(&set
, SIGBUS
);
2970 pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
2972 sigdelset(&set
, SIG_IPI
);
2973 if (kvm_immediate_exit
) {
2974 r
= pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
2976 r
= kvm_set_signal_mask(cpu
, &set
);
2979 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(-r
));
2984 /* Called asynchronously in VCPU thread. */
2985 int kvm_on_sigbus_vcpu(CPUState
*cpu
, int code
, void *addr
)
2987 #ifdef KVM_HAVE_MCE_INJECTION
2988 if (have_sigbus_pending
) {
2991 have_sigbus_pending
= true;
2992 pending_sigbus_addr
= addr
;
2993 pending_sigbus_code
= code
;
2994 qatomic_set(&cpu
->exit_request
, 1);
3001 /* Called synchronously (via signalfd) in main thread. */
3002 int kvm_on_sigbus(int code
, void *addr
)
3004 #ifdef KVM_HAVE_MCE_INJECTION
3005 /* Action required MCE kills the process if SIGBUS is blocked. Because
3006 * that's what happens in the I/O thread, where we handle MCE via signalfd,
3007 * we can only get action optional here.
3009 assert(code
!= BUS_MCEERR_AR
);
3010 kvm_arch_on_sigbus_vcpu(first_cpu
, code
, addr
);
3017 int kvm_create_device(KVMState
*s
, uint64_t type
, bool test
)
3020 struct kvm_create_device create_dev
;
3022 create_dev
.type
= type
;
3024 create_dev
.flags
= test
? KVM_CREATE_DEVICE_TEST
: 0;
3026 if (!kvm_check_extension(s
, KVM_CAP_DEVICE_CTRL
)) {
3030 ret
= kvm_vm_ioctl(s
, KVM_CREATE_DEVICE
, &create_dev
);
3035 return test
? 0 : create_dev
.fd
;
3038 bool kvm_device_supported(int vmfd
, uint64_t type
)
3040 struct kvm_create_device create_dev
= {
3043 .flags
= KVM_CREATE_DEVICE_TEST
,
3046 if (ioctl(vmfd
, KVM_CHECK_EXTENSION
, KVM_CAP_DEVICE_CTRL
) <= 0) {
3050 return (ioctl(vmfd
, KVM_CREATE_DEVICE
, &create_dev
) >= 0);
3053 int kvm_set_one_reg(CPUState
*cs
, uint64_t id
, void *source
)
3055 struct kvm_one_reg reg
;
3059 reg
.addr
= (uintptr_t) source
;
3060 r
= kvm_vcpu_ioctl(cs
, KVM_SET_ONE_REG
, ®
);
3062 trace_kvm_failed_reg_set(id
, strerror(-r
));
3067 int kvm_get_one_reg(CPUState
*cs
, uint64_t id
, void *target
)
3069 struct kvm_one_reg reg
;
3073 reg
.addr
= (uintptr_t) target
;
3074 r
= kvm_vcpu_ioctl(cs
, KVM_GET_ONE_REG
, ®
);
3076 trace_kvm_failed_reg_get(id
, strerror(-r
));
3081 static bool kvm_accel_has_memory(MachineState
*ms
, AddressSpace
*as
,
3082 hwaddr start_addr
, hwaddr size
)
3084 KVMState
*kvm
= KVM_STATE(ms
->accelerator
);
3087 for (i
= 0; i
< kvm
->nr_as
; ++i
) {
3088 if (kvm
->as
[i
].as
== as
&& kvm
->as
[i
].ml
) {
3089 size
= MIN(kvm_max_slot_size
, size
);
3090 return NULL
!= kvm_lookup_matching_slot(kvm
->as
[i
].ml
,
3098 static void kvm_get_kvm_shadow_mem(Object
*obj
, Visitor
*v
,
3099 const char *name
, void *opaque
,
3102 KVMState
*s
= KVM_STATE(obj
);
3103 int64_t value
= s
->kvm_shadow_mem
;
3105 visit_type_int(v
, name
, &value
, errp
);
3108 static void kvm_set_kvm_shadow_mem(Object
*obj
, Visitor
*v
,
3109 const char *name
, void *opaque
,
3112 KVMState
*s
= KVM_STATE(obj
);
3115 if (!visit_type_int(v
, name
, &value
, errp
)) {
3119 s
->kvm_shadow_mem
= value
;
3122 static void kvm_set_kernel_irqchip(Object
*obj
, Visitor
*v
,
3123 const char *name
, void *opaque
,
3126 KVMState
*s
= KVM_STATE(obj
);
3129 if (!visit_type_OnOffSplit(v
, name
, &mode
, errp
)) {
3133 case ON_OFF_SPLIT_ON
:
3134 s
->kernel_irqchip_allowed
= true;
3135 s
->kernel_irqchip_required
= true;
3136 s
->kernel_irqchip_split
= ON_OFF_AUTO_OFF
;
3138 case ON_OFF_SPLIT_OFF
:
3139 s
->kernel_irqchip_allowed
= false;
3140 s
->kernel_irqchip_required
= false;
3141 s
->kernel_irqchip_split
= ON_OFF_AUTO_OFF
;
3143 case ON_OFF_SPLIT_SPLIT
:
3144 s
->kernel_irqchip_allowed
= true;
3145 s
->kernel_irqchip_required
= true;
3146 s
->kernel_irqchip_split
= ON_OFF_AUTO_ON
;
3149 /* The value was checked in visit_type_OnOffSplit() above. If
3150 * we get here, then something is wrong in QEMU.
3156 bool kvm_kernel_irqchip_allowed(void)
3158 return kvm_state
->kernel_irqchip_allowed
;
3161 bool kvm_kernel_irqchip_required(void)
3163 return kvm_state
->kernel_irqchip_required
;
3166 bool kvm_kernel_irqchip_split(void)
3168 return kvm_state
->kernel_irqchip_split
== ON_OFF_AUTO_ON
;
3171 static void kvm_accel_instance_init(Object
*obj
)
3173 KVMState
*s
= KVM_STATE(obj
);
3175 s
->kvm_shadow_mem
= -1;
3176 s
->kernel_irqchip_allowed
= true;
3177 s
->kernel_irqchip_split
= ON_OFF_AUTO_AUTO
;
3180 static void kvm_accel_class_init(ObjectClass
*oc
, void *data
)
3182 AccelClass
*ac
= ACCEL_CLASS(oc
);
3184 ac
->init_machine
= kvm_init
;
3185 ac
->has_memory
= kvm_accel_has_memory
;
3186 ac
->allowed
= &kvm_allowed
;
3188 object_class_property_add(oc
, "kernel-irqchip", "on|off|split",
3189 NULL
, kvm_set_kernel_irqchip
,
3191 object_class_property_set_description(oc
, "kernel-irqchip",
3192 "Configure KVM in-kernel irqchip");
3194 object_class_property_add(oc
, "kvm-shadow-mem", "int",
3195 kvm_get_kvm_shadow_mem
, kvm_set_kvm_shadow_mem
,
3197 object_class_property_set_description(oc
, "kvm-shadow-mem",
3198 "KVM shadow MMU size");
3201 static const TypeInfo kvm_accel_type
= {
3202 .name
= TYPE_KVM_ACCEL
,
3203 .parent
= TYPE_ACCEL
,
3204 .instance_init
= kvm_accel_instance_init
,
3205 .class_init
= kvm_accel_class_init
,
3206 .instance_size
= sizeof(KVMState
),
3209 static void kvm_type_init(void)
3211 type_register_static(&kvm_accel_type
);
3214 type_init(kvm_type_init
);