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>
20 #include <linux/kvm.h>
22 #include "qemu/atomic.h"
23 #include "qemu/option.h"
24 #include "qemu/config-file.h"
25 #include "qemu/error-report.h"
26 #include "qapi/error.h"
27 #include "hw/pci/msi.h"
28 #include "hw/pci/msix.h"
29 #include "hw/s390x/adapter.h"
30 #include "exec/gdbstub.h"
31 #include "sysemu/kvm_int.h"
32 #include "sysemu/runstate.h"
33 #include "sysemu/cpus.h"
34 #include "qemu/bswap.h"
35 #include "exec/memory.h"
36 #include "exec/ram_addr.h"
37 #include "qemu/event_notifier.h"
38 #include "qemu/main-loop.h"
41 #include "qapi/visitor.h"
42 #include "qapi/qapi-types-common.h"
43 #include "qapi/qapi-visit-common.h"
44 #include "sysemu/reset.h"
45 #include "qemu/guest-random.h"
46 #include "sysemu/hw_accel.h"
49 #include "hw/boards.h"
51 /* This check must be after config-host.h is included */
53 #include <sys/eventfd.h>
56 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
57 * need to use the real host PAGE_SIZE, as that's what KVM will use.
62 #define PAGE_SIZE qemu_real_host_page_size()
64 #ifndef KVM_GUESTDBG_BLOCKIRQ
65 #define KVM_GUESTDBG_BLOCKIRQ 0
71 #define DPRINTF(fmt, ...) \
72 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
74 #define DPRINTF(fmt, ...) \
78 #define KVM_MSI_HASHTAB_SIZE 256
80 struct KVMParkedVcpu
{
81 unsigned long vcpu_id
;
83 QLIST_ENTRY(KVMParkedVcpu
) node
;
86 enum KVMDirtyRingReaperState
{
87 KVM_DIRTY_RING_REAPER_NONE
= 0,
88 /* The reaper is sleeping */
89 KVM_DIRTY_RING_REAPER_WAIT
,
90 /* The reaper is reaping for dirty pages */
91 KVM_DIRTY_RING_REAPER_REAPING
,
95 * KVM reaper instance, responsible for collecting the KVM dirty bits
98 struct KVMDirtyRingReaper
{
99 /* The reaper thread */
100 QemuThread reaper_thr
;
101 volatile uint64_t reaper_iteration
; /* iteration number of reaper thr */
102 volatile enum KVMDirtyRingReaperState reaper_state
; /* reap thr state */
107 AccelState parent_obj
;
114 struct kvm_coalesced_mmio_ring
*coalesced_mmio_ring
;
115 bool coalesced_flush_in_progress
;
117 int robust_singlestep
;
119 #ifdef KVM_CAP_SET_GUEST_DEBUG
120 QTAILQ_HEAD(, kvm_sw_breakpoint
) kvm_sw_breakpoints
;
122 int max_nested_state_len
;
126 bool kernel_irqchip_allowed
;
127 bool kernel_irqchip_required
;
128 OnOffAuto kernel_irqchip_split
;
130 uint64_t manual_dirty_log_protect
;
131 /* The man page (and posix) say ioctl numbers are signed int, but
132 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
133 * unsigned, and treating them as signed here can break things */
134 unsigned irq_set_ioctl
;
135 unsigned int sigmask_len
;
137 #ifdef KVM_CAP_IRQ_ROUTING
138 struct kvm_irq_routing
*irq_routes
;
139 int nr_allocated_irq_routes
;
140 unsigned long *used_gsi_bitmap
;
141 unsigned int gsi_count
;
142 QTAILQ_HEAD(, KVMMSIRoute
) msi_hashtab
[KVM_MSI_HASHTAB_SIZE
];
144 KVMMemoryListener memory_listener
;
145 QLIST_HEAD(, KVMParkedVcpu
) kvm_parked_vcpus
;
147 /* For "info mtree -f" to tell if an MR is registered in KVM */
150 KVMMemoryListener
*ml
;
153 uint64_t kvm_dirty_ring_bytes
; /* Size of the per-vcpu dirty ring */
154 uint32_t kvm_dirty_ring_size
; /* Number of dirty GFNs per ring */
155 struct KVMDirtyRingReaper reaper
;
159 bool kvm_kernel_irqchip
;
160 bool kvm_split_irqchip
;
161 bool kvm_async_interrupts_allowed
;
162 bool kvm_halt_in_kernel_allowed
;
163 bool kvm_eventfds_allowed
;
164 bool kvm_irqfds_allowed
;
165 bool kvm_resamplefds_allowed
;
166 bool kvm_msi_via_irqfd_allowed
;
167 bool kvm_gsi_routing_allowed
;
168 bool kvm_gsi_direct_mapping
;
170 bool kvm_readonly_mem_allowed
;
171 bool kvm_vm_attributes_allowed
;
172 bool kvm_direct_msi_allowed
;
173 bool kvm_ioeventfd_any_length_allowed
;
174 bool kvm_msi_use_devid
;
175 bool kvm_has_guest_debug
;
177 static bool kvm_immediate_exit
;
178 static hwaddr kvm_max_slot_size
= ~0;
180 static const KVMCapabilityInfo kvm_required_capabilites
[] = {
181 KVM_CAP_INFO(USER_MEMORY
),
182 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS
),
183 KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS
),
187 static NotifierList kvm_irqchip_change_notifiers
=
188 NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers
);
190 struct KVMResampleFd
{
192 EventNotifier
*resample_event
;
193 QLIST_ENTRY(KVMResampleFd
) node
;
195 typedef struct KVMResampleFd KVMResampleFd
;
198 * Only used with split irqchip where we need to do the resample fd
199 * kick for the kernel from userspace.
201 static QLIST_HEAD(, KVMResampleFd
) kvm_resample_fd_list
=
202 QLIST_HEAD_INITIALIZER(kvm_resample_fd_list
);
204 static QemuMutex kml_slots_lock
;
206 #define kvm_slots_lock() qemu_mutex_lock(&kml_slots_lock)
207 #define kvm_slots_unlock() qemu_mutex_unlock(&kml_slots_lock)
209 static void kvm_slot_init_dirty_bitmap(KVMSlot
*mem
);
211 static inline void kvm_resample_fd_remove(int gsi
)
215 QLIST_FOREACH(rfd
, &kvm_resample_fd_list
, node
) {
216 if (rfd
->gsi
== gsi
) {
217 QLIST_REMOVE(rfd
, node
);
224 static inline void kvm_resample_fd_insert(int gsi
, EventNotifier
*event
)
226 KVMResampleFd
*rfd
= g_new0(KVMResampleFd
, 1);
229 rfd
->resample_event
= event
;
231 QLIST_INSERT_HEAD(&kvm_resample_fd_list
, rfd
, node
);
234 void kvm_resample_fd_notify(int gsi
)
238 QLIST_FOREACH(rfd
, &kvm_resample_fd_list
, node
) {
239 if (rfd
->gsi
== gsi
) {
240 event_notifier_set(rfd
->resample_event
);
241 trace_kvm_resample_fd_notify(gsi
);
247 int kvm_get_max_memslots(void)
249 KVMState
*s
= KVM_STATE(current_accel());
254 /* Called with KVMMemoryListener.slots_lock held */
255 static KVMSlot
*kvm_get_free_slot(KVMMemoryListener
*kml
)
257 KVMState
*s
= kvm_state
;
260 for (i
= 0; i
< s
->nr_slots
; i
++) {
261 if (kml
->slots
[i
].memory_size
== 0) {
262 return &kml
->slots
[i
];
269 bool kvm_has_free_slot(MachineState
*ms
)
271 KVMState
*s
= KVM_STATE(ms
->accelerator
);
273 KVMMemoryListener
*kml
= &s
->memory_listener
;
276 result
= !!kvm_get_free_slot(kml
);
282 /* Called with KVMMemoryListener.slots_lock held */
283 static KVMSlot
*kvm_alloc_slot(KVMMemoryListener
*kml
)
285 KVMSlot
*slot
= kvm_get_free_slot(kml
);
291 fprintf(stderr
, "%s: no free slot available\n", __func__
);
295 static KVMSlot
*kvm_lookup_matching_slot(KVMMemoryListener
*kml
,
299 KVMState
*s
= kvm_state
;
302 for (i
= 0; i
< s
->nr_slots
; i
++) {
303 KVMSlot
*mem
= &kml
->slots
[i
];
305 if (start_addr
== mem
->start_addr
&& size
== mem
->memory_size
) {
314 * Calculate and align the start address and the size of the section.
315 * Return the size. If the size is 0, the aligned section is empty.
317 static hwaddr
kvm_align_section(MemoryRegionSection
*section
,
320 hwaddr size
= int128_get64(section
->size
);
321 hwaddr delta
, aligned
;
323 /* kvm works in page size chunks, but the function may be called
324 with sub-page size and unaligned start address. Pad the start
325 address to next and truncate size to previous page boundary. */
326 aligned
= ROUND_UP(section
->offset_within_address_space
,
327 qemu_real_host_page_size());
328 delta
= aligned
- section
->offset_within_address_space
;
334 return (size
- delta
) & qemu_real_host_page_mask();
337 int kvm_physical_memory_addr_from_host(KVMState
*s
, void *ram
,
340 KVMMemoryListener
*kml
= &s
->memory_listener
;
344 for (i
= 0; i
< s
->nr_slots
; i
++) {
345 KVMSlot
*mem
= &kml
->slots
[i
];
347 if (ram
>= mem
->ram
&& ram
< mem
->ram
+ mem
->memory_size
) {
348 *phys_addr
= mem
->start_addr
+ (ram
- mem
->ram
);
358 static int kvm_set_user_memory_region(KVMMemoryListener
*kml
, KVMSlot
*slot
, bool new)
360 KVMState
*s
= kvm_state
;
361 struct kvm_userspace_memory_region mem
;
364 mem
.slot
= slot
->slot
| (kml
->as_id
<< 16);
365 mem
.guest_phys_addr
= slot
->start_addr
;
366 mem
.userspace_addr
= (unsigned long)slot
->ram
;
367 mem
.flags
= slot
->flags
;
369 if (slot
->memory_size
&& !new && (mem
.flags
^ slot
->old_flags
) & KVM_MEM_READONLY
) {
370 /* Set the slot size to 0 before setting the slot to the desired
371 * value. This is needed based on KVM commit 75d61fbc. */
373 ret
= kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
378 mem
.memory_size
= slot
->memory_size
;
379 ret
= kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
380 slot
->old_flags
= mem
.flags
;
382 trace_kvm_set_user_memory(mem
.slot
, mem
.flags
, mem
.guest_phys_addr
,
383 mem
.memory_size
, mem
.userspace_addr
, ret
);
385 error_report("%s: KVM_SET_USER_MEMORY_REGION failed, slot=%d,"
386 " start=0x%" PRIx64
", size=0x%" PRIx64
": %s",
387 __func__
, mem
.slot
, slot
->start_addr
,
388 (uint64_t)mem
.memory_size
, strerror(errno
));
393 static int do_kvm_destroy_vcpu(CPUState
*cpu
)
395 KVMState
*s
= kvm_state
;
397 struct KVMParkedVcpu
*vcpu
= NULL
;
400 DPRINTF("kvm_destroy_vcpu\n");
402 ret
= kvm_arch_destroy_vcpu(cpu
);
407 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
410 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
414 ret
= munmap(cpu
->kvm_run
, mmap_size
);
419 if (cpu
->kvm_dirty_gfns
) {
420 ret
= munmap(cpu
->kvm_dirty_gfns
, s
->kvm_dirty_ring_bytes
);
426 vcpu
= g_malloc0(sizeof(*vcpu
));
427 vcpu
->vcpu_id
= kvm_arch_vcpu_id(cpu
);
428 vcpu
->kvm_fd
= cpu
->kvm_fd
;
429 QLIST_INSERT_HEAD(&kvm_state
->kvm_parked_vcpus
, vcpu
, node
);
434 void kvm_destroy_vcpu(CPUState
*cpu
)
436 if (do_kvm_destroy_vcpu(cpu
) < 0) {
437 error_report("kvm_destroy_vcpu failed");
442 static int kvm_get_vcpu(KVMState
*s
, unsigned long vcpu_id
)
444 struct KVMParkedVcpu
*cpu
;
446 QLIST_FOREACH(cpu
, &s
->kvm_parked_vcpus
, node
) {
447 if (cpu
->vcpu_id
== vcpu_id
) {
450 QLIST_REMOVE(cpu
, node
);
451 kvm_fd
= cpu
->kvm_fd
;
457 return kvm_vm_ioctl(s
, KVM_CREATE_VCPU
, (void *)vcpu_id
);
460 int kvm_init_vcpu(CPUState
*cpu
, Error
**errp
)
462 KVMState
*s
= kvm_state
;
466 trace_kvm_init_vcpu(cpu
->cpu_index
, kvm_arch_vcpu_id(cpu
));
468 ret
= kvm_get_vcpu(s
, kvm_arch_vcpu_id(cpu
));
470 error_setg_errno(errp
, -ret
, "kvm_init_vcpu: kvm_get_vcpu failed (%lu)",
471 kvm_arch_vcpu_id(cpu
));
477 cpu
->vcpu_dirty
= true;
478 cpu
->dirty_pages
= 0;
480 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
483 error_setg_errno(errp
, -mmap_size
,
484 "kvm_init_vcpu: KVM_GET_VCPU_MMAP_SIZE failed");
488 cpu
->kvm_run
= mmap(NULL
, mmap_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
490 if (cpu
->kvm_run
== MAP_FAILED
) {
492 error_setg_errno(errp
, ret
,
493 "kvm_init_vcpu: mmap'ing vcpu state failed (%lu)",
494 kvm_arch_vcpu_id(cpu
));
498 if (s
->coalesced_mmio
&& !s
->coalesced_mmio_ring
) {
499 s
->coalesced_mmio_ring
=
500 (void *)cpu
->kvm_run
+ s
->coalesced_mmio
* PAGE_SIZE
;
503 if (s
->kvm_dirty_ring_size
) {
504 /* Use MAP_SHARED to share pages with the kernel */
505 cpu
->kvm_dirty_gfns
= mmap(NULL
, s
->kvm_dirty_ring_bytes
,
506 PROT_READ
| PROT_WRITE
, MAP_SHARED
,
508 PAGE_SIZE
* KVM_DIRTY_LOG_PAGE_OFFSET
);
509 if (cpu
->kvm_dirty_gfns
== MAP_FAILED
) {
511 DPRINTF("mmap'ing vcpu dirty gfns failed: %d\n", ret
);
516 ret
= kvm_arch_init_vcpu(cpu
);
518 error_setg_errno(errp
, -ret
,
519 "kvm_init_vcpu: kvm_arch_init_vcpu failed (%lu)",
520 kvm_arch_vcpu_id(cpu
));
527 * dirty pages logging control
530 static int kvm_mem_flags(MemoryRegion
*mr
)
532 bool readonly
= mr
->readonly
|| memory_region_is_romd(mr
);
535 if (memory_region_get_dirty_log_mask(mr
) != 0) {
536 flags
|= KVM_MEM_LOG_DIRTY_PAGES
;
538 if (readonly
&& kvm_readonly_mem_allowed
) {
539 flags
|= KVM_MEM_READONLY
;
544 /* Called with KVMMemoryListener.slots_lock held */
545 static int kvm_slot_update_flags(KVMMemoryListener
*kml
, KVMSlot
*mem
,
548 mem
->flags
= kvm_mem_flags(mr
);
550 /* If nothing changed effectively, no need to issue ioctl */
551 if (mem
->flags
== mem
->old_flags
) {
555 kvm_slot_init_dirty_bitmap(mem
);
556 return kvm_set_user_memory_region(kml
, mem
, false);
559 static int kvm_section_update_flags(KVMMemoryListener
*kml
,
560 MemoryRegionSection
*section
)
562 hwaddr start_addr
, size
, slot_size
;
566 size
= kvm_align_section(section
, &start_addr
);
573 while (size
&& !ret
) {
574 slot_size
= MIN(kvm_max_slot_size
, size
);
575 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
577 /* We don't have a slot if we want to trap every access. */
581 ret
= kvm_slot_update_flags(kml
, mem
, section
->mr
);
582 start_addr
+= slot_size
;
591 static void kvm_log_start(MemoryListener
*listener
,
592 MemoryRegionSection
*section
,
595 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
602 r
= kvm_section_update_flags(kml
, section
);
608 static void kvm_log_stop(MemoryListener
*listener
,
609 MemoryRegionSection
*section
,
612 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
619 r
= kvm_section_update_flags(kml
, section
);
625 /* get kvm's dirty pages bitmap and update qemu's */
626 static void kvm_slot_sync_dirty_pages(KVMSlot
*slot
)
628 ram_addr_t start
= slot
->ram_start_offset
;
629 ram_addr_t pages
= slot
->memory_size
/ qemu_real_host_page_size();
631 cpu_physical_memory_set_dirty_lebitmap(slot
->dirty_bmap
, start
, pages
);
634 static void kvm_slot_reset_dirty_pages(KVMSlot
*slot
)
636 memset(slot
->dirty_bmap
, 0, slot
->dirty_bmap_size
);
639 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
641 /* Allocate the dirty bitmap for a slot */
642 static void kvm_slot_init_dirty_bitmap(KVMSlot
*mem
)
644 if (!(mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) || mem
->dirty_bmap
) {
649 * XXX bad kernel interface alert
650 * For dirty bitmap, kernel allocates array of size aligned to
651 * bits-per-long. But for case when the kernel is 64bits and
652 * the userspace is 32bits, userspace can't align to the same
653 * bits-per-long, since sizeof(long) is different between kernel
654 * and user space. This way, userspace will provide buffer which
655 * may be 4 bytes less than the kernel will use, resulting in
656 * userspace memory corruption (which is not detectable by valgrind
657 * too, in most cases).
658 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
659 * a hope that sizeof(long) won't become >8 any time soon.
661 * Note: the granule of kvm dirty log is qemu_real_host_page_size.
662 * And mem->memory_size is aligned to it (otherwise this mem can't
663 * be registered to KVM).
665 hwaddr bitmap_size
= ALIGN(mem
->memory_size
/ qemu_real_host_page_size(),
666 /*HOST_LONG_BITS*/ 64) / 8;
667 mem
->dirty_bmap
= g_malloc0(bitmap_size
);
668 mem
->dirty_bmap_size
= bitmap_size
;
672 * Sync dirty bitmap from kernel to KVMSlot.dirty_bmap, return true if
673 * succeeded, false otherwise
675 static bool kvm_slot_get_dirty_log(KVMState
*s
, KVMSlot
*slot
)
677 struct kvm_dirty_log d
= {};
680 d
.dirty_bitmap
= slot
->dirty_bmap
;
681 d
.slot
= slot
->slot
| (slot
->as_id
<< 16);
682 ret
= kvm_vm_ioctl(s
, KVM_GET_DIRTY_LOG
, &d
);
684 if (ret
== -ENOENT
) {
685 /* kernel does not have dirty bitmap in this slot */
689 error_report_once("%s: KVM_GET_DIRTY_LOG failed with %d",
695 /* Should be with all slots_lock held for the address spaces. */
696 static void kvm_dirty_ring_mark_page(KVMState
*s
, uint32_t as_id
,
697 uint32_t slot_id
, uint64_t offset
)
699 KVMMemoryListener
*kml
;
702 if (as_id
>= s
->nr_as
) {
706 kml
= s
->as
[as_id
].ml
;
707 mem
= &kml
->slots
[slot_id
];
709 if (!mem
->memory_size
|| offset
>=
710 (mem
->memory_size
/ qemu_real_host_page_size())) {
714 set_bit(offset
, mem
->dirty_bmap
);
717 static bool dirty_gfn_is_dirtied(struct kvm_dirty_gfn
*gfn
)
719 return gfn
->flags
== KVM_DIRTY_GFN_F_DIRTY
;
722 static void dirty_gfn_set_collected(struct kvm_dirty_gfn
*gfn
)
724 gfn
->flags
= KVM_DIRTY_GFN_F_RESET
;
728 * Should be with all slots_lock held for the address spaces. It returns the
729 * dirty page we've collected on this dirty ring.
731 static uint32_t kvm_dirty_ring_reap_one(KVMState
*s
, CPUState
*cpu
)
733 struct kvm_dirty_gfn
*dirty_gfns
= cpu
->kvm_dirty_gfns
, *cur
;
734 uint32_t ring_size
= s
->kvm_dirty_ring_size
;
735 uint32_t count
= 0, fetch
= cpu
->kvm_fetch_index
;
737 assert(dirty_gfns
&& ring_size
);
738 trace_kvm_dirty_ring_reap_vcpu(cpu
->cpu_index
);
741 cur
= &dirty_gfns
[fetch
% ring_size
];
742 if (!dirty_gfn_is_dirtied(cur
)) {
745 kvm_dirty_ring_mark_page(s
, cur
->slot
>> 16, cur
->slot
& 0xffff,
747 dirty_gfn_set_collected(cur
);
748 trace_kvm_dirty_ring_page(cpu
->cpu_index
, fetch
, cur
->offset
);
752 cpu
->kvm_fetch_index
= fetch
;
753 cpu
->dirty_pages
+= count
;
758 /* Must be with slots_lock held */
759 static uint64_t kvm_dirty_ring_reap_locked(KVMState
*s
)
769 total
+= kvm_dirty_ring_reap_one(s
, cpu
);
773 ret
= kvm_vm_ioctl(s
, KVM_RESET_DIRTY_RINGS
);
774 assert(ret
== total
);
777 stamp
= get_clock() - stamp
;
780 trace_kvm_dirty_ring_reap(total
, stamp
/ 1000);
787 * Currently for simplicity, we must hold BQL before calling this. We can
788 * consider to drop the BQL if we're clear with all the race conditions.
790 static uint64_t kvm_dirty_ring_reap(KVMState
*s
)
795 * We need to lock all kvm slots for all address spaces here,
798 * (1) We need to mark dirty for dirty bitmaps in multiple slots
799 * and for tons of pages, so it's better to take the lock here
800 * once rather than once per page. And more importantly,
802 * (2) We must _NOT_ publish dirty bits to the other threads
803 * (e.g., the migration thread) via the kvm memory slot dirty
804 * bitmaps before correctly re-protect those dirtied pages.
805 * Otherwise we can have potential risk of data corruption if
806 * the page data is read in the other thread before we do
810 total
= kvm_dirty_ring_reap_locked(s
);
816 static void do_kvm_cpu_synchronize_kick(CPUState
*cpu
, run_on_cpu_data arg
)
818 /* No need to do anything */
822 * Kick all vcpus out in a synchronized way. When returned, we
823 * guarantee that every vcpu has been kicked and at least returned to
826 static void kvm_cpu_synchronize_kick_all(void)
831 run_on_cpu(cpu
, do_kvm_cpu_synchronize_kick
, RUN_ON_CPU_NULL
);
836 * Flush all the existing dirty pages to the KVM slot buffers. When
837 * this call returns, we guarantee that all the touched dirty pages
838 * before calling this function have been put into the per-kvmslot
841 * This function must be called with BQL held.
843 static void kvm_dirty_ring_flush(void)
845 trace_kvm_dirty_ring_flush(0);
847 * The function needs to be serialized. Since this function
848 * should always be with BQL held, serialization is guaranteed.
849 * However, let's be sure of it.
851 assert(qemu_mutex_iothread_locked());
853 * First make sure to flush the hardware buffers by kicking all
854 * vcpus out in a synchronous way.
856 kvm_cpu_synchronize_kick_all();
857 kvm_dirty_ring_reap(kvm_state
);
858 trace_kvm_dirty_ring_flush(1);
862 * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
864 * This function will first try to fetch dirty bitmap from the kernel,
865 * and then updates qemu's dirty bitmap.
867 * NOTE: caller must be with kml->slots_lock held.
869 * @kml: the KVM memory listener object
870 * @section: the memory section to sync the dirty bitmap with
872 static void kvm_physical_sync_dirty_bitmap(KVMMemoryListener
*kml
,
873 MemoryRegionSection
*section
)
875 KVMState
*s
= kvm_state
;
877 hwaddr start_addr
, size
;
880 size
= kvm_align_section(section
, &start_addr
);
882 slot_size
= MIN(kvm_max_slot_size
, size
);
883 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
885 /* We don't have a slot if we want to trap every access. */
888 if (kvm_slot_get_dirty_log(s
, mem
)) {
889 kvm_slot_sync_dirty_pages(mem
);
891 start_addr
+= slot_size
;
896 /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
897 #define KVM_CLEAR_LOG_SHIFT 6
898 #define KVM_CLEAR_LOG_ALIGN (qemu_real_host_page_size() << KVM_CLEAR_LOG_SHIFT)
899 #define KVM_CLEAR_LOG_MASK (-KVM_CLEAR_LOG_ALIGN)
901 static int kvm_log_clear_one_slot(KVMSlot
*mem
, int as_id
, uint64_t start
,
904 KVMState
*s
= kvm_state
;
905 uint64_t end
, bmap_start
, start_delta
, bmap_npages
;
906 struct kvm_clear_dirty_log d
;
907 unsigned long *bmap_clear
= NULL
, psize
= qemu_real_host_page_size();
911 * We need to extend either the start or the size or both to
912 * satisfy the KVM interface requirement. Firstly, do the start
913 * page alignment on 64 host pages
915 bmap_start
= start
& KVM_CLEAR_LOG_MASK
;
916 start_delta
= start
- bmap_start
;
920 * The kernel interface has restriction on the size too, that either:
922 * (1) the size is 64 host pages aligned (just like the start), or
923 * (2) the size fills up until the end of the KVM memslot.
925 bmap_npages
= DIV_ROUND_UP(size
+ start_delta
, KVM_CLEAR_LOG_ALIGN
)
926 << KVM_CLEAR_LOG_SHIFT
;
927 end
= mem
->memory_size
/ psize
;
928 if (bmap_npages
> end
- bmap_start
) {
929 bmap_npages
= end
- bmap_start
;
931 start_delta
/= psize
;
934 * Prepare the bitmap to clear dirty bits. Here we must guarantee
935 * that we won't clear any unknown dirty bits otherwise we might
936 * accidentally clear some set bits which are not yet synced from
937 * the kernel into QEMU's bitmap, then we'll lose track of the
938 * guest modifications upon those pages (which can directly lead
939 * to guest data loss or panic after migration).
941 * Layout of the KVMSlot.dirty_bmap:
943 * |<-------- bmap_npages -----------..>|
946 * |----------------|-------------|------------------|------------|
949 * start bmap_start (start) end
950 * of memslot of memslot
952 * [1] bmap_npages can be aligned to either 64 pages or the end of slot
955 assert(bmap_start
% BITS_PER_LONG
== 0);
956 /* We should never do log_clear before log_sync */
957 assert(mem
->dirty_bmap
);
958 if (start_delta
|| bmap_npages
- size
/ psize
) {
959 /* Slow path - we need to manipulate a temp bitmap */
960 bmap_clear
= bitmap_new(bmap_npages
);
961 bitmap_copy_with_src_offset(bmap_clear
, mem
->dirty_bmap
,
962 bmap_start
, start_delta
+ size
/ psize
);
964 * We need to fill the holes at start because that was not
965 * specified by the caller and we extended the bitmap only for
968 bitmap_clear(bmap_clear
, 0, start_delta
);
969 d
.dirty_bitmap
= bmap_clear
;
972 * Fast path - both start and size align well with BITS_PER_LONG
973 * (or the end of memory slot)
975 d
.dirty_bitmap
= mem
->dirty_bmap
+ BIT_WORD(bmap_start
);
978 d
.first_page
= bmap_start
;
979 /* It should never overflow. If it happens, say something */
980 assert(bmap_npages
<= UINT32_MAX
);
981 d
.num_pages
= bmap_npages
;
982 d
.slot
= mem
->slot
| (as_id
<< 16);
984 ret
= kvm_vm_ioctl(s
, KVM_CLEAR_DIRTY_LOG
, &d
);
985 if (ret
< 0 && ret
!= -ENOENT
) {
986 error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
987 "start=0x%"PRIx64
", size=0x%"PRIx32
", errno=%d",
988 __func__
, d
.slot
, (uint64_t)d
.first_page
,
989 (uint32_t)d
.num_pages
, ret
);
992 trace_kvm_clear_dirty_log(d
.slot
, d
.first_page
, d
.num_pages
);
996 * After we have updated the remote dirty bitmap, we update the
997 * cached bitmap as well for the memslot, then if another user
998 * clears the same region we know we shouldn't clear it again on
999 * the remote otherwise it's data loss as well.
1001 bitmap_clear(mem
->dirty_bmap
, bmap_start
+ start_delta
,
1003 /* This handles the NULL case well */
1010 * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
1012 * NOTE: this will be a no-op if we haven't enabled manual dirty log
1013 * protection in the host kernel because in that case this operation
1014 * will be done within log_sync().
1016 * @kml: the kvm memory listener
1017 * @section: the memory range to clear dirty bitmap
1019 static int kvm_physical_log_clear(KVMMemoryListener
*kml
,
1020 MemoryRegionSection
*section
)
1022 KVMState
*s
= kvm_state
;
1023 uint64_t start
, size
, offset
, count
;
1027 if (!s
->manual_dirty_log_protect
) {
1028 /* No need to do explicit clear */
1032 start
= section
->offset_within_address_space
;
1033 size
= int128_get64(section
->size
);
1036 /* Nothing more we can do... */
1042 for (i
= 0; i
< s
->nr_slots
; i
++) {
1043 mem
= &kml
->slots
[i
];
1044 /* Discard slots that are empty or do not overlap the section */
1045 if (!mem
->memory_size
||
1046 mem
->start_addr
> start
+ size
- 1 ||
1047 start
> mem
->start_addr
+ mem
->memory_size
- 1) {
1051 if (start
>= mem
->start_addr
) {
1052 /* The slot starts before section or is aligned to it. */
1053 offset
= start
- mem
->start_addr
;
1054 count
= MIN(mem
->memory_size
- offset
, size
);
1056 /* The slot starts after section. */
1058 count
= MIN(mem
->memory_size
, size
- (mem
->start_addr
- start
));
1060 ret
= kvm_log_clear_one_slot(mem
, kml
->as_id
, offset
, count
);
1071 static void kvm_coalesce_mmio_region(MemoryListener
*listener
,
1072 MemoryRegionSection
*secion
,
1073 hwaddr start
, hwaddr size
)
1075 KVMState
*s
= kvm_state
;
1077 if (s
->coalesced_mmio
) {
1078 struct kvm_coalesced_mmio_zone zone
;
1084 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
1088 static void kvm_uncoalesce_mmio_region(MemoryListener
*listener
,
1089 MemoryRegionSection
*secion
,
1090 hwaddr start
, hwaddr size
)
1092 KVMState
*s
= kvm_state
;
1094 if (s
->coalesced_mmio
) {
1095 struct kvm_coalesced_mmio_zone zone
;
1101 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
1105 static void kvm_coalesce_pio_add(MemoryListener
*listener
,
1106 MemoryRegionSection
*section
,
1107 hwaddr start
, hwaddr size
)
1109 KVMState
*s
= kvm_state
;
1111 if (s
->coalesced_pio
) {
1112 struct kvm_coalesced_mmio_zone zone
;
1118 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
1122 static void kvm_coalesce_pio_del(MemoryListener
*listener
,
1123 MemoryRegionSection
*section
,
1124 hwaddr start
, hwaddr size
)
1126 KVMState
*s
= kvm_state
;
1128 if (s
->coalesced_pio
) {
1129 struct kvm_coalesced_mmio_zone zone
;
1135 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
1139 static MemoryListener kvm_coalesced_pio_listener
= {
1140 .name
= "kvm-coalesced-pio",
1141 .coalesced_io_add
= kvm_coalesce_pio_add
,
1142 .coalesced_io_del
= kvm_coalesce_pio_del
,
1145 int kvm_check_extension(KVMState
*s
, unsigned int extension
)
1149 ret
= kvm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
1157 int kvm_vm_check_extension(KVMState
*s
, unsigned int extension
)
1161 ret
= kvm_vm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
1163 /* VM wide version not implemented, use global one instead */
1164 ret
= kvm_check_extension(s
, extension
);
1170 typedef struct HWPoisonPage
{
1171 ram_addr_t ram_addr
;
1172 QLIST_ENTRY(HWPoisonPage
) list
;
1175 static QLIST_HEAD(, HWPoisonPage
) hwpoison_page_list
=
1176 QLIST_HEAD_INITIALIZER(hwpoison_page_list
);
1178 static void kvm_unpoison_all(void *param
)
1180 HWPoisonPage
*page
, *next_page
;
1182 QLIST_FOREACH_SAFE(page
, &hwpoison_page_list
, list
, next_page
) {
1183 QLIST_REMOVE(page
, list
);
1184 qemu_ram_remap(page
->ram_addr
, TARGET_PAGE_SIZE
);
1189 void kvm_hwpoison_page_add(ram_addr_t ram_addr
)
1193 QLIST_FOREACH(page
, &hwpoison_page_list
, list
) {
1194 if (page
->ram_addr
== ram_addr
) {
1198 page
= g_new(HWPoisonPage
, 1);
1199 page
->ram_addr
= ram_addr
;
1200 QLIST_INSERT_HEAD(&hwpoison_page_list
, page
, list
);
1203 static uint32_t adjust_ioeventfd_endianness(uint32_t val
, uint32_t size
)
1205 #if HOST_BIG_ENDIAN != TARGET_BIG_ENDIAN
1206 /* The kernel expects ioeventfd values in HOST_BIG_ENDIAN
1207 * endianness, but the memory core hands them in target endianness.
1208 * For example, PPC is always treated as big-endian even if running
1209 * on KVM and on PPC64LE. Correct here.
1223 static int kvm_set_ioeventfd_mmio(int fd
, hwaddr addr
, uint32_t val
,
1224 bool assign
, uint32_t size
, bool datamatch
)
1227 struct kvm_ioeventfd iofd
= {
1228 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
1235 trace_kvm_set_ioeventfd_mmio(fd
, (uint64_t)addr
, val
, assign
, size
,
1237 if (!kvm_enabled()) {
1242 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
1245 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
1248 ret
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &iofd
);
1257 static int kvm_set_ioeventfd_pio(int fd
, uint16_t addr
, uint16_t val
,
1258 bool assign
, uint32_t size
, bool datamatch
)
1260 struct kvm_ioeventfd kick
= {
1261 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
1263 .flags
= KVM_IOEVENTFD_FLAG_PIO
,
1268 trace_kvm_set_ioeventfd_pio(fd
, addr
, val
, assign
, size
, datamatch
);
1269 if (!kvm_enabled()) {
1273 kick
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
1276 kick
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
1278 r
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &kick
);
1286 static int kvm_check_many_ioeventfds(void)
1288 /* Userspace can use ioeventfd for io notification. This requires a host
1289 * that supports eventfd(2) and an I/O thread; since eventfd does not
1290 * support SIGIO it cannot interrupt the vcpu.
1292 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
1293 * can avoid creating too many ioeventfds.
1295 #if defined(CONFIG_EVENTFD)
1298 for (i
= 0; i
< ARRAY_SIZE(ioeventfds
); i
++) {
1299 ioeventfds
[i
] = eventfd(0, EFD_CLOEXEC
);
1300 if (ioeventfds
[i
] < 0) {
1303 ret
= kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, true, 2, true);
1305 close(ioeventfds
[i
]);
1310 /* Decide whether many devices are supported or not */
1311 ret
= i
== ARRAY_SIZE(ioeventfds
);
1314 kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, false, 2, true);
1315 close(ioeventfds
[i
]);
1323 static const KVMCapabilityInfo
*
1324 kvm_check_extension_list(KVMState
*s
, const KVMCapabilityInfo
*list
)
1326 while (list
->name
) {
1327 if (!kvm_check_extension(s
, list
->value
)) {
1335 void kvm_set_max_memslot_size(hwaddr max_slot_size
)
1338 ROUND_UP(max_slot_size
, qemu_real_host_page_size()) == max_slot_size
1340 kvm_max_slot_size
= max_slot_size
;
1343 static void kvm_set_phys_mem(KVMMemoryListener
*kml
,
1344 MemoryRegionSection
*section
, bool add
)
1348 MemoryRegion
*mr
= section
->mr
;
1349 bool writeable
= !mr
->readonly
&& !mr
->rom_device
;
1350 hwaddr start_addr
, size
, slot_size
, mr_offset
;
1351 ram_addr_t ram_start_offset
;
1354 if (!memory_region_is_ram(mr
)) {
1355 if (writeable
|| !kvm_readonly_mem_allowed
) {
1357 } else if (!mr
->romd_mode
) {
1358 /* If the memory device is not in romd_mode, then we actually want
1359 * to remove the kvm memory slot so all accesses will trap. */
1364 size
= kvm_align_section(section
, &start_addr
);
1369 /* The offset of the kvmslot within the memory region */
1370 mr_offset
= section
->offset_within_region
+ start_addr
-
1371 section
->offset_within_address_space
;
1373 /* use aligned delta to align the ram address and offset */
1374 ram
= memory_region_get_ram_ptr(mr
) + mr_offset
;
1375 ram_start_offset
= memory_region_get_ram_addr(mr
) + mr_offset
;
1381 slot_size
= MIN(kvm_max_slot_size
, size
);
1382 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
1386 if (mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
1388 * NOTE: We should be aware of the fact that here we're only
1389 * doing a best effort to sync dirty bits. No matter whether
1390 * we're using dirty log or dirty ring, we ignored two facts:
1392 * (1) dirty bits can reside in hardware buffers (PML)
1394 * (2) after we collected dirty bits here, pages can be dirtied
1395 * again before we do the final KVM_SET_USER_MEMORY_REGION to
1398 * Not easy. Let's cross the fingers until it's fixed.
1400 if (kvm_state
->kvm_dirty_ring_size
) {
1401 kvm_dirty_ring_reap_locked(kvm_state
);
1403 kvm_slot_get_dirty_log(kvm_state
, mem
);
1405 kvm_slot_sync_dirty_pages(mem
);
1408 /* unregister the slot */
1409 g_free(mem
->dirty_bmap
);
1410 mem
->dirty_bmap
= NULL
;
1411 mem
->memory_size
= 0;
1413 err
= kvm_set_user_memory_region(kml
, mem
, false);
1415 fprintf(stderr
, "%s: error unregistering slot: %s\n",
1416 __func__
, strerror(-err
));
1419 start_addr
+= slot_size
;
1425 /* register the new slot */
1427 slot_size
= MIN(kvm_max_slot_size
, size
);
1428 mem
= kvm_alloc_slot(kml
);
1429 mem
->as_id
= kml
->as_id
;
1430 mem
->memory_size
= slot_size
;
1431 mem
->start_addr
= start_addr
;
1432 mem
->ram_start_offset
= ram_start_offset
;
1434 mem
->flags
= kvm_mem_flags(mr
);
1435 kvm_slot_init_dirty_bitmap(mem
);
1436 err
= kvm_set_user_memory_region(kml
, mem
, true);
1438 fprintf(stderr
, "%s: error registering slot: %s\n", __func__
,
1442 start_addr
+= slot_size
;
1443 ram_start_offset
+= slot_size
;
1452 static void *kvm_dirty_ring_reaper_thread(void *data
)
1455 struct KVMDirtyRingReaper
*r
= &s
->reaper
;
1457 rcu_register_thread();
1459 trace_kvm_dirty_ring_reaper("init");
1462 r
->reaper_state
= KVM_DIRTY_RING_REAPER_WAIT
;
1463 trace_kvm_dirty_ring_reaper("wait");
1465 * TODO: provide a smarter timeout rather than a constant?
1469 trace_kvm_dirty_ring_reaper("wakeup");
1470 r
->reaper_state
= KVM_DIRTY_RING_REAPER_REAPING
;
1472 qemu_mutex_lock_iothread();
1473 kvm_dirty_ring_reap(s
);
1474 qemu_mutex_unlock_iothread();
1476 r
->reaper_iteration
++;
1479 trace_kvm_dirty_ring_reaper("exit");
1481 rcu_unregister_thread();
1486 static int kvm_dirty_ring_reaper_init(KVMState
*s
)
1488 struct KVMDirtyRingReaper
*r
= &s
->reaper
;
1490 qemu_thread_create(&r
->reaper_thr
, "kvm-reaper",
1491 kvm_dirty_ring_reaper_thread
,
1492 s
, QEMU_THREAD_JOINABLE
);
1497 static void kvm_region_add(MemoryListener
*listener
,
1498 MemoryRegionSection
*section
)
1500 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1502 memory_region_ref(section
->mr
);
1503 kvm_set_phys_mem(kml
, section
, true);
1506 static void kvm_region_del(MemoryListener
*listener
,
1507 MemoryRegionSection
*section
)
1509 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1511 kvm_set_phys_mem(kml
, section
, false);
1512 memory_region_unref(section
->mr
);
1515 static void kvm_log_sync(MemoryListener
*listener
,
1516 MemoryRegionSection
*section
)
1518 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1521 kvm_physical_sync_dirty_bitmap(kml
, section
);
1525 static void kvm_log_sync_global(MemoryListener
*l
)
1527 KVMMemoryListener
*kml
= container_of(l
, KVMMemoryListener
, listener
);
1528 KVMState
*s
= kvm_state
;
1532 /* Flush all kernel dirty addresses into KVMSlot dirty bitmap */
1533 kvm_dirty_ring_flush();
1536 * TODO: make this faster when nr_slots is big while there are
1537 * only a few used slots (small VMs).
1540 for (i
= 0; i
< s
->nr_slots
; i
++) {
1541 mem
= &kml
->slots
[i
];
1542 if (mem
->memory_size
&& mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
1543 kvm_slot_sync_dirty_pages(mem
);
1545 * This is not needed by KVM_GET_DIRTY_LOG because the
1546 * ioctl will unconditionally overwrite the whole region.
1547 * However kvm dirty ring has no such side effect.
1549 kvm_slot_reset_dirty_pages(mem
);
1555 static void kvm_log_clear(MemoryListener
*listener
,
1556 MemoryRegionSection
*section
)
1558 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1561 r
= kvm_physical_log_clear(kml
, section
);
1563 error_report_once("%s: kvm log clear failed: mr=%s "
1564 "offset=%"HWADDR_PRIx
" size=%"PRIx64
, __func__
,
1565 section
->mr
->name
, section
->offset_within_region
,
1566 int128_get64(section
->size
));
1571 static void kvm_mem_ioeventfd_add(MemoryListener
*listener
,
1572 MemoryRegionSection
*section
,
1573 bool match_data
, uint64_t data
,
1576 int fd
= event_notifier_get_fd(e
);
1579 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
1580 data
, true, int128_get64(section
->size
),
1583 fprintf(stderr
, "%s: error adding ioeventfd: %s (%d)\n",
1584 __func__
, strerror(-r
), -r
);
1589 static void kvm_mem_ioeventfd_del(MemoryListener
*listener
,
1590 MemoryRegionSection
*section
,
1591 bool match_data
, uint64_t data
,
1594 int fd
= event_notifier_get_fd(e
);
1597 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
1598 data
, false, int128_get64(section
->size
),
1601 fprintf(stderr
, "%s: error deleting ioeventfd: %s (%d)\n",
1602 __func__
, strerror(-r
), -r
);
1607 static void kvm_io_ioeventfd_add(MemoryListener
*listener
,
1608 MemoryRegionSection
*section
,
1609 bool match_data
, uint64_t data
,
1612 int fd
= event_notifier_get_fd(e
);
1615 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
1616 data
, true, int128_get64(section
->size
),
1619 fprintf(stderr
, "%s: error adding ioeventfd: %s (%d)\n",
1620 __func__
, strerror(-r
), -r
);
1625 static void kvm_io_ioeventfd_del(MemoryListener
*listener
,
1626 MemoryRegionSection
*section
,
1627 bool match_data
, uint64_t data
,
1631 int fd
= event_notifier_get_fd(e
);
1634 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
1635 data
, false, int128_get64(section
->size
),
1638 fprintf(stderr
, "%s: error deleting ioeventfd: %s (%d)\n",
1639 __func__
, strerror(-r
), -r
);
1644 void kvm_memory_listener_register(KVMState
*s
, KVMMemoryListener
*kml
,
1645 AddressSpace
*as
, int as_id
, const char *name
)
1649 kml
->slots
= g_new0(KVMSlot
, s
->nr_slots
);
1652 for (i
= 0; i
< s
->nr_slots
; i
++) {
1653 kml
->slots
[i
].slot
= i
;
1656 kml
->listener
.region_add
= kvm_region_add
;
1657 kml
->listener
.region_del
= kvm_region_del
;
1658 kml
->listener
.log_start
= kvm_log_start
;
1659 kml
->listener
.log_stop
= kvm_log_stop
;
1660 kml
->listener
.priority
= 10;
1661 kml
->listener
.name
= name
;
1663 if (s
->kvm_dirty_ring_size
) {
1664 kml
->listener
.log_sync_global
= kvm_log_sync_global
;
1666 kml
->listener
.log_sync
= kvm_log_sync
;
1667 kml
->listener
.log_clear
= kvm_log_clear
;
1670 memory_listener_register(&kml
->listener
, as
);
1672 for (i
= 0; i
< s
->nr_as
; ++i
) {
1681 static MemoryListener kvm_io_listener
= {
1683 .eventfd_add
= kvm_io_ioeventfd_add
,
1684 .eventfd_del
= kvm_io_ioeventfd_del
,
1688 int kvm_set_irq(KVMState
*s
, int irq
, int level
)
1690 struct kvm_irq_level event
;
1693 assert(kvm_async_interrupts_enabled());
1695 event
.level
= level
;
1697 ret
= kvm_vm_ioctl(s
, s
->irq_set_ioctl
, &event
);
1699 perror("kvm_set_irq");
1703 return (s
->irq_set_ioctl
== KVM_IRQ_LINE
) ? 1 : event
.status
;
1706 #ifdef KVM_CAP_IRQ_ROUTING
1707 typedef struct KVMMSIRoute
{
1708 struct kvm_irq_routing_entry kroute
;
1709 QTAILQ_ENTRY(KVMMSIRoute
) entry
;
1712 static void set_gsi(KVMState
*s
, unsigned int gsi
)
1714 set_bit(gsi
, s
->used_gsi_bitmap
);
1717 static void clear_gsi(KVMState
*s
, unsigned int gsi
)
1719 clear_bit(gsi
, s
->used_gsi_bitmap
);
1722 void kvm_init_irq_routing(KVMState
*s
)
1726 gsi_count
= kvm_check_extension(s
, KVM_CAP_IRQ_ROUTING
) - 1;
1727 if (gsi_count
> 0) {
1728 /* Round up so we can search ints using ffs */
1729 s
->used_gsi_bitmap
= bitmap_new(gsi_count
);
1730 s
->gsi_count
= gsi_count
;
1733 s
->irq_routes
= g_malloc0(sizeof(*s
->irq_routes
));
1734 s
->nr_allocated_irq_routes
= 0;
1736 if (!kvm_direct_msi_allowed
) {
1737 for (i
= 0; i
< KVM_MSI_HASHTAB_SIZE
; i
++) {
1738 QTAILQ_INIT(&s
->msi_hashtab
[i
]);
1742 kvm_arch_init_irq_routing(s
);
1745 void kvm_irqchip_commit_routes(KVMState
*s
)
1749 if (kvm_gsi_direct_mapping()) {
1753 if (!kvm_gsi_routing_enabled()) {
1757 s
->irq_routes
->flags
= 0;
1758 trace_kvm_irqchip_commit_routes();
1759 ret
= kvm_vm_ioctl(s
, KVM_SET_GSI_ROUTING
, s
->irq_routes
);
1763 static void kvm_add_routing_entry(KVMState
*s
,
1764 struct kvm_irq_routing_entry
*entry
)
1766 struct kvm_irq_routing_entry
*new;
1769 if (s
->irq_routes
->nr
== s
->nr_allocated_irq_routes
) {
1770 n
= s
->nr_allocated_irq_routes
* 2;
1774 size
= sizeof(struct kvm_irq_routing
);
1775 size
+= n
* sizeof(*new);
1776 s
->irq_routes
= g_realloc(s
->irq_routes
, size
);
1777 s
->nr_allocated_irq_routes
= n
;
1779 n
= s
->irq_routes
->nr
++;
1780 new = &s
->irq_routes
->entries
[n
];
1784 set_gsi(s
, entry
->gsi
);
1787 static int kvm_update_routing_entry(KVMState
*s
,
1788 struct kvm_irq_routing_entry
*new_entry
)
1790 struct kvm_irq_routing_entry
*entry
;
1793 for (n
= 0; n
< s
->irq_routes
->nr
; n
++) {
1794 entry
= &s
->irq_routes
->entries
[n
];
1795 if (entry
->gsi
!= new_entry
->gsi
) {
1799 if(!memcmp(entry
, new_entry
, sizeof *entry
)) {
1803 *entry
= *new_entry
;
1811 void kvm_irqchip_add_irq_route(KVMState
*s
, int irq
, int irqchip
, int pin
)
1813 struct kvm_irq_routing_entry e
= {};
1815 assert(pin
< s
->gsi_count
);
1818 e
.type
= KVM_IRQ_ROUTING_IRQCHIP
;
1820 e
.u
.irqchip
.irqchip
= irqchip
;
1821 e
.u
.irqchip
.pin
= pin
;
1822 kvm_add_routing_entry(s
, &e
);
1825 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
1827 struct kvm_irq_routing_entry
*e
;
1830 if (kvm_gsi_direct_mapping()) {
1834 for (i
= 0; i
< s
->irq_routes
->nr
; i
++) {
1835 e
= &s
->irq_routes
->entries
[i
];
1836 if (e
->gsi
== virq
) {
1837 s
->irq_routes
->nr
--;
1838 *e
= s
->irq_routes
->entries
[s
->irq_routes
->nr
];
1842 kvm_arch_release_virq_post(virq
);
1843 trace_kvm_irqchip_release_virq(virq
);
1846 void kvm_irqchip_add_change_notifier(Notifier
*n
)
1848 notifier_list_add(&kvm_irqchip_change_notifiers
, n
);
1851 void kvm_irqchip_remove_change_notifier(Notifier
*n
)
1856 void kvm_irqchip_change_notify(void)
1858 notifier_list_notify(&kvm_irqchip_change_notifiers
, NULL
);
1861 static unsigned int kvm_hash_msi(uint32_t data
)
1863 /* This is optimized for IA32 MSI layout. However, no other arch shall
1864 * repeat the mistake of not providing a direct MSI injection API. */
1868 static void kvm_flush_dynamic_msi_routes(KVMState
*s
)
1870 KVMMSIRoute
*route
, *next
;
1873 for (hash
= 0; hash
< KVM_MSI_HASHTAB_SIZE
; hash
++) {
1874 QTAILQ_FOREACH_SAFE(route
, &s
->msi_hashtab
[hash
], entry
, next
) {
1875 kvm_irqchip_release_virq(s
, route
->kroute
.gsi
);
1876 QTAILQ_REMOVE(&s
->msi_hashtab
[hash
], route
, entry
);
1882 static int kvm_irqchip_get_virq(KVMState
*s
)
1887 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1888 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1889 * number can succeed even though a new route entry cannot be added.
1890 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1892 if (!kvm_direct_msi_allowed
&& s
->irq_routes
->nr
== s
->gsi_count
) {
1893 kvm_flush_dynamic_msi_routes(s
);
1896 /* Return the lowest unused GSI in the bitmap */
1897 next_virq
= find_first_zero_bit(s
->used_gsi_bitmap
, s
->gsi_count
);
1898 if (next_virq
>= s
->gsi_count
) {
1905 static KVMMSIRoute
*kvm_lookup_msi_route(KVMState
*s
, MSIMessage msg
)
1907 unsigned int hash
= kvm_hash_msi(msg
.data
);
1910 QTAILQ_FOREACH(route
, &s
->msi_hashtab
[hash
], entry
) {
1911 if (route
->kroute
.u
.msi
.address_lo
== (uint32_t)msg
.address
&&
1912 route
->kroute
.u
.msi
.address_hi
== (msg
.address
>> 32) &&
1913 route
->kroute
.u
.msi
.data
== le32_to_cpu(msg
.data
)) {
1920 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1925 if (kvm_direct_msi_allowed
) {
1926 msi
.address_lo
= (uint32_t)msg
.address
;
1927 msi
.address_hi
= msg
.address
>> 32;
1928 msi
.data
= le32_to_cpu(msg
.data
);
1930 memset(msi
.pad
, 0, sizeof(msi
.pad
));
1932 return kvm_vm_ioctl(s
, KVM_SIGNAL_MSI
, &msi
);
1935 route
= kvm_lookup_msi_route(s
, msg
);
1939 virq
= kvm_irqchip_get_virq(s
);
1944 route
= g_new0(KVMMSIRoute
, 1);
1945 route
->kroute
.gsi
= virq
;
1946 route
->kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1947 route
->kroute
.flags
= 0;
1948 route
->kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1949 route
->kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1950 route
->kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1952 kvm_add_routing_entry(s
, &route
->kroute
);
1953 kvm_irqchip_commit_routes(s
);
1955 QTAILQ_INSERT_TAIL(&s
->msi_hashtab
[kvm_hash_msi(msg
.data
)], route
,
1959 assert(route
->kroute
.type
== KVM_IRQ_ROUTING_MSI
);
1961 return kvm_set_irq(s
, route
->kroute
.gsi
, 1);
1964 int kvm_irqchip_add_msi_route(KVMRouteChange
*c
, int vector
, PCIDevice
*dev
)
1966 struct kvm_irq_routing_entry kroute
= {};
1969 MSIMessage msg
= {0, 0};
1971 if (pci_available
&& dev
) {
1972 msg
= pci_get_msi_message(dev
, vector
);
1975 if (kvm_gsi_direct_mapping()) {
1976 return kvm_arch_msi_data_to_gsi(msg
.data
);
1979 if (!kvm_gsi_routing_enabled()) {
1983 virq
= kvm_irqchip_get_virq(s
);
1989 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1991 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1992 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1993 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1994 if (pci_available
&& kvm_msi_devid_required()) {
1995 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1996 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1998 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1999 kvm_irqchip_release_virq(s
, virq
);
2003 trace_kvm_irqchip_add_msi_route(dev
? dev
->name
: (char *)"N/A",
2006 kvm_add_routing_entry(s
, &kroute
);
2007 kvm_arch_add_msi_route_post(&kroute
, vector
, dev
);
2013 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
,
2016 struct kvm_irq_routing_entry kroute
= {};
2018 if (kvm_gsi_direct_mapping()) {
2022 if (!kvm_irqchip_in_kernel()) {
2027 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
2029 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
2030 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
2031 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
2032 if (pci_available
&& kvm_msi_devid_required()) {
2033 kroute
.flags
= KVM_MSI_VALID_DEVID
;
2034 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
2036 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
2040 trace_kvm_irqchip_update_msi_route(virq
);
2042 return kvm_update_routing_entry(s
, &kroute
);
2045 static int kvm_irqchip_assign_irqfd(KVMState
*s
, EventNotifier
*event
,
2046 EventNotifier
*resample
, int virq
,
2049 int fd
= event_notifier_get_fd(event
);
2050 int rfd
= resample
? event_notifier_get_fd(resample
) : -1;
2052 struct kvm_irqfd irqfd
= {
2055 .flags
= assign
? 0 : KVM_IRQFD_FLAG_DEASSIGN
,
2060 if (kvm_irqchip_is_split()) {
2062 * When the slow irqchip (e.g. IOAPIC) is in the
2063 * userspace, KVM kernel resamplefd will not work because
2064 * the EOI of the interrupt will be delivered to userspace
2065 * instead, so the KVM kernel resamplefd kick will be
2066 * skipped. The userspace here mimics what the kernel
2067 * provides with resamplefd, remember the resamplefd and
2068 * kick it when we receive EOI of this IRQ.
2070 * This is hackery because IOAPIC is mostly bypassed
2071 * (except EOI broadcasts) when irqfd is used. However
2072 * this can bring much performance back for split irqchip
2073 * with INTx IRQs (for VFIO, this gives 93% perf of the
2074 * full fast path, which is 46% perf boost comparing to
2075 * the INTx slow path).
2077 kvm_resample_fd_insert(virq
, resample
);
2079 irqfd
.flags
|= KVM_IRQFD_FLAG_RESAMPLE
;
2080 irqfd
.resamplefd
= rfd
;
2082 } else if (!assign
) {
2083 if (kvm_irqchip_is_split()) {
2084 kvm_resample_fd_remove(virq
);
2088 if (!kvm_irqfds_enabled()) {
2092 return kvm_vm_ioctl(s
, KVM_IRQFD
, &irqfd
);
2095 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
2097 struct kvm_irq_routing_entry kroute
= {};
2100 if (!kvm_gsi_routing_enabled()) {
2104 virq
= kvm_irqchip_get_virq(s
);
2110 kroute
.type
= KVM_IRQ_ROUTING_S390_ADAPTER
;
2112 kroute
.u
.adapter
.summary_addr
= adapter
->summary_addr
;
2113 kroute
.u
.adapter
.ind_addr
= adapter
->ind_addr
;
2114 kroute
.u
.adapter
.summary_offset
= adapter
->summary_offset
;
2115 kroute
.u
.adapter
.ind_offset
= adapter
->ind_offset
;
2116 kroute
.u
.adapter
.adapter_id
= adapter
->adapter_id
;
2118 kvm_add_routing_entry(s
, &kroute
);
2123 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
2125 struct kvm_irq_routing_entry kroute
= {};
2128 if (!kvm_gsi_routing_enabled()) {
2131 if (!kvm_check_extension(s
, KVM_CAP_HYPERV_SYNIC
)) {
2134 virq
= kvm_irqchip_get_virq(s
);
2140 kroute
.type
= KVM_IRQ_ROUTING_HV_SINT
;
2142 kroute
.u
.hv_sint
.vcpu
= vcpu
;
2143 kroute
.u
.hv_sint
.sint
= sint
;
2145 kvm_add_routing_entry(s
, &kroute
);
2146 kvm_irqchip_commit_routes(s
);
2151 #else /* !KVM_CAP_IRQ_ROUTING */
2153 void kvm_init_irq_routing(KVMState
*s
)
2157 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
2161 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
2166 int kvm_irqchip_add_msi_route(KVMRouteChange
*c
, int vector
, PCIDevice
*dev
)
2171 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
2176 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
2181 static int kvm_irqchip_assign_irqfd(KVMState
*s
, EventNotifier
*event
,
2182 EventNotifier
*resample
, int virq
,
2188 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
)
2192 #endif /* !KVM_CAP_IRQ_ROUTING */
2194 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
2195 EventNotifier
*rn
, int virq
)
2197 return kvm_irqchip_assign_irqfd(s
, n
, rn
, virq
, true);
2200 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
2203 return kvm_irqchip_assign_irqfd(s
, n
, NULL
, virq
, false);
2206 int kvm_irqchip_add_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
2207 EventNotifier
*rn
, qemu_irq irq
)
2210 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
2215 return kvm_irqchip_add_irqfd_notifier_gsi(s
, n
, rn
, GPOINTER_TO_INT(gsi
));
2218 int kvm_irqchip_remove_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
2222 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
2227 return kvm_irqchip_remove_irqfd_notifier_gsi(s
, n
, GPOINTER_TO_INT(gsi
));
2230 void kvm_irqchip_set_qemuirq_gsi(KVMState
*s
, qemu_irq irq
, int gsi
)
2232 g_hash_table_insert(s
->gsimap
, irq
, GINT_TO_POINTER(gsi
));
2235 static void kvm_irqchip_create(KVMState
*s
)
2239 assert(s
->kernel_irqchip_split
!= ON_OFF_AUTO_AUTO
);
2240 if (kvm_check_extension(s
, KVM_CAP_IRQCHIP
)) {
2242 } else if (kvm_check_extension(s
, KVM_CAP_S390_IRQCHIP
)) {
2243 ret
= kvm_vm_enable_cap(s
, KVM_CAP_S390_IRQCHIP
, 0);
2245 fprintf(stderr
, "Enable kernel irqchip failed: %s\n", strerror(-ret
));
2252 /* First probe and see if there's a arch-specific hook to create the
2253 * in-kernel irqchip for us */
2254 ret
= kvm_arch_irqchip_create(s
);
2256 if (s
->kernel_irqchip_split
== ON_OFF_AUTO_ON
) {
2257 perror("Split IRQ chip mode not supported.");
2260 ret
= kvm_vm_ioctl(s
, KVM_CREATE_IRQCHIP
);
2264 fprintf(stderr
, "Create kernel irqchip failed: %s\n", strerror(-ret
));
2268 kvm_kernel_irqchip
= true;
2269 /* If we have an in-kernel IRQ chip then we must have asynchronous
2270 * interrupt delivery (though the reverse is not necessarily true)
2272 kvm_async_interrupts_allowed
= true;
2273 kvm_halt_in_kernel_allowed
= true;
2275 kvm_init_irq_routing(s
);
2277 s
->gsimap
= g_hash_table_new(g_direct_hash
, g_direct_equal
);
2280 /* Find number of supported CPUs using the recommended
2281 * procedure from the kernel API documentation to cope with
2282 * older kernels that may be missing capabilities.
2284 static int kvm_recommended_vcpus(KVMState
*s
)
2286 int ret
= kvm_vm_check_extension(s
, KVM_CAP_NR_VCPUS
);
2287 return (ret
) ? ret
: 4;
2290 static int kvm_max_vcpus(KVMState
*s
)
2292 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPUS
);
2293 return (ret
) ? ret
: kvm_recommended_vcpus(s
);
2296 static int kvm_max_vcpu_id(KVMState
*s
)
2298 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPU_ID
);
2299 return (ret
) ? ret
: kvm_max_vcpus(s
);
2302 bool kvm_vcpu_id_is_valid(int vcpu_id
)
2304 KVMState
*s
= KVM_STATE(current_accel());
2305 return vcpu_id
>= 0 && vcpu_id
< kvm_max_vcpu_id(s
);
2308 bool kvm_dirty_ring_enabled(void)
2310 return kvm_state
->kvm_dirty_ring_size
? true : false;
2313 static int kvm_init(MachineState
*ms
)
2315 MachineClass
*mc
= MACHINE_GET_CLASS(ms
);
2316 static const char upgrade_note
[] =
2317 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
2318 "(see http://sourceforge.net/projects/kvm).\n";
2323 { "SMP", ms
->smp
.cpus
},
2324 { "hotpluggable", ms
->smp
.max_cpus
},
2327 int soft_vcpus_limit
, hard_vcpus_limit
;
2329 const KVMCapabilityInfo
*missing_cap
;
2332 uint64_t dirty_log_manual_caps
;
2334 qemu_mutex_init(&kml_slots_lock
);
2336 s
= KVM_STATE(ms
->accelerator
);
2339 * On systems where the kernel can support different base page
2340 * sizes, host page size may be different from TARGET_PAGE_SIZE,
2341 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
2342 * page size for the system though.
2344 assert(TARGET_PAGE_SIZE
<= qemu_real_host_page_size());
2348 #ifdef KVM_CAP_SET_GUEST_DEBUG
2349 QTAILQ_INIT(&s
->kvm_sw_breakpoints
);
2351 QLIST_INIT(&s
->kvm_parked_vcpus
);
2352 s
->fd
= qemu_open_old("/dev/kvm", O_RDWR
);
2354 fprintf(stderr
, "Could not access KVM kernel module: %m\n");
2359 ret
= kvm_ioctl(s
, KVM_GET_API_VERSION
, 0);
2360 if (ret
< KVM_API_VERSION
) {
2364 fprintf(stderr
, "kvm version too old\n");
2368 if (ret
> KVM_API_VERSION
) {
2370 fprintf(stderr
, "kvm version not supported\n");
2374 kvm_immediate_exit
= kvm_check_extension(s
, KVM_CAP_IMMEDIATE_EXIT
);
2375 s
->nr_slots
= kvm_check_extension(s
, KVM_CAP_NR_MEMSLOTS
);
2377 /* If unspecified, use the default value */
2382 s
->nr_as
= kvm_check_extension(s
, KVM_CAP_MULTI_ADDRESS_SPACE
);
2383 if (s
->nr_as
<= 1) {
2386 s
->as
= g_new0(struct KVMAs
, s
->nr_as
);
2388 if (object_property_find(OBJECT(current_machine
), "kvm-type")) {
2389 g_autofree
char *kvm_type
= object_property_get_str(OBJECT(current_machine
),
2392 type
= mc
->kvm_type(ms
, kvm_type
);
2393 } else if (mc
->kvm_type
) {
2394 type
= mc
->kvm_type(ms
, NULL
);
2398 ret
= kvm_ioctl(s
, KVM_CREATE_VM
, type
);
2399 } while (ret
== -EINTR
);
2402 fprintf(stderr
, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret
,
2406 if (ret
== -EINVAL
) {
2408 "Host kernel setup problem detected. Please verify:\n");
2409 fprintf(stderr
, "- for kernels supporting the switch_amode or"
2410 " user_mode parameters, whether\n");
2412 " user space is running in primary address space\n");
2414 "- for kernels supporting the vm.allocate_pgste sysctl, "
2415 "whether it is enabled\n");
2417 #elif defined(TARGET_PPC)
2418 if (ret
== -EINVAL
) {
2420 "PPC KVM module is not loaded. Try modprobe kvm_%s.\n",
2421 (type
== 2) ? "pr" : "hv");
2429 /* check the vcpu limits */
2430 soft_vcpus_limit
= kvm_recommended_vcpus(s
);
2431 hard_vcpus_limit
= kvm_max_vcpus(s
);
2434 if (nc
->num
> soft_vcpus_limit
) {
2435 warn_report("Number of %s cpus requested (%d) exceeds "
2436 "the recommended cpus supported by KVM (%d)",
2437 nc
->name
, nc
->num
, soft_vcpus_limit
);
2439 if (nc
->num
> hard_vcpus_limit
) {
2440 fprintf(stderr
, "Number of %s cpus requested (%d) exceeds "
2441 "the maximum cpus supported by KVM (%d)\n",
2442 nc
->name
, nc
->num
, hard_vcpus_limit
);
2449 missing_cap
= kvm_check_extension_list(s
, kvm_required_capabilites
);
2452 kvm_check_extension_list(s
, kvm_arch_required_capabilities
);
2456 fprintf(stderr
, "kvm does not support %s\n%s",
2457 missing_cap
->name
, upgrade_note
);
2461 s
->coalesced_mmio
= kvm_check_extension(s
, KVM_CAP_COALESCED_MMIO
);
2462 s
->coalesced_pio
= s
->coalesced_mmio
&&
2463 kvm_check_extension(s
, KVM_CAP_COALESCED_PIO
);
2466 * Enable KVM dirty ring if supported, otherwise fall back to
2467 * dirty logging mode
2469 if (s
->kvm_dirty_ring_size
> 0) {
2470 uint64_t ring_bytes
;
2472 ring_bytes
= s
->kvm_dirty_ring_size
* sizeof(struct kvm_dirty_gfn
);
2474 /* Read the max supported pages */
2475 ret
= kvm_vm_check_extension(s
, KVM_CAP_DIRTY_LOG_RING
);
2477 if (ring_bytes
> ret
) {
2478 error_report("KVM dirty ring size %" PRIu32
" too big "
2479 "(maximum is %ld). Please use a smaller value.",
2480 s
->kvm_dirty_ring_size
,
2481 (long)ret
/ sizeof(struct kvm_dirty_gfn
));
2486 ret
= kvm_vm_enable_cap(s
, KVM_CAP_DIRTY_LOG_RING
, 0, ring_bytes
);
2488 error_report("Enabling of KVM dirty ring failed: %s. "
2489 "Suggested minimum value is 1024.", strerror(-ret
));
2493 s
->kvm_dirty_ring_bytes
= ring_bytes
;
2495 warn_report("KVM dirty ring not available, using bitmap method");
2496 s
->kvm_dirty_ring_size
= 0;
2501 * KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is not needed when dirty ring is
2502 * enabled. More importantly, KVM_DIRTY_LOG_INITIALLY_SET will assume no
2503 * page is wr-protected initially, which is against how kvm dirty ring is
2504 * usage - kvm dirty ring requires all pages are wr-protected at the very
2505 * beginning. Enabling this feature for dirty ring causes data corruption.
2507 * TODO: Without KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 and kvm clear dirty log,
2508 * we may expect a higher stall time when starting the migration. In the
2509 * future we can enable KVM_CLEAR_DIRTY_LOG to work with dirty ring too:
2510 * instead of clearing dirty bit, it can be a way to explicitly wr-protect
2513 if (!s
->kvm_dirty_ring_size
) {
2514 dirty_log_manual_caps
=
2515 kvm_check_extension(s
, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2
);
2516 dirty_log_manual_caps
&= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE
|
2517 KVM_DIRTY_LOG_INITIALLY_SET
);
2518 s
->manual_dirty_log_protect
= dirty_log_manual_caps
;
2519 if (dirty_log_manual_caps
) {
2520 ret
= kvm_vm_enable_cap(s
, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2
, 0,
2521 dirty_log_manual_caps
);
2523 warn_report("Trying to enable capability %"PRIu64
" of "
2524 "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
2525 "Falling back to the legacy mode. ",
2526 dirty_log_manual_caps
);
2527 s
->manual_dirty_log_protect
= 0;
2532 #ifdef KVM_CAP_VCPU_EVENTS
2533 s
->vcpu_events
= kvm_check_extension(s
, KVM_CAP_VCPU_EVENTS
);
2536 s
->robust_singlestep
=
2537 kvm_check_extension(s
, KVM_CAP_X86_ROBUST_SINGLESTEP
);
2539 #ifdef KVM_CAP_DEBUGREGS
2540 s
->debugregs
= kvm_check_extension(s
, KVM_CAP_DEBUGREGS
);
2543 s
->max_nested_state_len
= kvm_check_extension(s
, KVM_CAP_NESTED_STATE
);
2545 #ifdef KVM_CAP_IRQ_ROUTING
2546 kvm_direct_msi_allowed
= (kvm_check_extension(s
, KVM_CAP_SIGNAL_MSI
) > 0);
2549 s
->intx_set_mask
= kvm_check_extension(s
, KVM_CAP_PCI_2_3
);
2551 s
->irq_set_ioctl
= KVM_IRQ_LINE
;
2552 if (kvm_check_extension(s
, KVM_CAP_IRQ_INJECT_STATUS
)) {
2553 s
->irq_set_ioctl
= KVM_IRQ_LINE_STATUS
;
2556 kvm_readonly_mem_allowed
=
2557 (kvm_check_extension(s
, KVM_CAP_READONLY_MEM
) > 0);
2559 kvm_eventfds_allowed
=
2560 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD
) > 0);
2562 kvm_irqfds_allowed
=
2563 (kvm_check_extension(s
, KVM_CAP_IRQFD
) > 0);
2565 kvm_resamplefds_allowed
=
2566 (kvm_check_extension(s
, KVM_CAP_IRQFD_RESAMPLE
) > 0);
2568 kvm_vm_attributes_allowed
=
2569 (kvm_check_extension(s
, KVM_CAP_VM_ATTRIBUTES
) > 0);
2571 kvm_ioeventfd_any_length_allowed
=
2572 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD_ANY_LENGTH
) > 0);
2574 #ifdef KVM_CAP_SET_GUEST_DEBUG
2575 kvm_has_guest_debug
=
2576 (kvm_check_extension(s
, KVM_CAP_SET_GUEST_DEBUG
) > 0);
2579 kvm_sstep_flags
= 0;
2580 if (kvm_has_guest_debug
) {
2581 kvm_sstep_flags
= SSTEP_ENABLE
;
2583 #if defined KVM_CAP_SET_GUEST_DEBUG2
2584 int guest_debug_flags
=
2585 kvm_check_extension(s
, KVM_CAP_SET_GUEST_DEBUG2
);
2587 if (guest_debug_flags
& KVM_GUESTDBG_BLOCKIRQ
) {
2588 kvm_sstep_flags
|= SSTEP_NOIRQ
;
2595 ret
= kvm_arch_init(ms
, s
);
2600 if (s
->kernel_irqchip_split
== ON_OFF_AUTO_AUTO
) {
2601 s
->kernel_irqchip_split
= mc
->default_kernel_irqchip_split
? ON_OFF_AUTO_ON
: ON_OFF_AUTO_OFF
;
2604 qemu_register_reset(kvm_unpoison_all
, NULL
);
2606 if (s
->kernel_irqchip_allowed
) {
2607 kvm_irqchip_create(s
);
2610 if (kvm_eventfds_allowed
) {
2611 s
->memory_listener
.listener
.eventfd_add
= kvm_mem_ioeventfd_add
;
2612 s
->memory_listener
.listener
.eventfd_del
= kvm_mem_ioeventfd_del
;
2614 s
->memory_listener
.listener
.coalesced_io_add
= kvm_coalesce_mmio_region
;
2615 s
->memory_listener
.listener
.coalesced_io_del
= kvm_uncoalesce_mmio_region
;
2617 kvm_memory_listener_register(s
, &s
->memory_listener
,
2618 &address_space_memory
, 0, "kvm-memory");
2619 if (kvm_eventfds_allowed
) {
2620 memory_listener_register(&kvm_io_listener
,
2623 memory_listener_register(&kvm_coalesced_pio_listener
,
2626 s
->many_ioeventfds
= kvm_check_many_ioeventfds();
2628 s
->sync_mmu
= !!kvm_vm_check_extension(kvm_state
, KVM_CAP_SYNC_MMU
);
2630 ret
= ram_block_discard_disable(true);
2634 if (s
->kvm_dirty_ring_size
) {
2635 ret
= kvm_dirty_ring_reaper_init(s
);
2651 g_free(s
->memory_listener
.slots
);
2656 void kvm_set_sigmask_len(KVMState
*s
, unsigned int sigmask_len
)
2658 s
->sigmask_len
= sigmask_len
;
2661 static void kvm_handle_io(uint16_t port
, MemTxAttrs attrs
, void *data
, int direction
,
2662 int size
, uint32_t count
)
2665 uint8_t *ptr
= data
;
2667 for (i
= 0; i
< count
; i
++) {
2668 address_space_rw(&address_space_io
, port
, attrs
,
2670 direction
== KVM_EXIT_IO_OUT
);
2675 static int kvm_handle_internal_error(CPUState
*cpu
, struct kvm_run
*run
)
2677 fprintf(stderr
, "KVM internal error. Suberror: %d\n",
2678 run
->internal
.suberror
);
2680 if (kvm_check_extension(kvm_state
, KVM_CAP_INTERNAL_ERROR_DATA
)) {
2683 for (i
= 0; i
< run
->internal
.ndata
; ++i
) {
2684 fprintf(stderr
, "extra data[%d]: 0x%016"PRIx64
"\n",
2685 i
, (uint64_t)run
->internal
.data
[i
]);
2688 if (run
->internal
.suberror
== KVM_INTERNAL_ERROR_EMULATION
) {
2689 fprintf(stderr
, "emulation failure\n");
2690 if (!kvm_arch_stop_on_emulation_error(cpu
)) {
2691 cpu_dump_state(cpu
, stderr
, CPU_DUMP_CODE
);
2692 return EXCP_INTERRUPT
;
2695 /* FIXME: Should trigger a qmp message to let management know
2696 * something went wrong.
2701 void kvm_flush_coalesced_mmio_buffer(void)
2703 KVMState
*s
= kvm_state
;
2705 if (s
->coalesced_flush_in_progress
) {
2709 s
->coalesced_flush_in_progress
= true;
2711 if (s
->coalesced_mmio_ring
) {
2712 struct kvm_coalesced_mmio_ring
*ring
= s
->coalesced_mmio_ring
;
2713 while (ring
->first
!= ring
->last
) {
2714 struct kvm_coalesced_mmio
*ent
;
2716 ent
= &ring
->coalesced_mmio
[ring
->first
];
2718 if (ent
->pio
== 1) {
2719 address_space_write(&address_space_io
, ent
->phys_addr
,
2720 MEMTXATTRS_UNSPECIFIED
, ent
->data
,
2723 cpu_physical_memory_write(ent
->phys_addr
, ent
->data
, ent
->len
);
2726 ring
->first
= (ring
->first
+ 1) % KVM_COALESCED_MMIO_MAX
;
2730 s
->coalesced_flush_in_progress
= false;
2733 bool kvm_cpu_check_are_resettable(void)
2735 return kvm_arch_cpu_check_are_resettable();
2738 static void do_kvm_cpu_synchronize_state(CPUState
*cpu
, run_on_cpu_data arg
)
2740 if (!cpu
->vcpu_dirty
) {
2741 kvm_arch_get_registers(cpu
);
2742 cpu
->vcpu_dirty
= true;
2746 void kvm_cpu_synchronize_state(CPUState
*cpu
)
2748 if (!cpu
->vcpu_dirty
) {
2749 run_on_cpu(cpu
, do_kvm_cpu_synchronize_state
, RUN_ON_CPU_NULL
);
2753 static void do_kvm_cpu_synchronize_post_reset(CPUState
*cpu
, run_on_cpu_data arg
)
2755 kvm_arch_put_registers(cpu
, KVM_PUT_RESET_STATE
);
2756 cpu
->vcpu_dirty
= false;
2759 void kvm_cpu_synchronize_post_reset(CPUState
*cpu
)
2761 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_reset
, RUN_ON_CPU_NULL
);
2764 static void do_kvm_cpu_synchronize_post_init(CPUState
*cpu
, run_on_cpu_data arg
)
2766 kvm_arch_put_registers(cpu
, KVM_PUT_FULL_STATE
);
2767 cpu
->vcpu_dirty
= false;
2770 void kvm_cpu_synchronize_post_init(CPUState
*cpu
)
2772 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_init
, RUN_ON_CPU_NULL
);
2775 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
, run_on_cpu_data arg
)
2777 cpu
->vcpu_dirty
= true;
2780 void kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
)
2782 run_on_cpu(cpu
, do_kvm_cpu_synchronize_pre_loadvm
, RUN_ON_CPU_NULL
);
2785 #ifdef KVM_HAVE_MCE_INJECTION
2786 static __thread
void *pending_sigbus_addr
;
2787 static __thread
int pending_sigbus_code
;
2788 static __thread
bool have_sigbus_pending
;
2791 static void kvm_cpu_kick(CPUState
*cpu
)
2793 qatomic_set(&cpu
->kvm_run
->immediate_exit
, 1);
2796 static void kvm_cpu_kick_self(void)
2798 if (kvm_immediate_exit
) {
2799 kvm_cpu_kick(current_cpu
);
2801 qemu_cpu_kick_self();
2805 static void kvm_eat_signals(CPUState
*cpu
)
2807 struct timespec ts
= { 0, 0 };
2813 if (kvm_immediate_exit
) {
2814 qatomic_set(&cpu
->kvm_run
->immediate_exit
, 0);
2815 /* Write kvm_run->immediate_exit before the cpu->exit_request
2816 * write in kvm_cpu_exec.
2822 sigemptyset(&waitset
);
2823 sigaddset(&waitset
, SIG_IPI
);
2826 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
2827 if (r
== -1 && !(errno
== EAGAIN
|| errno
== EINTR
)) {
2828 perror("sigtimedwait");
2832 r
= sigpending(&chkset
);
2834 perror("sigpending");
2837 } while (sigismember(&chkset
, SIG_IPI
));
2840 int kvm_cpu_exec(CPUState
*cpu
)
2842 struct kvm_run
*run
= cpu
->kvm_run
;
2845 DPRINTF("kvm_cpu_exec()\n");
2847 if (kvm_arch_process_async_events(cpu
)) {
2848 qatomic_set(&cpu
->exit_request
, 0);
2852 qemu_mutex_unlock_iothread();
2853 cpu_exec_start(cpu
);
2858 if (cpu
->vcpu_dirty
) {
2859 kvm_arch_put_registers(cpu
, KVM_PUT_RUNTIME_STATE
);
2860 cpu
->vcpu_dirty
= false;
2863 kvm_arch_pre_run(cpu
, run
);
2864 if (qatomic_read(&cpu
->exit_request
)) {
2865 DPRINTF("interrupt exit requested\n");
2867 * KVM requires us to reenter the kernel after IO exits to complete
2868 * instruction emulation. This self-signal will ensure that we
2871 kvm_cpu_kick_self();
2874 /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2875 * Matching barrier in kvm_eat_signals.
2879 run_ret
= kvm_vcpu_ioctl(cpu
, KVM_RUN
, 0);
2881 attrs
= kvm_arch_post_run(cpu
, run
);
2883 #ifdef KVM_HAVE_MCE_INJECTION
2884 if (unlikely(have_sigbus_pending
)) {
2885 qemu_mutex_lock_iothread();
2886 kvm_arch_on_sigbus_vcpu(cpu
, pending_sigbus_code
,
2887 pending_sigbus_addr
);
2888 have_sigbus_pending
= false;
2889 qemu_mutex_unlock_iothread();
2894 if (run_ret
== -EINTR
|| run_ret
== -EAGAIN
) {
2895 DPRINTF("io window exit\n");
2896 kvm_eat_signals(cpu
);
2897 ret
= EXCP_INTERRUPT
;
2900 fprintf(stderr
, "error: kvm run failed %s\n",
2901 strerror(-run_ret
));
2903 if (run_ret
== -EBUSY
) {
2905 "This is probably because your SMT is enabled.\n"
2906 "VCPU can only run on primary threads with all "
2907 "secondary threads offline.\n");
2914 trace_kvm_run_exit(cpu
->cpu_index
, run
->exit_reason
);
2915 switch (run
->exit_reason
) {
2917 DPRINTF("handle_io\n");
2918 /* Called outside BQL */
2919 kvm_handle_io(run
->io
.port
, attrs
,
2920 (uint8_t *)run
+ run
->io
.data_offset
,
2927 DPRINTF("handle_mmio\n");
2928 /* Called outside BQL */
2929 address_space_rw(&address_space_memory
,
2930 run
->mmio
.phys_addr
, attrs
,
2933 run
->mmio
.is_write
);
2936 case KVM_EXIT_IRQ_WINDOW_OPEN
:
2937 DPRINTF("irq_window_open\n");
2938 ret
= EXCP_INTERRUPT
;
2940 case KVM_EXIT_SHUTDOWN
:
2941 DPRINTF("shutdown\n");
2942 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
2943 ret
= EXCP_INTERRUPT
;
2945 case KVM_EXIT_UNKNOWN
:
2946 fprintf(stderr
, "KVM: unknown exit, hardware reason %" PRIx64
"\n",
2947 (uint64_t)run
->hw
.hardware_exit_reason
);
2950 case KVM_EXIT_INTERNAL_ERROR
:
2951 ret
= kvm_handle_internal_error(cpu
, run
);
2953 case KVM_EXIT_DIRTY_RING_FULL
:
2955 * We shouldn't continue if the dirty ring of this vcpu is
2956 * still full. Got kicked by KVM_RESET_DIRTY_RINGS.
2958 trace_kvm_dirty_ring_full(cpu
->cpu_index
);
2959 qemu_mutex_lock_iothread();
2960 kvm_dirty_ring_reap(kvm_state
);
2961 qemu_mutex_unlock_iothread();
2964 case KVM_EXIT_SYSTEM_EVENT
:
2965 switch (run
->system_event
.type
) {
2966 case KVM_SYSTEM_EVENT_SHUTDOWN
:
2967 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN
);
2968 ret
= EXCP_INTERRUPT
;
2970 case KVM_SYSTEM_EVENT_RESET
:
2971 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
2972 ret
= EXCP_INTERRUPT
;
2974 case KVM_SYSTEM_EVENT_CRASH
:
2975 kvm_cpu_synchronize_state(cpu
);
2976 qemu_mutex_lock_iothread();
2977 qemu_system_guest_panicked(cpu_get_crash_info(cpu
));
2978 qemu_mutex_unlock_iothread();
2982 DPRINTF("kvm_arch_handle_exit\n");
2983 ret
= kvm_arch_handle_exit(cpu
, run
);
2988 DPRINTF("kvm_arch_handle_exit\n");
2989 ret
= kvm_arch_handle_exit(cpu
, run
);
2995 qemu_mutex_lock_iothread();
2998 cpu_dump_state(cpu
, stderr
, CPU_DUMP_CODE
);
2999 vm_stop(RUN_STATE_INTERNAL_ERROR
);
3002 qatomic_set(&cpu
->exit_request
, 0);
3006 int kvm_ioctl(KVMState
*s
, int type
, ...)
3013 arg
= va_arg(ap
, void *);
3016 trace_kvm_ioctl(type
, arg
);
3017 ret
= ioctl(s
->fd
, type
, arg
);
3024 int kvm_vm_ioctl(KVMState
*s
, int type
, ...)
3031 arg
= va_arg(ap
, void *);
3034 trace_kvm_vm_ioctl(type
, arg
);
3035 ret
= ioctl(s
->vmfd
, type
, arg
);
3042 int kvm_vcpu_ioctl(CPUState
*cpu
, int type
, ...)
3049 arg
= va_arg(ap
, void *);
3052 trace_kvm_vcpu_ioctl(cpu
->cpu_index
, type
, arg
);
3053 ret
= ioctl(cpu
->kvm_fd
, type
, arg
);
3060 int kvm_device_ioctl(int fd
, int type
, ...)
3067 arg
= va_arg(ap
, void *);
3070 trace_kvm_device_ioctl(fd
, type
, arg
);
3071 ret
= ioctl(fd
, type
, arg
);
3078 int kvm_vm_check_attr(KVMState
*s
, uint32_t group
, uint64_t attr
)
3081 struct kvm_device_attr attribute
= {
3086 if (!kvm_vm_attributes_allowed
) {
3090 ret
= kvm_vm_ioctl(s
, KVM_HAS_DEVICE_ATTR
, &attribute
);
3091 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
3095 int kvm_device_check_attr(int dev_fd
, uint32_t group
, uint64_t attr
)
3097 struct kvm_device_attr attribute
= {
3103 return kvm_device_ioctl(dev_fd
, KVM_HAS_DEVICE_ATTR
, &attribute
) ? 0 : 1;
3106 int kvm_device_access(int fd
, int group
, uint64_t attr
,
3107 void *val
, bool write
, Error
**errp
)
3109 struct kvm_device_attr kvmattr
;
3113 kvmattr
.group
= group
;
3114 kvmattr
.attr
= attr
;
3115 kvmattr
.addr
= (uintptr_t)val
;
3117 err
= kvm_device_ioctl(fd
,
3118 write
? KVM_SET_DEVICE_ATTR
: KVM_GET_DEVICE_ATTR
,
3121 error_setg_errno(errp
, -err
,
3122 "KVM_%s_DEVICE_ATTR failed: Group %d "
3123 "attr 0x%016" PRIx64
,
3124 write
? "SET" : "GET", group
, attr
);
3129 bool kvm_has_sync_mmu(void)
3131 return kvm_state
->sync_mmu
;
3134 int kvm_has_vcpu_events(void)
3136 return kvm_state
->vcpu_events
;
3139 int kvm_has_robust_singlestep(void)
3141 return kvm_state
->robust_singlestep
;
3144 int kvm_has_debugregs(void)
3146 return kvm_state
->debugregs
;
3149 int kvm_max_nested_state_length(void)
3151 return kvm_state
->max_nested_state_len
;
3154 int kvm_has_many_ioeventfds(void)
3156 if (!kvm_enabled()) {
3159 return kvm_state
->many_ioeventfds
;
3162 int kvm_has_gsi_routing(void)
3164 #ifdef KVM_CAP_IRQ_ROUTING
3165 return kvm_check_extension(kvm_state
, KVM_CAP_IRQ_ROUTING
);
3171 int kvm_has_intx_set_mask(void)
3173 return kvm_state
->intx_set_mask
;
3176 bool kvm_arm_supports_user_irq(void)
3178 return kvm_check_extension(kvm_state
, KVM_CAP_ARM_USER_IRQ
);
3181 #ifdef KVM_CAP_SET_GUEST_DEBUG
3182 struct kvm_sw_breakpoint
*kvm_find_sw_breakpoint(CPUState
*cpu
,
3185 struct kvm_sw_breakpoint
*bp
;
3187 QTAILQ_FOREACH(bp
, &cpu
->kvm_state
->kvm_sw_breakpoints
, entry
) {
3195 int kvm_sw_breakpoints_active(CPUState
*cpu
)
3197 return !QTAILQ_EMPTY(&cpu
->kvm_state
->kvm_sw_breakpoints
);
3200 struct kvm_set_guest_debug_data
{
3201 struct kvm_guest_debug dbg
;
3205 static void kvm_invoke_set_guest_debug(CPUState
*cpu
, run_on_cpu_data data
)
3207 struct kvm_set_guest_debug_data
*dbg_data
=
3208 (struct kvm_set_guest_debug_data
*) data
.host_ptr
;
3210 dbg_data
->err
= kvm_vcpu_ioctl(cpu
, KVM_SET_GUEST_DEBUG
,
3214 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
3216 struct kvm_set_guest_debug_data data
;
3218 data
.dbg
.control
= reinject_trap
;
3220 if (cpu
->singlestep_enabled
) {
3221 data
.dbg
.control
|= KVM_GUESTDBG_ENABLE
| KVM_GUESTDBG_SINGLESTEP
;
3223 if (cpu
->singlestep_enabled
& SSTEP_NOIRQ
) {
3224 data
.dbg
.control
|= KVM_GUESTDBG_BLOCKIRQ
;
3227 kvm_arch_update_guest_debug(cpu
, &data
.dbg
);
3229 run_on_cpu(cpu
, kvm_invoke_set_guest_debug
,
3230 RUN_ON_CPU_HOST_PTR(&data
));
3234 int kvm_insert_breakpoint(CPUState
*cpu
, target_ulong addr
,
3235 target_ulong len
, int type
)
3237 struct kvm_sw_breakpoint
*bp
;
3240 if (type
== GDB_BREAKPOINT_SW
) {
3241 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
3247 bp
= g_new(struct kvm_sw_breakpoint
, 1);
3250 err
= kvm_arch_insert_sw_breakpoint(cpu
, bp
);
3256 QTAILQ_INSERT_HEAD(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
3258 err
= kvm_arch_insert_hw_breakpoint(addr
, len
, type
);
3265 err
= kvm_update_guest_debug(cpu
, 0);
3273 int kvm_remove_breakpoint(CPUState
*cpu
, target_ulong addr
,
3274 target_ulong len
, int type
)
3276 struct kvm_sw_breakpoint
*bp
;
3279 if (type
== GDB_BREAKPOINT_SW
) {
3280 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
3285 if (bp
->use_count
> 1) {
3290 err
= kvm_arch_remove_sw_breakpoint(cpu
, bp
);
3295 QTAILQ_REMOVE(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
3298 err
= kvm_arch_remove_hw_breakpoint(addr
, len
, type
);
3305 err
= kvm_update_guest_debug(cpu
, 0);
3313 void kvm_remove_all_breakpoints(CPUState
*cpu
)
3315 struct kvm_sw_breakpoint
*bp
, *next
;
3316 KVMState
*s
= cpu
->kvm_state
;
3319 QTAILQ_FOREACH_SAFE(bp
, &s
->kvm_sw_breakpoints
, entry
, next
) {
3320 if (kvm_arch_remove_sw_breakpoint(cpu
, bp
) != 0) {
3321 /* Try harder to find a CPU that currently sees the breakpoint. */
3322 CPU_FOREACH(tmpcpu
) {
3323 if (kvm_arch_remove_sw_breakpoint(tmpcpu
, bp
) == 0) {
3328 QTAILQ_REMOVE(&s
->kvm_sw_breakpoints
, bp
, entry
);
3331 kvm_arch_remove_all_hw_breakpoints();
3334 kvm_update_guest_debug(cpu
, 0);
3338 #else /* !KVM_CAP_SET_GUEST_DEBUG */
3340 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
3345 int kvm_insert_breakpoint(CPUState
*cpu
, target_ulong addr
,
3346 target_ulong len
, int type
)
3351 int kvm_remove_breakpoint(CPUState
*cpu
, target_ulong addr
,
3352 target_ulong len
, int type
)
3357 void kvm_remove_all_breakpoints(CPUState
*cpu
)
3360 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
3362 static int kvm_set_signal_mask(CPUState
*cpu
, const sigset_t
*sigset
)
3364 KVMState
*s
= kvm_state
;
3365 struct kvm_signal_mask
*sigmask
;
3368 sigmask
= g_malloc(sizeof(*sigmask
) + sizeof(*sigset
));
3370 sigmask
->len
= s
->sigmask_len
;
3371 memcpy(sigmask
->sigset
, sigset
, sizeof(*sigset
));
3372 r
= kvm_vcpu_ioctl(cpu
, KVM_SET_SIGNAL_MASK
, sigmask
);
3378 static void kvm_ipi_signal(int sig
)
3381 assert(kvm_immediate_exit
);
3382 kvm_cpu_kick(current_cpu
);
3386 void kvm_init_cpu_signals(CPUState
*cpu
)
3390 struct sigaction sigact
;
3392 memset(&sigact
, 0, sizeof(sigact
));
3393 sigact
.sa_handler
= kvm_ipi_signal
;
3394 sigaction(SIG_IPI
, &sigact
, NULL
);
3396 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
3397 #if defined KVM_HAVE_MCE_INJECTION
3398 sigdelset(&set
, SIGBUS
);
3399 pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
3401 sigdelset(&set
, SIG_IPI
);
3402 if (kvm_immediate_exit
) {
3403 r
= pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
3405 r
= kvm_set_signal_mask(cpu
, &set
);
3408 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(-r
));
3413 /* Called asynchronously in VCPU thread. */
3414 int kvm_on_sigbus_vcpu(CPUState
*cpu
, int code
, void *addr
)
3416 #ifdef KVM_HAVE_MCE_INJECTION
3417 if (have_sigbus_pending
) {
3420 have_sigbus_pending
= true;
3421 pending_sigbus_addr
= addr
;
3422 pending_sigbus_code
= code
;
3423 qatomic_set(&cpu
->exit_request
, 1);
3430 /* Called synchronously (via signalfd) in main thread. */
3431 int kvm_on_sigbus(int code
, void *addr
)
3433 #ifdef KVM_HAVE_MCE_INJECTION
3434 /* Action required MCE kills the process if SIGBUS is blocked. Because
3435 * that's what happens in the I/O thread, where we handle MCE via signalfd,
3436 * we can only get action optional here.
3438 assert(code
!= BUS_MCEERR_AR
);
3439 kvm_arch_on_sigbus_vcpu(first_cpu
, code
, addr
);
3446 int kvm_create_device(KVMState
*s
, uint64_t type
, bool test
)
3449 struct kvm_create_device create_dev
;
3451 create_dev
.type
= type
;
3453 create_dev
.flags
= test
? KVM_CREATE_DEVICE_TEST
: 0;
3455 if (!kvm_check_extension(s
, KVM_CAP_DEVICE_CTRL
)) {
3459 ret
= kvm_vm_ioctl(s
, KVM_CREATE_DEVICE
, &create_dev
);
3464 return test
? 0 : create_dev
.fd
;
3467 bool kvm_device_supported(int vmfd
, uint64_t type
)
3469 struct kvm_create_device create_dev
= {
3472 .flags
= KVM_CREATE_DEVICE_TEST
,
3475 if (ioctl(vmfd
, KVM_CHECK_EXTENSION
, KVM_CAP_DEVICE_CTRL
) <= 0) {
3479 return (ioctl(vmfd
, KVM_CREATE_DEVICE
, &create_dev
) >= 0);
3482 int kvm_set_one_reg(CPUState
*cs
, uint64_t id
, void *source
)
3484 struct kvm_one_reg reg
;
3488 reg
.addr
= (uintptr_t) source
;
3489 r
= kvm_vcpu_ioctl(cs
, KVM_SET_ONE_REG
, ®
);
3491 trace_kvm_failed_reg_set(id
, strerror(-r
));
3496 int kvm_get_one_reg(CPUState
*cs
, uint64_t id
, void *target
)
3498 struct kvm_one_reg reg
;
3502 reg
.addr
= (uintptr_t) target
;
3503 r
= kvm_vcpu_ioctl(cs
, KVM_GET_ONE_REG
, ®
);
3505 trace_kvm_failed_reg_get(id
, strerror(-r
));
3510 static bool kvm_accel_has_memory(MachineState
*ms
, AddressSpace
*as
,
3511 hwaddr start_addr
, hwaddr size
)
3513 KVMState
*kvm
= KVM_STATE(ms
->accelerator
);
3516 for (i
= 0; i
< kvm
->nr_as
; ++i
) {
3517 if (kvm
->as
[i
].as
== as
&& kvm
->as
[i
].ml
) {
3518 size
= MIN(kvm_max_slot_size
, size
);
3519 return NULL
!= kvm_lookup_matching_slot(kvm
->as
[i
].ml
,
3527 static void kvm_get_kvm_shadow_mem(Object
*obj
, Visitor
*v
,
3528 const char *name
, void *opaque
,
3531 KVMState
*s
= KVM_STATE(obj
);
3532 int64_t value
= s
->kvm_shadow_mem
;
3534 visit_type_int(v
, name
, &value
, errp
);
3537 static void kvm_set_kvm_shadow_mem(Object
*obj
, Visitor
*v
,
3538 const char *name
, void *opaque
,
3541 KVMState
*s
= KVM_STATE(obj
);
3545 error_setg(errp
, "Cannot set properties after the accelerator has been initialized");
3549 if (!visit_type_int(v
, name
, &value
, errp
)) {
3553 s
->kvm_shadow_mem
= value
;
3556 static void kvm_set_kernel_irqchip(Object
*obj
, Visitor
*v
,
3557 const char *name
, void *opaque
,
3560 KVMState
*s
= KVM_STATE(obj
);
3564 error_setg(errp
, "Cannot set properties after the accelerator has been initialized");
3568 if (!visit_type_OnOffSplit(v
, name
, &mode
, errp
)) {
3572 case ON_OFF_SPLIT_ON
:
3573 s
->kernel_irqchip_allowed
= true;
3574 s
->kernel_irqchip_required
= true;
3575 s
->kernel_irqchip_split
= ON_OFF_AUTO_OFF
;
3577 case ON_OFF_SPLIT_OFF
:
3578 s
->kernel_irqchip_allowed
= false;
3579 s
->kernel_irqchip_required
= false;
3580 s
->kernel_irqchip_split
= ON_OFF_AUTO_OFF
;
3582 case ON_OFF_SPLIT_SPLIT
:
3583 s
->kernel_irqchip_allowed
= true;
3584 s
->kernel_irqchip_required
= true;
3585 s
->kernel_irqchip_split
= ON_OFF_AUTO_ON
;
3588 /* The value was checked in visit_type_OnOffSplit() above. If
3589 * we get here, then something is wrong in QEMU.
3595 bool kvm_kernel_irqchip_allowed(void)
3597 return kvm_state
->kernel_irqchip_allowed
;
3600 bool kvm_kernel_irqchip_required(void)
3602 return kvm_state
->kernel_irqchip_required
;
3605 bool kvm_kernel_irqchip_split(void)
3607 return kvm_state
->kernel_irqchip_split
== ON_OFF_AUTO_ON
;
3610 static void kvm_get_dirty_ring_size(Object
*obj
, Visitor
*v
,
3611 const char *name
, void *opaque
,
3614 KVMState
*s
= KVM_STATE(obj
);
3615 uint32_t value
= s
->kvm_dirty_ring_size
;
3617 visit_type_uint32(v
, name
, &value
, errp
);
3620 static void kvm_set_dirty_ring_size(Object
*obj
, Visitor
*v
,
3621 const char *name
, void *opaque
,
3624 KVMState
*s
= KVM_STATE(obj
);
3625 Error
*error
= NULL
;
3629 error_setg(errp
, "Cannot set properties after the accelerator has been initialized");
3633 visit_type_uint32(v
, name
, &value
, &error
);
3635 error_propagate(errp
, error
);
3638 if (value
& (value
- 1)) {
3639 error_setg(errp
, "dirty-ring-size must be a power of two.");
3643 s
->kvm_dirty_ring_size
= value
;
3646 static void kvm_accel_instance_init(Object
*obj
)
3648 KVMState
*s
= KVM_STATE(obj
);
3652 s
->kvm_shadow_mem
= -1;
3653 s
->kernel_irqchip_allowed
= true;
3654 s
->kernel_irqchip_split
= ON_OFF_AUTO_AUTO
;
3655 /* KVM dirty ring is by default off */
3656 s
->kvm_dirty_ring_size
= 0;
3659 static void kvm_accel_class_init(ObjectClass
*oc
, void *data
)
3661 AccelClass
*ac
= ACCEL_CLASS(oc
);
3663 ac
->init_machine
= kvm_init
;
3664 ac
->has_memory
= kvm_accel_has_memory
;
3665 ac
->allowed
= &kvm_allowed
;
3667 object_class_property_add(oc
, "kernel-irqchip", "on|off|split",
3668 NULL
, kvm_set_kernel_irqchip
,
3670 object_class_property_set_description(oc
, "kernel-irqchip",
3671 "Configure KVM in-kernel irqchip");
3673 object_class_property_add(oc
, "kvm-shadow-mem", "int",
3674 kvm_get_kvm_shadow_mem
, kvm_set_kvm_shadow_mem
,
3676 object_class_property_set_description(oc
, "kvm-shadow-mem",
3677 "KVM shadow MMU size");
3679 object_class_property_add(oc
, "dirty-ring-size", "uint32",
3680 kvm_get_dirty_ring_size
, kvm_set_dirty_ring_size
,
3682 object_class_property_set_description(oc
, "dirty-ring-size",
3683 "Size of KVM dirty page ring buffer (default: 0, i.e. use bitmap)");
3686 static const TypeInfo kvm_accel_type
= {
3687 .name
= TYPE_KVM_ACCEL
,
3688 .parent
= TYPE_ACCEL
,
3689 .instance_init
= kvm_accel_instance_init
,
3690 .class_init
= kvm_accel_class_init
,
3691 .instance_size
= sizeof(KVMState
),
3694 static void kvm_type_init(void)
3696 type_register_static(&kvm_accel_type
);
3699 type_init(kvm_type_init
);