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"
48 #include "sysemu/dirtylimit.h"
50 #include "hw/boards.h"
51 #include "monitor/stats.h"
53 /* This check must be after config-host.h is included */
55 #include <sys/eventfd.h>
58 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
59 * need to use the real host PAGE_SIZE, as that's what KVM will use.
64 #define PAGE_SIZE qemu_real_host_page_size()
66 #ifndef KVM_GUESTDBG_BLOCKIRQ
67 #define KVM_GUESTDBG_BLOCKIRQ 0
73 #define DPRINTF(fmt, ...) \
74 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
76 #define DPRINTF(fmt, ...) \
80 struct KVMParkedVcpu
{
81 unsigned long vcpu_id
;
83 QLIST_ENTRY(KVMParkedVcpu
) node
;
87 bool kvm_kernel_irqchip
;
88 bool kvm_split_irqchip
;
89 bool kvm_async_interrupts_allowed
;
90 bool kvm_halt_in_kernel_allowed
;
91 bool kvm_eventfds_allowed
;
92 bool kvm_irqfds_allowed
;
93 bool kvm_resamplefds_allowed
;
94 bool kvm_msi_via_irqfd_allowed
;
95 bool kvm_gsi_routing_allowed
;
96 bool kvm_gsi_direct_mapping
;
98 bool kvm_readonly_mem_allowed
;
99 bool kvm_vm_attributes_allowed
;
100 bool kvm_direct_msi_allowed
;
101 bool kvm_ioeventfd_any_length_allowed
;
102 bool kvm_msi_use_devid
;
103 bool kvm_has_guest_debug
;
104 static int kvm_sstep_flags
;
105 static bool kvm_immediate_exit
;
106 static hwaddr kvm_max_slot_size
= ~0;
108 static const KVMCapabilityInfo kvm_required_capabilites
[] = {
109 KVM_CAP_INFO(USER_MEMORY
),
110 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS
),
111 KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS
),
115 static NotifierList kvm_irqchip_change_notifiers
=
116 NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers
);
118 struct KVMResampleFd
{
120 EventNotifier
*resample_event
;
121 QLIST_ENTRY(KVMResampleFd
) node
;
123 typedef struct KVMResampleFd KVMResampleFd
;
126 * Only used with split irqchip where we need to do the resample fd
127 * kick for the kernel from userspace.
129 static QLIST_HEAD(, KVMResampleFd
) kvm_resample_fd_list
=
130 QLIST_HEAD_INITIALIZER(kvm_resample_fd_list
);
132 static QemuMutex kml_slots_lock
;
134 #define kvm_slots_lock() qemu_mutex_lock(&kml_slots_lock)
135 #define kvm_slots_unlock() qemu_mutex_unlock(&kml_slots_lock)
137 static void kvm_slot_init_dirty_bitmap(KVMSlot
*mem
);
139 static inline void kvm_resample_fd_remove(int gsi
)
143 QLIST_FOREACH(rfd
, &kvm_resample_fd_list
, node
) {
144 if (rfd
->gsi
== gsi
) {
145 QLIST_REMOVE(rfd
, node
);
152 static inline void kvm_resample_fd_insert(int gsi
, EventNotifier
*event
)
154 KVMResampleFd
*rfd
= g_new0(KVMResampleFd
, 1);
157 rfd
->resample_event
= event
;
159 QLIST_INSERT_HEAD(&kvm_resample_fd_list
, rfd
, node
);
162 void kvm_resample_fd_notify(int gsi
)
166 QLIST_FOREACH(rfd
, &kvm_resample_fd_list
, node
) {
167 if (rfd
->gsi
== gsi
) {
168 event_notifier_set(rfd
->resample_event
);
169 trace_kvm_resample_fd_notify(gsi
);
175 int kvm_get_max_memslots(void)
177 KVMState
*s
= KVM_STATE(current_accel());
182 /* Called with KVMMemoryListener.slots_lock held */
183 static KVMSlot
*kvm_get_free_slot(KVMMemoryListener
*kml
)
185 KVMState
*s
= kvm_state
;
188 for (i
= 0; i
< s
->nr_slots
; i
++) {
189 if (kml
->slots
[i
].memory_size
== 0) {
190 return &kml
->slots
[i
];
197 bool kvm_has_free_slot(MachineState
*ms
)
199 KVMState
*s
= KVM_STATE(ms
->accelerator
);
201 KVMMemoryListener
*kml
= &s
->memory_listener
;
204 result
= !!kvm_get_free_slot(kml
);
210 /* Called with KVMMemoryListener.slots_lock held */
211 static KVMSlot
*kvm_alloc_slot(KVMMemoryListener
*kml
)
213 KVMSlot
*slot
= kvm_get_free_slot(kml
);
219 fprintf(stderr
, "%s: no free slot available\n", __func__
);
223 static KVMSlot
*kvm_lookup_matching_slot(KVMMemoryListener
*kml
,
227 KVMState
*s
= kvm_state
;
230 for (i
= 0; i
< s
->nr_slots
; i
++) {
231 KVMSlot
*mem
= &kml
->slots
[i
];
233 if (start_addr
== mem
->start_addr
&& size
== mem
->memory_size
) {
242 * Calculate and align the start address and the size of the section.
243 * Return the size. If the size is 0, the aligned section is empty.
245 static hwaddr
kvm_align_section(MemoryRegionSection
*section
,
248 hwaddr size
= int128_get64(section
->size
);
249 hwaddr delta
, aligned
;
251 /* kvm works in page size chunks, but the function may be called
252 with sub-page size and unaligned start address. Pad the start
253 address to next and truncate size to previous page boundary. */
254 aligned
= ROUND_UP(section
->offset_within_address_space
,
255 qemu_real_host_page_size());
256 delta
= aligned
- section
->offset_within_address_space
;
262 return (size
- delta
) & qemu_real_host_page_mask();
265 int kvm_physical_memory_addr_from_host(KVMState
*s
, void *ram
,
268 KVMMemoryListener
*kml
= &s
->memory_listener
;
272 for (i
= 0; i
< s
->nr_slots
; i
++) {
273 KVMSlot
*mem
= &kml
->slots
[i
];
275 if (ram
>= mem
->ram
&& ram
< mem
->ram
+ mem
->memory_size
) {
276 *phys_addr
= mem
->start_addr
+ (ram
- mem
->ram
);
286 static int kvm_set_user_memory_region(KVMMemoryListener
*kml
, KVMSlot
*slot
, bool new)
288 KVMState
*s
= kvm_state
;
289 struct kvm_userspace_memory_region mem
;
292 mem
.slot
= slot
->slot
| (kml
->as_id
<< 16);
293 mem
.guest_phys_addr
= slot
->start_addr
;
294 mem
.userspace_addr
= (unsigned long)slot
->ram
;
295 mem
.flags
= slot
->flags
;
297 if (slot
->memory_size
&& !new && (mem
.flags
^ slot
->old_flags
) & KVM_MEM_READONLY
) {
298 /* Set the slot size to 0 before setting the slot to the desired
299 * value. This is needed based on KVM commit 75d61fbc. */
301 ret
= kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
306 mem
.memory_size
= slot
->memory_size
;
307 ret
= kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
308 slot
->old_flags
= mem
.flags
;
310 trace_kvm_set_user_memory(mem
.slot
, mem
.flags
, mem
.guest_phys_addr
,
311 mem
.memory_size
, mem
.userspace_addr
, ret
);
313 error_report("%s: KVM_SET_USER_MEMORY_REGION failed, slot=%d,"
314 " start=0x%" PRIx64
", size=0x%" PRIx64
": %s",
315 __func__
, mem
.slot
, slot
->start_addr
,
316 (uint64_t)mem
.memory_size
, strerror(errno
));
321 static int do_kvm_destroy_vcpu(CPUState
*cpu
)
323 KVMState
*s
= kvm_state
;
325 struct KVMParkedVcpu
*vcpu
= NULL
;
328 DPRINTF("kvm_destroy_vcpu\n");
330 ret
= kvm_arch_destroy_vcpu(cpu
);
335 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
338 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
342 ret
= munmap(cpu
->kvm_run
, mmap_size
);
347 if (cpu
->kvm_dirty_gfns
) {
348 ret
= munmap(cpu
->kvm_dirty_gfns
, s
->kvm_dirty_ring_bytes
);
354 vcpu
= g_malloc0(sizeof(*vcpu
));
355 vcpu
->vcpu_id
= kvm_arch_vcpu_id(cpu
);
356 vcpu
->kvm_fd
= cpu
->kvm_fd
;
357 QLIST_INSERT_HEAD(&kvm_state
->kvm_parked_vcpus
, vcpu
, node
);
362 void kvm_destroy_vcpu(CPUState
*cpu
)
364 if (do_kvm_destroy_vcpu(cpu
) < 0) {
365 error_report("kvm_destroy_vcpu failed");
370 static int kvm_get_vcpu(KVMState
*s
, unsigned long vcpu_id
)
372 struct KVMParkedVcpu
*cpu
;
374 QLIST_FOREACH(cpu
, &s
->kvm_parked_vcpus
, node
) {
375 if (cpu
->vcpu_id
== vcpu_id
) {
378 QLIST_REMOVE(cpu
, node
);
379 kvm_fd
= cpu
->kvm_fd
;
385 return kvm_vm_ioctl(s
, KVM_CREATE_VCPU
, (void *)vcpu_id
);
388 int kvm_init_vcpu(CPUState
*cpu
, Error
**errp
)
390 KVMState
*s
= kvm_state
;
394 trace_kvm_init_vcpu(cpu
->cpu_index
, kvm_arch_vcpu_id(cpu
));
396 ret
= kvm_get_vcpu(s
, kvm_arch_vcpu_id(cpu
));
398 error_setg_errno(errp
, -ret
, "kvm_init_vcpu: kvm_get_vcpu failed (%lu)",
399 kvm_arch_vcpu_id(cpu
));
405 cpu
->vcpu_dirty
= true;
406 cpu
->dirty_pages
= 0;
407 cpu
->throttle_us_per_full
= 0;
409 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
412 error_setg_errno(errp
, -mmap_size
,
413 "kvm_init_vcpu: KVM_GET_VCPU_MMAP_SIZE failed");
417 cpu
->kvm_run
= mmap(NULL
, mmap_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
419 if (cpu
->kvm_run
== MAP_FAILED
) {
421 error_setg_errno(errp
, ret
,
422 "kvm_init_vcpu: mmap'ing vcpu state failed (%lu)",
423 kvm_arch_vcpu_id(cpu
));
427 if (s
->coalesced_mmio
&& !s
->coalesced_mmio_ring
) {
428 s
->coalesced_mmio_ring
=
429 (void *)cpu
->kvm_run
+ s
->coalesced_mmio
* PAGE_SIZE
;
432 if (s
->kvm_dirty_ring_size
) {
433 /* Use MAP_SHARED to share pages with the kernel */
434 cpu
->kvm_dirty_gfns
= mmap(NULL
, s
->kvm_dirty_ring_bytes
,
435 PROT_READ
| PROT_WRITE
, MAP_SHARED
,
437 PAGE_SIZE
* KVM_DIRTY_LOG_PAGE_OFFSET
);
438 if (cpu
->kvm_dirty_gfns
== MAP_FAILED
) {
440 DPRINTF("mmap'ing vcpu dirty gfns failed: %d\n", ret
);
445 ret
= kvm_arch_init_vcpu(cpu
);
447 error_setg_errno(errp
, -ret
,
448 "kvm_init_vcpu: kvm_arch_init_vcpu failed (%lu)",
449 kvm_arch_vcpu_id(cpu
));
456 * dirty pages logging control
459 static int kvm_mem_flags(MemoryRegion
*mr
)
461 bool readonly
= mr
->readonly
|| memory_region_is_romd(mr
);
464 if (memory_region_get_dirty_log_mask(mr
) != 0) {
465 flags
|= KVM_MEM_LOG_DIRTY_PAGES
;
467 if (readonly
&& kvm_readonly_mem_allowed
) {
468 flags
|= KVM_MEM_READONLY
;
473 /* Called with KVMMemoryListener.slots_lock held */
474 static int kvm_slot_update_flags(KVMMemoryListener
*kml
, KVMSlot
*mem
,
477 mem
->flags
= kvm_mem_flags(mr
);
479 /* If nothing changed effectively, no need to issue ioctl */
480 if (mem
->flags
== mem
->old_flags
) {
484 kvm_slot_init_dirty_bitmap(mem
);
485 return kvm_set_user_memory_region(kml
, mem
, false);
488 static int kvm_section_update_flags(KVMMemoryListener
*kml
,
489 MemoryRegionSection
*section
)
491 hwaddr start_addr
, size
, slot_size
;
495 size
= kvm_align_section(section
, &start_addr
);
502 while (size
&& !ret
) {
503 slot_size
= MIN(kvm_max_slot_size
, size
);
504 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
506 /* We don't have a slot if we want to trap every access. */
510 ret
= kvm_slot_update_flags(kml
, mem
, section
->mr
);
511 start_addr
+= slot_size
;
520 static void kvm_log_start(MemoryListener
*listener
,
521 MemoryRegionSection
*section
,
524 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
531 r
= kvm_section_update_flags(kml
, section
);
537 static void kvm_log_stop(MemoryListener
*listener
,
538 MemoryRegionSection
*section
,
541 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
548 r
= kvm_section_update_flags(kml
, section
);
554 /* get kvm's dirty pages bitmap and update qemu's */
555 static void kvm_slot_sync_dirty_pages(KVMSlot
*slot
)
557 ram_addr_t start
= slot
->ram_start_offset
;
558 ram_addr_t pages
= slot
->memory_size
/ qemu_real_host_page_size();
560 cpu_physical_memory_set_dirty_lebitmap(slot
->dirty_bmap
, start
, pages
);
563 static void kvm_slot_reset_dirty_pages(KVMSlot
*slot
)
565 memset(slot
->dirty_bmap
, 0, slot
->dirty_bmap_size
);
568 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
570 /* Allocate the dirty bitmap for a slot */
571 static void kvm_slot_init_dirty_bitmap(KVMSlot
*mem
)
573 if (!(mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) || mem
->dirty_bmap
) {
578 * XXX bad kernel interface alert
579 * For dirty bitmap, kernel allocates array of size aligned to
580 * bits-per-long. But for case when the kernel is 64bits and
581 * the userspace is 32bits, userspace can't align to the same
582 * bits-per-long, since sizeof(long) is different between kernel
583 * and user space. This way, userspace will provide buffer which
584 * may be 4 bytes less than the kernel will use, resulting in
585 * userspace memory corruption (which is not detectable by valgrind
586 * too, in most cases).
587 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
588 * a hope that sizeof(long) won't become >8 any time soon.
590 * Note: the granule of kvm dirty log is qemu_real_host_page_size.
591 * And mem->memory_size is aligned to it (otherwise this mem can't
592 * be registered to KVM).
594 hwaddr bitmap_size
= ALIGN(mem
->memory_size
/ qemu_real_host_page_size(),
595 /*HOST_LONG_BITS*/ 64) / 8;
596 mem
->dirty_bmap
= g_malloc0(bitmap_size
);
597 mem
->dirty_bmap_size
= bitmap_size
;
601 * Sync dirty bitmap from kernel to KVMSlot.dirty_bmap, return true if
602 * succeeded, false otherwise
604 static bool kvm_slot_get_dirty_log(KVMState
*s
, KVMSlot
*slot
)
606 struct kvm_dirty_log d
= {};
609 d
.dirty_bitmap
= slot
->dirty_bmap
;
610 d
.slot
= slot
->slot
| (slot
->as_id
<< 16);
611 ret
= kvm_vm_ioctl(s
, KVM_GET_DIRTY_LOG
, &d
);
613 if (ret
== -ENOENT
) {
614 /* kernel does not have dirty bitmap in this slot */
618 error_report_once("%s: KVM_GET_DIRTY_LOG failed with %d",
624 /* Should be with all slots_lock held for the address spaces. */
625 static void kvm_dirty_ring_mark_page(KVMState
*s
, uint32_t as_id
,
626 uint32_t slot_id
, uint64_t offset
)
628 KVMMemoryListener
*kml
;
631 if (as_id
>= s
->nr_as
) {
635 kml
= s
->as
[as_id
].ml
;
636 mem
= &kml
->slots
[slot_id
];
638 if (!mem
->memory_size
|| offset
>=
639 (mem
->memory_size
/ qemu_real_host_page_size())) {
643 set_bit(offset
, mem
->dirty_bmap
);
646 static bool dirty_gfn_is_dirtied(struct kvm_dirty_gfn
*gfn
)
649 * Read the flags before the value. Pairs with barrier in
650 * KVM's kvm_dirty_ring_push() function.
652 return qatomic_load_acquire(&gfn
->flags
) == KVM_DIRTY_GFN_F_DIRTY
;
655 static void dirty_gfn_set_collected(struct kvm_dirty_gfn
*gfn
)
658 * Use a store-release so that the CPU that executes KVM_RESET_DIRTY_RINGS
659 * sees the full content of the ring:
662 * ------------------------------------------------------------------------------
664 * store-rel flags for gfn0
665 * load-acq flags for gfn0
666 * store-rel RESET for gfn0
668 * load-acq flags for gfn0
669 * check if flags have RESET
671 * The synchronization goes from CPU2 to CPU0 to CPU1.
673 qatomic_store_release(&gfn
->flags
, KVM_DIRTY_GFN_F_RESET
);
677 * Should be with all slots_lock held for the address spaces. It returns the
678 * dirty page we've collected on this dirty ring.
680 static uint32_t kvm_dirty_ring_reap_one(KVMState
*s
, CPUState
*cpu
)
682 struct kvm_dirty_gfn
*dirty_gfns
= cpu
->kvm_dirty_gfns
, *cur
;
683 uint32_t ring_size
= s
->kvm_dirty_ring_size
;
684 uint32_t count
= 0, fetch
= cpu
->kvm_fetch_index
;
686 assert(dirty_gfns
&& ring_size
);
687 trace_kvm_dirty_ring_reap_vcpu(cpu
->cpu_index
);
690 cur
= &dirty_gfns
[fetch
% ring_size
];
691 if (!dirty_gfn_is_dirtied(cur
)) {
694 kvm_dirty_ring_mark_page(s
, cur
->slot
>> 16, cur
->slot
& 0xffff,
696 dirty_gfn_set_collected(cur
);
697 trace_kvm_dirty_ring_page(cpu
->cpu_index
, fetch
, cur
->offset
);
701 cpu
->kvm_fetch_index
= fetch
;
702 cpu
->dirty_pages
+= count
;
707 /* Must be with slots_lock held */
708 static uint64_t kvm_dirty_ring_reap_locked(KVMState
*s
, CPUState
* cpu
)
717 total
= kvm_dirty_ring_reap_one(s
, cpu
);
720 total
+= kvm_dirty_ring_reap_one(s
, cpu
);
725 ret
= kvm_vm_ioctl(s
, KVM_RESET_DIRTY_RINGS
);
726 assert(ret
== total
);
729 stamp
= get_clock() - stamp
;
732 trace_kvm_dirty_ring_reap(total
, stamp
/ 1000);
739 * Currently for simplicity, we must hold BQL before calling this. We can
740 * consider to drop the BQL if we're clear with all the race conditions.
742 static uint64_t kvm_dirty_ring_reap(KVMState
*s
, CPUState
*cpu
)
747 * We need to lock all kvm slots for all address spaces here,
750 * (1) We need to mark dirty for dirty bitmaps in multiple slots
751 * and for tons of pages, so it's better to take the lock here
752 * once rather than once per page. And more importantly,
754 * (2) We must _NOT_ publish dirty bits to the other threads
755 * (e.g., the migration thread) via the kvm memory slot dirty
756 * bitmaps before correctly re-protect those dirtied pages.
757 * Otherwise we can have potential risk of data corruption if
758 * the page data is read in the other thread before we do
762 total
= kvm_dirty_ring_reap_locked(s
, cpu
);
768 static void do_kvm_cpu_synchronize_kick(CPUState
*cpu
, run_on_cpu_data arg
)
770 /* No need to do anything */
774 * Kick all vcpus out in a synchronized way. When returned, we
775 * guarantee that every vcpu has been kicked and at least returned to
778 static void kvm_cpu_synchronize_kick_all(void)
783 run_on_cpu(cpu
, do_kvm_cpu_synchronize_kick
, RUN_ON_CPU_NULL
);
788 * Flush all the existing dirty pages to the KVM slot buffers. When
789 * this call returns, we guarantee that all the touched dirty pages
790 * before calling this function have been put into the per-kvmslot
793 * This function must be called with BQL held.
795 static void kvm_dirty_ring_flush(void)
797 trace_kvm_dirty_ring_flush(0);
799 * The function needs to be serialized. Since this function
800 * should always be with BQL held, serialization is guaranteed.
801 * However, let's be sure of it.
803 assert(qemu_mutex_iothread_locked());
805 * First make sure to flush the hardware buffers by kicking all
806 * vcpus out in a synchronous way.
808 kvm_cpu_synchronize_kick_all();
809 kvm_dirty_ring_reap(kvm_state
, NULL
);
810 trace_kvm_dirty_ring_flush(1);
814 * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
816 * This function will first try to fetch dirty bitmap from the kernel,
817 * and then updates qemu's dirty bitmap.
819 * NOTE: caller must be with kml->slots_lock held.
821 * @kml: the KVM memory listener object
822 * @section: the memory section to sync the dirty bitmap with
824 static void kvm_physical_sync_dirty_bitmap(KVMMemoryListener
*kml
,
825 MemoryRegionSection
*section
)
827 KVMState
*s
= kvm_state
;
829 hwaddr start_addr
, size
;
832 size
= kvm_align_section(section
, &start_addr
);
834 slot_size
= MIN(kvm_max_slot_size
, size
);
835 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
837 /* We don't have a slot if we want to trap every access. */
840 if (kvm_slot_get_dirty_log(s
, mem
)) {
841 kvm_slot_sync_dirty_pages(mem
);
843 start_addr
+= slot_size
;
848 /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
849 #define KVM_CLEAR_LOG_SHIFT 6
850 #define KVM_CLEAR_LOG_ALIGN (qemu_real_host_page_size() << KVM_CLEAR_LOG_SHIFT)
851 #define KVM_CLEAR_LOG_MASK (-KVM_CLEAR_LOG_ALIGN)
853 static int kvm_log_clear_one_slot(KVMSlot
*mem
, int as_id
, uint64_t start
,
856 KVMState
*s
= kvm_state
;
857 uint64_t end
, bmap_start
, start_delta
, bmap_npages
;
858 struct kvm_clear_dirty_log d
;
859 unsigned long *bmap_clear
= NULL
, psize
= qemu_real_host_page_size();
863 * We need to extend either the start or the size or both to
864 * satisfy the KVM interface requirement. Firstly, do the start
865 * page alignment on 64 host pages
867 bmap_start
= start
& KVM_CLEAR_LOG_MASK
;
868 start_delta
= start
- bmap_start
;
872 * The kernel interface has restriction on the size too, that either:
874 * (1) the size is 64 host pages aligned (just like the start), or
875 * (2) the size fills up until the end of the KVM memslot.
877 bmap_npages
= DIV_ROUND_UP(size
+ start_delta
, KVM_CLEAR_LOG_ALIGN
)
878 << KVM_CLEAR_LOG_SHIFT
;
879 end
= mem
->memory_size
/ psize
;
880 if (bmap_npages
> end
- bmap_start
) {
881 bmap_npages
= end
- bmap_start
;
883 start_delta
/= psize
;
886 * Prepare the bitmap to clear dirty bits. Here we must guarantee
887 * that we won't clear any unknown dirty bits otherwise we might
888 * accidentally clear some set bits which are not yet synced from
889 * the kernel into QEMU's bitmap, then we'll lose track of the
890 * guest modifications upon those pages (which can directly lead
891 * to guest data loss or panic after migration).
893 * Layout of the KVMSlot.dirty_bmap:
895 * |<-------- bmap_npages -----------..>|
898 * |----------------|-------------|------------------|------------|
901 * start bmap_start (start) end
902 * of memslot of memslot
904 * [1] bmap_npages can be aligned to either 64 pages or the end of slot
907 assert(bmap_start
% BITS_PER_LONG
== 0);
908 /* We should never do log_clear before log_sync */
909 assert(mem
->dirty_bmap
);
910 if (start_delta
|| bmap_npages
- size
/ psize
) {
911 /* Slow path - we need to manipulate a temp bitmap */
912 bmap_clear
= bitmap_new(bmap_npages
);
913 bitmap_copy_with_src_offset(bmap_clear
, mem
->dirty_bmap
,
914 bmap_start
, start_delta
+ size
/ psize
);
916 * We need to fill the holes at start because that was not
917 * specified by the caller and we extended the bitmap only for
920 bitmap_clear(bmap_clear
, 0, start_delta
);
921 d
.dirty_bitmap
= bmap_clear
;
924 * Fast path - both start and size align well with BITS_PER_LONG
925 * (or the end of memory slot)
927 d
.dirty_bitmap
= mem
->dirty_bmap
+ BIT_WORD(bmap_start
);
930 d
.first_page
= bmap_start
;
931 /* It should never overflow. If it happens, say something */
932 assert(bmap_npages
<= UINT32_MAX
);
933 d
.num_pages
= bmap_npages
;
934 d
.slot
= mem
->slot
| (as_id
<< 16);
936 ret
= kvm_vm_ioctl(s
, KVM_CLEAR_DIRTY_LOG
, &d
);
937 if (ret
< 0 && ret
!= -ENOENT
) {
938 error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
939 "start=0x%"PRIx64
", size=0x%"PRIx32
", errno=%d",
940 __func__
, d
.slot
, (uint64_t)d
.first_page
,
941 (uint32_t)d
.num_pages
, ret
);
944 trace_kvm_clear_dirty_log(d
.slot
, d
.first_page
, d
.num_pages
);
948 * After we have updated the remote dirty bitmap, we update the
949 * cached bitmap as well for the memslot, then if another user
950 * clears the same region we know we shouldn't clear it again on
951 * the remote otherwise it's data loss as well.
953 bitmap_clear(mem
->dirty_bmap
, bmap_start
+ start_delta
,
955 /* This handles the NULL case well */
962 * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
964 * NOTE: this will be a no-op if we haven't enabled manual dirty log
965 * protection in the host kernel because in that case this operation
966 * will be done within log_sync().
968 * @kml: the kvm memory listener
969 * @section: the memory range to clear dirty bitmap
971 static int kvm_physical_log_clear(KVMMemoryListener
*kml
,
972 MemoryRegionSection
*section
)
974 KVMState
*s
= kvm_state
;
975 uint64_t start
, size
, offset
, count
;
979 if (!s
->manual_dirty_log_protect
) {
980 /* No need to do explicit clear */
984 start
= section
->offset_within_address_space
;
985 size
= int128_get64(section
->size
);
988 /* Nothing more we can do... */
994 for (i
= 0; i
< s
->nr_slots
; i
++) {
995 mem
= &kml
->slots
[i
];
996 /* Discard slots that are empty or do not overlap the section */
997 if (!mem
->memory_size
||
998 mem
->start_addr
> start
+ size
- 1 ||
999 start
> mem
->start_addr
+ mem
->memory_size
- 1) {
1003 if (start
>= mem
->start_addr
) {
1004 /* The slot starts before section or is aligned to it. */
1005 offset
= start
- mem
->start_addr
;
1006 count
= MIN(mem
->memory_size
- offset
, size
);
1008 /* The slot starts after section. */
1010 count
= MIN(mem
->memory_size
, size
- (mem
->start_addr
- start
));
1012 ret
= kvm_log_clear_one_slot(mem
, kml
->as_id
, offset
, count
);
1023 static void kvm_coalesce_mmio_region(MemoryListener
*listener
,
1024 MemoryRegionSection
*secion
,
1025 hwaddr start
, hwaddr size
)
1027 KVMState
*s
= kvm_state
;
1029 if (s
->coalesced_mmio
) {
1030 struct kvm_coalesced_mmio_zone zone
;
1036 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
1040 static void kvm_uncoalesce_mmio_region(MemoryListener
*listener
,
1041 MemoryRegionSection
*secion
,
1042 hwaddr start
, hwaddr size
)
1044 KVMState
*s
= kvm_state
;
1046 if (s
->coalesced_mmio
) {
1047 struct kvm_coalesced_mmio_zone zone
;
1053 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
1057 static void kvm_coalesce_pio_add(MemoryListener
*listener
,
1058 MemoryRegionSection
*section
,
1059 hwaddr start
, hwaddr size
)
1061 KVMState
*s
= kvm_state
;
1063 if (s
->coalesced_pio
) {
1064 struct kvm_coalesced_mmio_zone zone
;
1070 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
1074 static void kvm_coalesce_pio_del(MemoryListener
*listener
,
1075 MemoryRegionSection
*section
,
1076 hwaddr start
, hwaddr size
)
1078 KVMState
*s
= kvm_state
;
1080 if (s
->coalesced_pio
) {
1081 struct kvm_coalesced_mmio_zone zone
;
1087 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
1091 static MemoryListener kvm_coalesced_pio_listener
= {
1092 .name
= "kvm-coalesced-pio",
1093 .coalesced_io_add
= kvm_coalesce_pio_add
,
1094 .coalesced_io_del
= kvm_coalesce_pio_del
,
1097 int kvm_check_extension(KVMState
*s
, unsigned int extension
)
1101 ret
= kvm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
1109 int kvm_vm_check_extension(KVMState
*s
, unsigned int extension
)
1113 ret
= kvm_vm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
1115 /* VM wide version not implemented, use global one instead */
1116 ret
= kvm_check_extension(s
, extension
);
1122 typedef struct HWPoisonPage
{
1123 ram_addr_t ram_addr
;
1124 QLIST_ENTRY(HWPoisonPage
) list
;
1127 static QLIST_HEAD(, HWPoisonPage
) hwpoison_page_list
=
1128 QLIST_HEAD_INITIALIZER(hwpoison_page_list
);
1130 static void kvm_unpoison_all(void *param
)
1132 HWPoisonPage
*page
, *next_page
;
1134 QLIST_FOREACH_SAFE(page
, &hwpoison_page_list
, list
, next_page
) {
1135 QLIST_REMOVE(page
, list
);
1136 qemu_ram_remap(page
->ram_addr
, TARGET_PAGE_SIZE
);
1141 void kvm_hwpoison_page_add(ram_addr_t ram_addr
)
1145 QLIST_FOREACH(page
, &hwpoison_page_list
, list
) {
1146 if (page
->ram_addr
== ram_addr
) {
1150 page
= g_new(HWPoisonPage
, 1);
1151 page
->ram_addr
= ram_addr
;
1152 QLIST_INSERT_HEAD(&hwpoison_page_list
, page
, list
);
1155 static uint32_t adjust_ioeventfd_endianness(uint32_t val
, uint32_t size
)
1157 #if HOST_BIG_ENDIAN != TARGET_BIG_ENDIAN
1158 /* The kernel expects ioeventfd values in HOST_BIG_ENDIAN
1159 * endianness, but the memory core hands them in target endianness.
1160 * For example, PPC is always treated as big-endian even if running
1161 * on KVM and on PPC64LE. Correct here.
1175 static int kvm_set_ioeventfd_mmio(int fd
, hwaddr addr
, uint32_t val
,
1176 bool assign
, uint32_t size
, bool datamatch
)
1179 struct kvm_ioeventfd iofd
= {
1180 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
1187 trace_kvm_set_ioeventfd_mmio(fd
, (uint64_t)addr
, val
, assign
, size
,
1189 if (!kvm_enabled()) {
1194 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
1197 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
1200 ret
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &iofd
);
1209 static int kvm_set_ioeventfd_pio(int fd
, uint16_t addr
, uint16_t val
,
1210 bool assign
, uint32_t size
, bool datamatch
)
1212 struct kvm_ioeventfd kick
= {
1213 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
1215 .flags
= KVM_IOEVENTFD_FLAG_PIO
,
1220 trace_kvm_set_ioeventfd_pio(fd
, addr
, val
, assign
, size
, datamatch
);
1221 if (!kvm_enabled()) {
1225 kick
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
1228 kick
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
1230 r
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &kick
);
1238 static int kvm_check_many_ioeventfds(void)
1240 /* Userspace can use ioeventfd for io notification. This requires a host
1241 * that supports eventfd(2) and an I/O thread; since eventfd does not
1242 * support SIGIO it cannot interrupt the vcpu.
1244 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
1245 * can avoid creating too many ioeventfds.
1247 #if defined(CONFIG_EVENTFD)
1250 for (i
= 0; i
< ARRAY_SIZE(ioeventfds
); i
++) {
1251 ioeventfds
[i
] = eventfd(0, EFD_CLOEXEC
);
1252 if (ioeventfds
[i
] < 0) {
1255 ret
= kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, true, 2, true);
1257 close(ioeventfds
[i
]);
1262 /* Decide whether many devices are supported or not */
1263 ret
= i
== ARRAY_SIZE(ioeventfds
);
1266 kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, false, 2, true);
1267 close(ioeventfds
[i
]);
1275 static const KVMCapabilityInfo
*
1276 kvm_check_extension_list(KVMState
*s
, const KVMCapabilityInfo
*list
)
1278 while (list
->name
) {
1279 if (!kvm_check_extension(s
, list
->value
)) {
1287 void kvm_set_max_memslot_size(hwaddr max_slot_size
)
1290 ROUND_UP(max_slot_size
, qemu_real_host_page_size()) == max_slot_size
1292 kvm_max_slot_size
= max_slot_size
;
1295 static void kvm_set_phys_mem(KVMMemoryListener
*kml
,
1296 MemoryRegionSection
*section
, bool add
)
1300 MemoryRegion
*mr
= section
->mr
;
1301 bool writable
= !mr
->readonly
&& !mr
->rom_device
;
1302 hwaddr start_addr
, size
, slot_size
, mr_offset
;
1303 ram_addr_t ram_start_offset
;
1306 if (!memory_region_is_ram(mr
)) {
1307 if (writable
|| !kvm_readonly_mem_allowed
) {
1309 } else if (!mr
->romd_mode
) {
1310 /* If the memory device is not in romd_mode, then we actually want
1311 * to remove the kvm memory slot so all accesses will trap. */
1316 size
= kvm_align_section(section
, &start_addr
);
1321 /* The offset of the kvmslot within the memory region */
1322 mr_offset
= section
->offset_within_region
+ start_addr
-
1323 section
->offset_within_address_space
;
1325 /* use aligned delta to align the ram address and offset */
1326 ram
= memory_region_get_ram_ptr(mr
) + mr_offset
;
1327 ram_start_offset
= memory_region_get_ram_addr(mr
) + mr_offset
;
1333 slot_size
= MIN(kvm_max_slot_size
, size
);
1334 mem
= kvm_lookup_matching_slot(kml
, start_addr
, slot_size
);
1338 if (mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
1340 * NOTE: We should be aware of the fact that here we're only
1341 * doing a best effort to sync dirty bits. No matter whether
1342 * we're using dirty log or dirty ring, we ignored two facts:
1344 * (1) dirty bits can reside in hardware buffers (PML)
1346 * (2) after we collected dirty bits here, pages can be dirtied
1347 * again before we do the final KVM_SET_USER_MEMORY_REGION to
1350 * Not easy. Let's cross the fingers until it's fixed.
1352 if (kvm_state
->kvm_dirty_ring_size
) {
1353 kvm_dirty_ring_reap_locked(kvm_state
, NULL
);
1355 kvm_slot_get_dirty_log(kvm_state
, mem
);
1357 kvm_slot_sync_dirty_pages(mem
);
1360 /* unregister the slot */
1361 g_free(mem
->dirty_bmap
);
1362 mem
->dirty_bmap
= NULL
;
1363 mem
->memory_size
= 0;
1365 err
= kvm_set_user_memory_region(kml
, mem
, false);
1367 fprintf(stderr
, "%s: error unregistering slot: %s\n",
1368 __func__
, strerror(-err
));
1371 start_addr
+= slot_size
;
1377 /* register the new slot */
1379 slot_size
= MIN(kvm_max_slot_size
, size
);
1380 mem
= kvm_alloc_slot(kml
);
1381 mem
->as_id
= kml
->as_id
;
1382 mem
->memory_size
= slot_size
;
1383 mem
->start_addr
= start_addr
;
1384 mem
->ram_start_offset
= ram_start_offset
;
1386 mem
->flags
= kvm_mem_flags(mr
);
1387 kvm_slot_init_dirty_bitmap(mem
);
1388 err
= kvm_set_user_memory_region(kml
, mem
, true);
1390 fprintf(stderr
, "%s: error registering slot: %s\n", __func__
,
1394 start_addr
+= slot_size
;
1395 ram_start_offset
+= slot_size
;
1404 static void *kvm_dirty_ring_reaper_thread(void *data
)
1407 struct KVMDirtyRingReaper
*r
= &s
->reaper
;
1409 rcu_register_thread();
1411 trace_kvm_dirty_ring_reaper("init");
1414 r
->reaper_state
= KVM_DIRTY_RING_REAPER_WAIT
;
1415 trace_kvm_dirty_ring_reaper("wait");
1417 * TODO: provide a smarter timeout rather than a constant?
1421 /* keep sleeping so that dirtylimit not be interfered by reaper */
1422 if (dirtylimit_in_service()) {
1426 trace_kvm_dirty_ring_reaper("wakeup");
1427 r
->reaper_state
= KVM_DIRTY_RING_REAPER_REAPING
;
1429 qemu_mutex_lock_iothread();
1430 kvm_dirty_ring_reap(s
, NULL
);
1431 qemu_mutex_unlock_iothread();
1433 r
->reaper_iteration
++;
1436 trace_kvm_dirty_ring_reaper("exit");
1438 rcu_unregister_thread();
1443 static int kvm_dirty_ring_reaper_init(KVMState
*s
)
1445 struct KVMDirtyRingReaper
*r
= &s
->reaper
;
1447 qemu_thread_create(&r
->reaper_thr
, "kvm-reaper",
1448 kvm_dirty_ring_reaper_thread
,
1449 s
, QEMU_THREAD_JOINABLE
);
1454 static void kvm_region_add(MemoryListener
*listener
,
1455 MemoryRegionSection
*section
)
1457 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1459 memory_region_ref(section
->mr
);
1460 kvm_set_phys_mem(kml
, section
, true);
1463 static void kvm_region_del(MemoryListener
*listener
,
1464 MemoryRegionSection
*section
)
1466 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1468 kvm_set_phys_mem(kml
, section
, false);
1469 memory_region_unref(section
->mr
);
1472 static void kvm_log_sync(MemoryListener
*listener
,
1473 MemoryRegionSection
*section
)
1475 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1478 kvm_physical_sync_dirty_bitmap(kml
, section
);
1482 static void kvm_log_sync_global(MemoryListener
*l
)
1484 KVMMemoryListener
*kml
= container_of(l
, KVMMemoryListener
, listener
);
1485 KVMState
*s
= kvm_state
;
1489 /* Flush all kernel dirty addresses into KVMSlot dirty bitmap */
1490 kvm_dirty_ring_flush();
1493 * TODO: make this faster when nr_slots is big while there are
1494 * only a few used slots (small VMs).
1497 for (i
= 0; i
< s
->nr_slots
; i
++) {
1498 mem
= &kml
->slots
[i
];
1499 if (mem
->memory_size
&& mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
1500 kvm_slot_sync_dirty_pages(mem
);
1502 * This is not needed by KVM_GET_DIRTY_LOG because the
1503 * ioctl will unconditionally overwrite the whole region.
1504 * However kvm dirty ring has no such side effect.
1506 kvm_slot_reset_dirty_pages(mem
);
1512 static void kvm_log_clear(MemoryListener
*listener
,
1513 MemoryRegionSection
*section
)
1515 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
1518 r
= kvm_physical_log_clear(kml
, section
);
1520 error_report_once("%s: kvm log clear failed: mr=%s "
1521 "offset=%"HWADDR_PRIx
" size=%"PRIx64
, __func__
,
1522 section
->mr
->name
, section
->offset_within_region
,
1523 int128_get64(section
->size
));
1528 static void kvm_mem_ioeventfd_add(MemoryListener
*listener
,
1529 MemoryRegionSection
*section
,
1530 bool match_data
, uint64_t data
,
1533 int fd
= event_notifier_get_fd(e
);
1536 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
1537 data
, true, int128_get64(section
->size
),
1540 fprintf(stderr
, "%s: error adding ioeventfd: %s (%d)\n",
1541 __func__
, strerror(-r
), -r
);
1546 static void kvm_mem_ioeventfd_del(MemoryListener
*listener
,
1547 MemoryRegionSection
*section
,
1548 bool match_data
, uint64_t data
,
1551 int fd
= event_notifier_get_fd(e
);
1554 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
1555 data
, false, int128_get64(section
->size
),
1558 fprintf(stderr
, "%s: error deleting ioeventfd: %s (%d)\n",
1559 __func__
, strerror(-r
), -r
);
1564 static void kvm_io_ioeventfd_add(MemoryListener
*listener
,
1565 MemoryRegionSection
*section
,
1566 bool match_data
, uint64_t data
,
1569 int fd
= event_notifier_get_fd(e
);
1572 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
1573 data
, true, int128_get64(section
->size
),
1576 fprintf(stderr
, "%s: error adding ioeventfd: %s (%d)\n",
1577 __func__
, strerror(-r
), -r
);
1582 static void kvm_io_ioeventfd_del(MemoryListener
*listener
,
1583 MemoryRegionSection
*section
,
1584 bool match_data
, uint64_t data
,
1588 int fd
= event_notifier_get_fd(e
);
1591 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
1592 data
, false, int128_get64(section
->size
),
1595 fprintf(stderr
, "%s: error deleting ioeventfd: %s (%d)\n",
1596 __func__
, strerror(-r
), -r
);
1601 void kvm_memory_listener_register(KVMState
*s
, KVMMemoryListener
*kml
,
1602 AddressSpace
*as
, int as_id
, const char *name
)
1606 kml
->slots
= g_new0(KVMSlot
, s
->nr_slots
);
1609 for (i
= 0; i
< s
->nr_slots
; i
++) {
1610 kml
->slots
[i
].slot
= i
;
1613 kml
->listener
.region_add
= kvm_region_add
;
1614 kml
->listener
.region_del
= kvm_region_del
;
1615 kml
->listener
.log_start
= kvm_log_start
;
1616 kml
->listener
.log_stop
= kvm_log_stop
;
1617 kml
->listener
.priority
= 10;
1618 kml
->listener
.name
= name
;
1620 if (s
->kvm_dirty_ring_size
) {
1621 kml
->listener
.log_sync_global
= kvm_log_sync_global
;
1623 kml
->listener
.log_sync
= kvm_log_sync
;
1624 kml
->listener
.log_clear
= kvm_log_clear
;
1627 memory_listener_register(&kml
->listener
, as
);
1629 for (i
= 0; i
< s
->nr_as
; ++i
) {
1638 static MemoryListener kvm_io_listener
= {
1640 .eventfd_add
= kvm_io_ioeventfd_add
,
1641 .eventfd_del
= kvm_io_ioeventfd_del
,
1645 int kvm_set_irq(KVMState
*s
, int irq
, int level
)
1647 struct kvm_irq_level event
;
1650 assert(kvm_async_interrupts_enabled());
1652 event
.level
= level
;
1654 ret
= kvm_vm_ioctl(s
, s
->irq_set_ioctl
, &event
);
1656 perror("kvm_set_irq");
1660 return (s
->irq_set_ioctl
== KVM_IRQ_LINE
) ? 1 : event
.status
;
1663 #ifdef KVM_CAP_IRQ_ROUTING
1664 typedef struct KVMMSIRoute
{
1665 struct kvm_irq_routing_entry kroute
;
1666 QTAILQ_ENTRY(KVMMSIRoute
) entry
;
1669 static void set_gsi(KVMState
*s
, unsigned int gsi
)
1671 set_bit(gsi
, s
->used_gsi_bitmap
);
1674 static void clear_gsi(KVMState
*s
, unsigned int gsi
)
1676 clear_bit(gsi
, s
->used_gsi_bitmap
);
1679 void kvm_init_irq_routing(KVMState
*s
)
1683 gsi_count
= kvm_check_extension(s
, KVM_CAP_IRQ_ROUTING
) - 1;
1684 if (gsi_count
> 0) {
1685 /* Round up so we can search ints using ffs */
1686 s
->used_gsi_bitmap
= bitmap_new(gsi_count
);
1687 s
->gsi_count
= gsi_count
;
1690 s
->irq_routes
= g_malloc0(sizeof(*s
->irq_routes
));
1691 s
->nr_allocated_irq_routes
= 0;
1693 if (!kvm_direct_msi_allowed
) {
1694 for (i
= 0; i
< KVM_MSI_HASHTAB_SIZE
; i
++) {
1695 QTAILQ_INIT(&s
->msi_hashtab
[i
]);
1699 kvm_arch_init_irq_routing(s
);
1702 void kvm_irqchip_commit_routes(KVMState
*s
)
1706 if (kvm_gsi_direct_mapping()) {
1710 if (!kvm_gsi_routing_enabled()) {
1714 s
->irq_routes
->flags
= 0;
1715 trace_kvm_irqchip_commit_routes();
1716 ret
= kvm_vm_ioctl(s
, KVM_SET_GSI_ROUTING
, s
->irq_routes
);
1720 static void kvm_add_routing_entry(KVMState
*s
,
1721 struct kvm_irq_routing_entry
*entry
)
1723 struct kvm_irq_routing_entry
*new;
1726 if (s
->irq_routes
->nr
== s
->nr_allocated_irq_routes
) {
1727 n
= s
->nr_allocated_irq_routes
* 2;
1731 size
= sizeof(struct kvm_irq_routing
);
1732 size
+= n
* sizeof(*new);
1733 s
->irq_routes
= g_realloc(s
->irq_routes
, size
);
1734 s
->nr_allocated_irq_routes
= n
;
1736 n
= s
->irq_routes
->nr
++;
1737 new = &s
->irq_routes
->entries
[n
];
1741 set_gsi(s
, entry
->gsi
);
1744 static int kvm_update_routing_entry(KVMState
*s
,
1745 struct kvm_irq_routing_entry
*new_entry
)
1747 struct kvm_irq_routing_entry
*entry
;
1750 for (n
= 0; n
< s
->irq_routes
->nr
; n
++) {
1751 entry
= &s
->irq_routes
->entries
[n
];
1752 if (entry
->gsi
!= new_entry
->gsi
) {
1756 if(!memcmp(entry
, new_entry
, sizeof *entry
)) {
1760 *entry
= *new_entry
;
1768 void kvm_irqchip_add_irq_route(KVMState
*s
, int irq
, int irqchip
, int pin
)
1770 struct kvm_irq_routing_entry e
= {};
1772 assert(pin
< s
->gsi_count
);
1775 e
.type
= KVM_IRQ_ROUTING_IRQCHIP
;
1777 e
.u
.irqchip
.irqchip
= irqchip
;
1778 e
.u
.irqchip
.pin
= pin
;
1779 kvm_add_routing_entry(s
, &e
);
1782 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
1784 struct kvm_irq_routing_entry
*e
;
1787 if (kvm_gsi_direct_mapping()) {
1791 for (i
= 0; i
< s
->irq_routes
->nr
; i
++) {
1792 e
= &s
->irq_routes
->entries
[i
];
1793 if (e
->gsi
== virq
) {
1794 s
->irq_routes
->nr
--;
1795 *e
= s
->irq_routes
->entries
[s
->irq_routes
->nr
];
1799 kvm_arch_release_virq_post(virq
);
1800 trace_kvm_irqchip_release_virq(virq
);
1803 void kvm_irqchip_add_change_notifier(Notifier
*n
)
1805 notifier_list_add(&kvm_irqchip_change_notifiers
, n
);
1808 void kvm_irqchip_remove_change_notifier(Notifier
*n
)
1813 void kvm_irqchip_change_notify(void)
1815 notifier_list_notify(&kvm_irqchip_change_notifiers
, NULL
);
1818 static unsigned int kvm_hash_msi(uint32_t data
)
1820 /* This is optimized for IA32 MSI layout. However, no other arch shall
1821 * repeat the mistake of not providing a direct MSI injection API. */
1825 static void kvm_flush_dynamic_msi_routes(KVMState
*s
)
1827 KVMMSIRoute
*route
, *next
;
1830 for (hash
= 0; hash
< KVM_MSI_HASHTAB_SIZE
; hash
++) {
1831 QTAILQ_FOREACH_SAFE(route
, &s
->msi_hashtab
[hash
], entry
, next
) {
1832 kvm_irqchip_release_virq(s
, route
->kroute
.gsi
);
1833 QTAILQ_REMOVE(&s
->msi_hashtab
[hash
], route
, entry
);
1839 static int kvm_irqchip_get_virq(KVMState
*s
)
1844 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1845 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1846 * number can succeed even though a new route entry cannot be added.
1847 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1849 if (!kvm_direct_msi_allowed
&& s
->irq_routes
->nr
== s
->gsi_count
) {
1850 kvm_flush_dynamic_msi_routes(s
);
1853 /* Return the lowest unused GSI in the bitmap */
1854 next_virq
= find_first_zero_bit(s
->used_gsi_bitmap
, s
->gsi_count
);
1855 if (next_virq
>= s
->gsi_count
) {
1862 static KVMMSIRoute
*kvm_lookup_msi_route(KVMState
*s
, MSIMessage msg
)
1864 unsigned int hash
= kvm_hash_msi(msg
.data
);
1867 QTAILQ_FOREACH(route
, &s
->msi_hashtab
[hash
], entry
) {
1868 if (route
->kroute
.u
.msi
.address_lo
== (uint32_t)msg
.address
&&
1869 route
->kroute
.u
.msi
.address_hi
== (msg
.address
>> 32) &&
1870 route
->kroute
.u
.msi
.data
== le32_to_cpu(msg
.data
)) {
1877 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1882 if (kvm_direct_msi_allowed
) {
1883 msi
.address_lo
= (uint32_t)msg
.address
;
1884 msi
.address_hi
= msg
.address
>> 32;
1885 msi
.data
= le32_to_cpu(msg
.data
);
1887 memset(msi
.pad
, 0, sizeof(msi
.pad
));
1889 return kvm_vm_ioctl(s
, KVM_SIGNAL_MSI
, &msi
);
1892 route
= kvm_lookup_msi_route(s
, msg
);
1896 virq
= kvm_irqchip_get_virq(s
);
1901 route
= g_new0(KVMMSIRoute
, 1);
1902 route
->kroute
.gsi
= virq
;
1903 route
->kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1904 route
->kroute
.flags
= 0;
1905 route
->kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1906 route
->kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1907 route
->kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1909 kvm_add_routing_entry(s
, &route
->kroute
);
1910 kvm_irqchip_commit_routes(s
);
1912 QTAILQ_INSERT_TAIL(&s
->msi_hashtab
[kvm_hash_msi(msg
.data
)], route
,
1916 assert(route
->kroute
.type
== KVM_IRQ_ROUTING_MSI
);
1918 return kvm_set_irq(s
, route
->kroute
.gsi
, 1);
1921 int kvm_irqchip_add_msi_route(KVMRouteChange
*c
, int vector
, PCIDevice
*dev
)
1923 struct kvm_irq_routing_entry kroute
= {};
1926 MSIMessage msg
= {0, 0};
1928 if (pci_available
&& dev
) {
1929 msg
= pci_get_msi_message(dev
, vector
);
1932 if (kvm_gsi_direct_mapping()) {
1933 return kvm_arch_msi_data_to_gsi(msg
.data
);
1936 if (!kvm_gsi_routing_enabled()) {
1940 virq
= kvm_irqchip_get_virq(s
);
1946 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1948 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1949 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1950 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1951 if (pci_available
&& kvm_msi_devid_required()) {
1952 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1953 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1955 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1956 kvm_irqchip_release_virq(s
, virq
);
1960 trace_kvm_irqchip_add_msi_route(dev
? dev
->name
: (char *)"N/A",
1963 kvm_add_routing_entry(s
, &kroute
);
1964 kvm_arch_add_msi_route_post(&kroute
, vector
, dev
);
1970 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
,
1973 struct kvm_irq_routing_entry kroute
= {};
1975 if (kvm_gsi_direct_mapping()) {
1979 if (!kvm_irqchip_in_kernel()) {
1984 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1986 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1987 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1988 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1989 if (pci_available
&& kvm_msi_devid_required()) {
1990 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1991 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1993 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1997 trace_kvm_irqchip_update_msi_route(virq
);
1999 return kvm_update_routing_entry(s
, &kroute
);
2002 static int kvm_irqchip_assign_irqfd(KVMState
*s
, EventNotifier
*event
,
2003 EventNotifier
*resample
, int virq
,
2006 int fd
= event_notifier_get_fd(event
);
2007 int rfd
= resample
? event_notifier_get_fd(resample
) : -1;
2009 struct kvm_irqfd irqfd
= {
2012 .flags
= assign
? 0 : KVM_IRQFD_FLAG_DEASSIGN
,
2017 if (kvm_irqchip_is_split()) {
2019 * When the slow irqchip (e.g. IOAPIC) is in the
2020 * userspace, KVM kernel resamplefd will not work because
2021 * the EOI of the interrupt will be delivered to userspace
2022 * instead, so the KVM kernel resamplefd kick will be
2023 * skipped. The userspace here mimics what the kernel
2024 * provides with resamplefd, remember the resamplefd and
2025 * kick it when we receive EOI of this IRQ.
2027 * This is hackery because IOAPIC is mostly bypassed
2028 * (except EOI broadcasts) when irqfd is used. However
2029 * this can bring much performance back for split irqchip
2030 * with INTx IRQs (for VFIO, this gives 93% perf of the
2031 * full fast path, which is 46% perf boost comparing to
2032 * the INTx slow path).
2034 kvm_resample_fd_insert(virq
, resample
);
2036 irqfd
.flags
|= KVM_IRQFD_FLAG_RESAMPLE
;
2037 irqfd
.resamplefd
= rfd
;
2039 } else if (!assign
) {
2040 if (kvm_irqchip_is_split()) {
2041 kvm_resample_fd_remove(virq
);
2045 if (!kvm_irqfds_enabled()) {
2049 return kvm_vm_ioctl(s
, KVM_IRQFD
, &irqfd
);
2052 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
2054 struct kvm_irq_routing_entry kroute
= {};
2057 if (!kvm_gsi_routing_enabled()) {
2061 virq
= kvm_irqchip_get_virq(s
);
2067 kroute
.type
= KVM_IRQ_ROUTING_S390_ADAPTER
;
2069 kroute
.u
.adapter
.summary_addr
= adapter
->summary_addr
;
2070 kroute
.u
.adapter
.ind_addr
= adapter
->ind_addr
;
2071 kroute
.u
.adapter
.summary_offset
= adapter
->summary_offset
;
2072 kroute
.u
.adapter
.ind_offset
= adapter
->ind_offset
;
2073 kroute
.u
.adapter
.adapter_id
= adapter
->adapter_id
;
2075 kvm_add_routing_entry(s
, &kroute
);
2080 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
2082 struct kvm_irq_routing_entry kroute
= {};
2085 if (!kvm_gsi_routing_enabled()) {
2088 if (!kvm_check_extension(s
, KVM_CAP_HYPERV_SYNIC
)) {
2091 virq
= kvm_irqchip_get_virq(s
);
2097 kroute
.type
= KVM_IRQ_ROUTING_HV_SINT
;
2099 kroute
.u
.hv_sint
.vcpu
= vcpu
;
2100 kroute
.u
.hv_sint
.sint
= sint
;
2102 kvm_add_routing_entry(s
, &kroute
);
2103 kvm_irqchip_commit_routes(s
);
2108 #else /* !KVM_CAP_IRQ_ROUTING */
2110 void kvm_init_irq_routing(KVMState
*s
)
2114 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
2118 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
2123 int kvm_irqchip_add_msi_route(KVMRouteChange
*c
, int vector
, PCIDevice
*dev
)
2128 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
2133 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
2138 static int kvm_irqchip_assign_irqfd(KVMState
*s
, EventNotifier
*event
,
2139 EventNotifier
*resample
, int virq
,
2145 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
)
2149 #endif /* !KVM_CAP_IRQ_ROUTING */
2151 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
2152 EventNotifier
*rn
, int virq
)
2154 return kvm_irqchip_assign_irqfd(s
, n
, rn
, virq
, true);
2157 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
2160 return kvm_irqchip_assign_irqfd(s
, n
, NULL
, virq
, false);
2163 int kvm_irqchip_add_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
2164 EventNotifier
*rn
, qemu_irq irq
)
2167 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
2172 return kvm_irqchip_add_irqfd_notifier_gsi(s
, n
, rn
, GPOINTER_TO_INT(gsi
));
2175 int kvm_irqchip_remove_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
2179 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
2184 return kvm_irqchip_remove_irqfd_notifier_gsi(s
, n
, GPOINTER_TO_INT(gsi
));
2187 void kvm_irqchip_set_qemuirq_gsi(KVMState
*s
, qemu_irq irq
, int gsi
)
2189 g_hash_table_insert(s
->gsimap
, irq
, GINT_TO_POINTER(gsi
));
2192 static void kvm_irqchip_create(KVMState
*s
)
2196 assert(s
->kernel_irqchip_split
!= ON_OFF_AUTO_AUTO
);
2197 if (kvm_check_extension(s
, KVM_CAP_IRQCHIP
)) {
2199 } else if (kvm_check_extension(s
, KVM_CAP_S390_IRQCHIP
)) {
2200 ret
= kvm_vm_enable_cap(s
, KVM_CAP_S390_IRQCHIP
, 0);
2202 fprintf(stderr
, "Enable kernel irqchip failed: %s\n", strerror(-ret
));
2209 /* First probe and see if there's a arch-specific hook to create the
2210 * in-kernel irqchip for us */
2211 ret
= kvm_arch_irqchip_create(s
);
2213 if (s
->kernel_irqchip_split
== ON_OFF_AUTO_ON
) {
2214 error_report("Split IRQ chip mode not supported.");
2217 ret
= kvm_vm_ioctl(s
, KVM_CREATE_IRQCHIP
);
2221 fprintf(stderr
, "Create kernel irqchip failed: %s\n", strerror(-ret
));
2225 kvm_kernel_irqchip
= true;
2226 /* If we have an in-kernel IRQ chip then we must have asynchronous
2227 * interrupt delivery (though the reverse is not necessarily true)
2229 kvm_async_interrupts_allowed
= true;
2230 kvm_halt_in_kernel_allowed
= true;
2232 kvm_init_irq_routing(s
);
2234 s
->gsimap
= g_hash_table_new(g_direct_hash
, g_direct_equal
);
2237 /* Find number of supported CPUs using the recommended
2238 * procedure from the kernel API documentation to cope with
2239 * older kernels that may be missing capabilities.
2241 static int kvm_recommended_vcpus(KVMState
*s
)
2243 int ret
= kvm_vm_check_extension(s
, KVM_CAP_NR_VCPUS
);
2244 return (ret
) ? ret
: 4;
2247 static int kvm_max_vcpus(KVMState
*s
)
2249 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPUS
);
2250 return (ret
) ? ret
: kvm_recommended_vcpus(s
);
2253 static int kvm_max_vcpu_id(KVMState
*s
)
2255 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPU_ID
);
2256 return (ret
) ? ret
: kvm_max_vcpus(s
);
2259 bool kvm_vcpu_id_is_valid(int vcpu_id
)
2261 KVMState
*s
= KVM_STATE(current_accel());
2262 return vcpu_id
>= 0 && vcpu_id
< kvm_max_vcpu_id(s
);
2265 bool kvm_dirty_ring_enabled(void)
2267 return kvm_state
->kvm_dirty_ring_size
? true : false;
2270 static void query_stats_cb(StatsResultList
**result
, StatsTarget target
,
2271 strList
*names
, strList
*targets
, Error
**errp
);
2272 static void query_stats_schemas_cb(StatsSchemaList
**result
, Error
**errp
);
2274 uint32_t kvm_dirty_ring_size(void)
2276 return kvm_state
->kvm_dirty_ring_size
;
2279 static int kvm_init(MachineState
*ms
)
2281 MachineClass
*mc
= MACHINE_GET_CLASS(ms
);
2282 static const char upgrade_note
[] =
2283 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
2284 "(see http://sourceforge.net/projects/kvm).\n";
2289 { "SMP", ms
->smp
.cpus
},
2290 { "hotpluggable", ms
->smp
.max_cpus
},
2293 int soft_vcpus_limit
, hard_vcpus_limit
;
2295 const KVMCapabilityInfo
*missing_cap
;
2298 uint64_t dirty_log_manual_caps
;
2300 qemu_mutex_init(&kml_slots_lock
);
2302 s
= KVM_STATE(ms
->accelerator
);
2305 * On systems where the kernel can support different base page
2306 * sizes, host page size may be different from TARGET_PAGE_SIZE,
2307 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
2308 * page size for the system though.
2310 assert(TARGET_PAGE_SIZE
<= qemu_real_host_page_size());
2314 #ifdef KVM_CAP_SET_GUEST_DEBUG
2315 QTAILQ_INIT(&s
->kvm_sw_breakpoints
);
2317 QLIST_INIT(&s
->kvm_parked_vcpus
);
2318 s
->fd
= qemu_open_old("/dev/kvm", O_RDWR
);
2320 fprintf(stderr
, "Could not access KVM kernel module: %m\n");
2325 ret
= kvm_ioctl(s
, KVM_GET_API_VERSION
, 0);
2326 if (ret
< KVM_API_VERSION
) {
2330 fprintf(stderr
, "kvm version too old\n");
2334 if (ret
> KVM_API_VERSION
) {
2336 fprintf(stderr
, "kvm version not supported\n");
2340 kvm_immediate_exit
= kvm_check_extension(s
, KVM_CAP_IMMEDIATE_EXIT
);
2341 s
->nr_slots
= kvm_check_extension(s
, KVM_CAP_NR_MEMSLOTS
);
2343 /* If unspecified, use the default value */
2348 s
->nr_as
= kvm_check_extension(s
, KVM_CAP_MULTI_ADDRESS_SPACE
);
2349 if (s
->nr_as
<= 1) {
2352 s
->as
= g_new0(struct KVMAs
, s
->nr_as
);
2354 if (object_property_find(OBJECT(current_machine
), "kvm-type")) {
2355 g_autofree
char *kvm_type
= object_property_get_str(OBJECT(current_machine
),
2358 type
= mc
->kvm_type(ms
, kvm_type
);
2359 } else if (mc
->kvm_type
) {
2360 type
= mc
->kvm_type(ms
, NULL
);
2364 ret
= kvm_ioctl(s
, KVM_CREATE_VM
, type
);
2365 } while (ret
== -EINTR
);
2368 fprintf(stderr
, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret
,
2372 if (ret
== -EINVAL
) {
2374 "Host kernel setup problem detected. Please verify:\n");
2375 fprintf(stderr
, "- for kernels supporting the switch_amode or"
2376 " user_mode parameters, whether\n");
2378 " user space is running in primary address space\n");
2380 "- for kernels supporting the vm.allocate_pgste sysctl, "
2381 "whether it is enabled\n");
2383 #elif defined(TARGET_PPC)
2384 if (ret
== -EINVAL
) {
2386 "PPC KVM module is not loaded. Try modprobe kvm_%s.\n",
2387 (type
== 2) ? "pr" : "hv");
2395 /* check the vcpu limits */
2396 soft_vcpus_limit
= kvm_recommended_vcpus(s
);
2397 hard_vcpus_limit
= kvm_max_vcpus(s
);
2400 if (nc
->num
> soft_vcpus_limit
) {
2401 warn_report("Number of %s cpus requested (%d) exceeds "
2402 "the recommended cpus supported by KVM (%d)",
2403 nc
->name
, nc
->num
, soft_vcpus_limit
);
2405 if (nc
->num
> hard_vcpus_limit
) {
2406 fprintf(stderr
, "Number of %s cpus requested (%d) exceeds "
2407 "the maximum cpus supported by KVM (%d)\n",
2408 nc
->name
, nc
->num
, hard_vcpus_limit
);
2415 missing_cap
= kvm_check_extension_list(s
, kvm_required_capabilites
);
2418 kvm_check_extension_list(s
, kvm_arch_required_capabilities
);
2422 fprintf(stderr
, "kvm does not support %s\n%s",
2423 missing_cap
->name
, upgrade_note
);
2427 s
->coalesced_mmio
= kvm_check_extension(s
, KVM_CAP_COALESCED_MMIO
);
2428 s
->coalesced_pio
= s
->coalesced_mmio
&&
2429 kvm_check_extension(s
, KVM_CAP_COALESCED_PIO
);
2432 * Enable KVM dirty ring if supported, otherwise fall back to
2433 * dirty logging mode
2435 if (s
->kvm_dirty_ring_size
> 0) {
2436 uint64_t ring_bytes
;
2438 ring_bytes
= s
->kvm_dirty_ring_size
* sizeof(struct kvm_dirty_gfn
);
2440 /* Read the max supported pages */
2441 ret
= kvm_vm_check_extension(s
, KVM_CAP_DIRTY_LOG_RING
);
2443 if (ring_bytes
> ret
) {
2444 error_report("KVM dirty ring size %" PRIu32
" too big "
2445 "(maximum is %ld). Please use a smaller value.",
2446 s
->kvm_dirty_ring_size
,
2447 (long)ret
/ sizeof(struct kvm_dirty_gfn
));
2452 ret
= kvm_vm_enable_cap(s
, KVM_CAP_DIRTY_LOG_RING
, 0, ring_bytes
);
2454 error_report("Enabling of KVM dirty ring failed: %s. "
2455 "Suggested minimum value is 1024.", strerror(-ret
));
2459 s
->kvm_dirty_ring_bytes
= ring_bytes
;
2461 warn_report("KVM dirty ring not available, using bitmap method");
2462 s
->kvm_dirty_ring_size
= 0;
2467 * KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is not needed when dirty ring is
2468 * enabled. More importantly, KVM_DIRTY_LOG_INITIALLY_SET will assume no
2469 * page is wr-protected initially, which is against how kvm dirty ring is
2470 * usage - kvm dirty ring requires all pages are wr-protected at the very
2471 * beginning. Enabling this feature for dirty ring causes data corruption.
2473 * TODO: Without KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 and kvm clear dirty log,
2474 * we may expect a higher stall time when starting the migration. In the
2475 * future we can enable KVM_CLEAR_DIRTY_LOG to work with dirty ring too:
2476 * instead of clearing dirty bit, it can be a way to explicitly wr-protect
2479 if (!s
->kvm_dirty_ring_size
) {
2480 dirty_log_manual_caps
=
2481 kvm_check_extension(s
, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2
);
2482 dirty_log_manual_caps
&= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE
|
2483 KVM_DIRTY_LOG_INITIALLY_SET
);
2484 s
->manual_dirty_log_protect
= dirty_log_manual_caps
;
2485 if (dirty_log_manual_caps
) {
2486 ret
= kvm_vm_enable_cap(s
, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2
, 0,
2487 dirty_log_manual_caps
);
2489 warn_report("Trying to enable capability %"PRIu64
" of "
2490 "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
2491 "Falling back to the legacy mode. ",
2492 dirty_log_manual_caps
);
2493 s
->manual_dirty_log_protect
= 0;
2498 #ifdef KVM_CAP_VCPU_EVENTS
2499 s
->vcpu_events
= kvm_check_extension(s
, KVM_CAP_VCPU_EVENTS
);
2502 s
->robust_singlestep
=
2503 kvm_check_extension(s
, KVM_CAP_X86_ROBUST_SINGLESTEP
);
2505 #ifdef KVM_CAP_DEBUGREGS
2506 s
->debugregs
= kvm_check_extension(s
, KVM_CAP_DEBUGREGS
);
2509 s
->max_nested_state_len
= kvm_check_extension(s
, KVM_CAP_NESTED_STATE
);
2511 #ifdef KVM_CAP_IRQ_ROUTING
2512 kvm_direct_msi_allowed
= (kvm_check_extension(s
, KVM_CAP_SIGNAL_MSI
) > 0);
2515 s
->intx_set_mask
= kvm_check_extension(s
, KVM_CAP_PCI_2_3
);
2517 s
->irq_set_ioctl
= KVM_IRQ_LINE
;
2518 if (kvm_check_extension(s
, KVM_CAP_IRQ_INJECT_STATUS
)) {
2519 s
->irq_set_ioctl
= KVM_IRQ_LINE_STATUS
;
2522 kvm_readonly_mem_allowed
=
2523 (kvm_check_extension(s
, KVM_CAP_READONLY_MEM
) > 0);
2525 kvm_eventfds_allowed
=
2526 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD
) > 0);
2528 kvm_irqfds_allowed
=
2529 (kvm_check_extension(s
, KVM_CAP_IRQFD
) > 0);
2531 kvm_resamplefds_allowed
=
2532 (kvm_check_extension(s
, KVM_CAP_IRQFD_RESAMPLE
) > 0);
2534 kvm_vm_attributes_allowed
=
2535 (kvm_check_extension(s
, KVM_CAP_VM_ATTRIBUTES
) > 0);
2537 kvm_ioeventfd_any_length_allowed
=
2538 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD_ANY_LENGTH
) > 0);
2540 #ifdef KVM_CAP_SET_GUEST_DEBUG
2541 kvm_has_guest_debug
=
2542 (kvm_check_extension(s
, KVM_CAP_SET_GUEST_DEBUG
) > 0);
2545 kvm_sstep_flags
= 0;
2546 if (kvm_has_guest_debug
) {
2547 kvm_sstep_flags
= SSTEP_ENABLE
;
2549 #if defined KVM_CAP_SET_GUEST_DEBUG2
2550 int guest_debug_flags
=
2551 kvm_check_extension(s
, KVM_CAP_SET_GUEST_DEBUG2
);
2553 if (guest_debug_flags
& KVM_GUESTDBG_BLOCKIRQ
) {
2554 kvm_sstep_flags
|= SSTEP_NOIRQ
;
2561 ret
= kvm_arch_init(ms
, s
);
2566 if (s
->kernel_irqchip_split
== ON_OFF_AUTO_AUTO
) {
2567 s
->kernel_irqchip_split
= mc
->default_kernel_irqchip_split
? ON_OFF_AUTO_ON
: ON_OFF_AUTO_OFF
;
2570 qemu_register_reset(kvm_unpoison_all
, NULL
);
2572 if (s
->kernel_irqchip_allowed
) {
2573 kvm_irqchip_create(s
);
2576 if (kvm_eventfds_allowed
) {
2577 s
->memory_listener
.listener
.eventfd_add
= kvm_mem_ioeventfd_add
;
2578 s
->memory_listener
.listener
.eventfd_del
= kvm_mem_ioeventfd_del
;
2580 s
->memory_listener
.listener
.coalesced_io_add
= kvm_coalesce_mmio_region
;
2581 s
->memory_listener
.listener
.coalesced_io_del
= kvm_uncoalesce_mmio_region
;
2583 kvm_memory_listener_register(s
, &s
->memory_listener
,
2584 &address_space_memory
, 0, "kvm-memory");
2585 if (kvm_eventfds_allowed
) {
2586 memory_listener_register(&kvm_io_listener
,
2589 memory_listener_register(&kvm_coalesced_pio_listener
,
2592 s
->many_ioeventfds
= kvm_check_many_ioeventfds();
2594 s
->sync_mmu
= !!kvm_vm_check_extension(kvm_state
, KVM_CAP_SYNC_MMU
);
2596 ret
= ram_block_discard_disable(true);
2600 if (s
->kvm_dirty_ring_size
) {
2601 ret
= kvm_dirty_ring_reaper_init(s
);
2607 if (kvm_check_extension(kvm_state
, KVM_CAP_BINARY_STATS_FD
)) {
2608 add_stats_callbacks(STATS_PROVIDER_KVM
, query_stats_cb
,
2609 query_stats_schemas_cb
);
2622 g_free(s
->memory_listener
.slots
);
2627 void kvm_set_sigmask_len(KVMState
*s
, unsigned int sigmask_len
)
2629 s
->sigmask_len
= sigmask_len
;
2632 static void kvm_handle_io(uint16_t port
, MemTxAttrs attrs
, void *data
, int direction
,
2633 int size
, uint32_t count
)
2636 uint8_t *ptr
= data
;
2638 for (i
= 0; i
< count
; i
++) {
2639 address_space_rw(&address_space_io
, port
, attrs
,
2641 direction
== KVM_EXIT_IO_OUT
);
2646 static int kvm_handle_internal_error(CPUState
*cpu
, struct kvm_run
*run
)
2648 fprintf(stderr
, "KVM internal error. Suberror: %d\n",
2649 run
->internal
.suberror
);
2651 if (kvm_check_extension(kvm_state
, KVM_CAP_INTERNAL_ERROR_DATA
)) {
2654 for (i
= 0; i
< run
->internal
.ndata
; ++i
) {
2655 fprintf(stderr
, "extra data[%d]: 0x%016"PRIx64
"\n",
2656 i
, (uint64_t)run
->internal
.data
[i
]);
2659 if (run
->internal
.suberror
== KVM_INTERNAL_ERROR_EMULATION
) {
2660 fprintf(stderr
, "emulation failure\n");
2661 if (!kvm_arch_stop_on_emulation_error(cpu
)) {
2662 cpu_dump_state(cpu
, stderr
, CPU_DUMP_CODE
);
2663 return EXCP_INTERRUPT
;
2666 /* FIXME: Should trigger a qmp message to let management know
2667 * something went wrong.
2672 void kvm_flush_coalesced_mmio_buffer(void)
2674 KVMState
*s
= kvm_state
;
2676 if (s
->coalesced_flush_in_progress
) {
2680 s
->coalesced_flush_in_progress
= true;
2682 if (s
->coalesced_mmio_ring
) {
2683 struct kvm_coalesced_mmio_ring
*ring
= s
->coalesced_mmio_ring
;
2684 while (ring
->first
!= ring
->last
) {
2685 struct kvm_coalesced_mmio
*ent
;
2687 ent
= &ring
->coalesced_mmio
[ring
->first
];
2689 if (ent
->pio
== 1) {
2690 address_space_write(&address_space_io
, ent
->phys_addr
,
2691 MEMTXATTRS_UNSPECIFIED
, ent
->data
,
2694 cpu_physical_memory_write(ent
->phys_addr
, ent
->data
, ent
->len
);
2697 ring
->first
= (ring
->first
+ 1) % KVM_COALESCED_MMIO_MAX
;
2701 s
->coalesced_flush_in_progress
= false;
2704 bool kvm_cpu_check_are_resettable(void)
2706 return kvm_arch_cpu_check_are_resettable();
2709 static void do_kvm_cpu_synchronize_state(CPUState
*cpu
, run_on_cpu_data arg
)
2711 if (!cpu
->vcpu_dirty
) {
2712 kvm_arch_get_registers(cpu
);
2713 cpu
->vcpu_dirty
= true;
2717 void kvm_cpu_synchronize_state(CPUState
*cpu
)
2719 if (!cpu
->vcpu_dirty
) {
2720 run_on_cpu(cpu
, do_kvm_cpu_synchronize_state
, RUN_ON_CPU_NULL
);
2724 static void do_kvm_cpu_synchronize_post_reset(CPUState
*cpu
, run_on_cpu_data arg
)
2726 kvm_arch_put_registers(cpu
, KVM_PUT_RESET_STATE
);
2727 cpu
->vcpu_dirty
= false;
2730 void kvm_cpu_synchronize_post_reset(CPUState
*cpu
)
2732 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_reset
, RUN_ON_CPU_NULL
);
2735 static void do_kvm_cpu_synchronize_post_init(CPUState
*cpu
, run_on_cpu_data arg
)
2737 kvm_arch_put_registers(cpu
, KVM_PUT_FULL_STATE
);
2738 cpu
->vcpu_dirty
= false;
2741 void kvm_cpu_synchronize_post_init(CPUState
*cpu
)
2743 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_init
, RUN_ON_CPU_NULL
);
2746 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
, run_on_cpu_data arg
)
2748 cpu
->vcpu_dirty
= true;
2751 void kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
)
2753 run_on_cpu(cpu
, do_kvm_cpu_synchronize_pre_loadvm
, RUN_ON_CPU_NULL
);
2756 #ifdef KVM_HAVE_MCE_INJECTION
2757 static __thread
void *pending_sigbus_addr
;
2758 static __thread
int pending_sigbus_code
;
2759 static __thread
bool have_sigbus_pending
;
2762 static void kvm_cpu_kick(CPUState
*cpu
)
2764 qatomic_set(&cpu
->kvm_run
->immediate_exit
, 1);
2767 static void kvm_cpu_kick_self(void)
2769 if (kvm_immediate_exit
) {
2770 kvm_cpu_kick(current_cpu
);
2772 qemu_cpu_kick_self();
2776 static void kvm_eat_signals(CPUState
*cpu
)
2778 struct timespec ts
= { 0, 0 };
2784 if (kvm_immediate_exit
) {
2785 qatomic_set(&cpu
->kvm_run
->immediate_exit
, 0);
2786 /* Write kvm_run->immediate_exit before the cpu->exit_request
2787 * write in kvm_cpu_exec.
2793 sigemptyset(&waitset
);
2794 sigaddset(&waitset
, SIG_IPI
);
2797 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
2798 if (r
== -1 && !(errno
== EAGAIN
|| errno
== EINTR
)) {
2799 perror("sigtimedwait");
2803 r
= sigpending(&chkset
);
2805 perror("sigpending");
2808 } while (sigismember(&chkset
, SIG_IPI
));
2811 int kvm_cpu_exec(CPUState
*cpu
)
2813 struct kvm_run
*run
= cpu
->kvm_run
;
2816 DPRINTF("kvm_cpu_exec()\n");
2818 if (kvm_arch_process_async_events(cpu
)) {
2819 qatomic_set(&cpu
->exit_request
, 0);
2823 qemu_mutex_unlock_iothread();
2824 cpu_exec_start(cpu
);
2829 if (cpu
->vcpu_dirty
) {
2830 kvm_arch_put_registers(cpu
, KVM_PUT_RUNTIME_STATE
);
2831 cpu
->vcpu_dirty
= false;
2834 kvm_arch_pre_run(cpu
, run
);
2835 if (qatomic_read(&cpu
->exit_request
)) {
2836 DPRINTF("interrupt exit requested\n");
2838 * KVM requires us to reenter the kernel after IO exits to complete
2839 * instruction emulation. This self-signal will ensure that we
2842 kvm_cpu_kick_self();
2845 /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2846 * Matching barrier in kvm_eat_signals.
2850 run_ret
= kvm_vcpu_ioctl(cpu
, KVM_RUN
, 0);
2852 attrs
= kvm_arch_post_run(cpu
, run
);
2854 #ifdef KVM_HAVE_MCE_INJECTION
2855 if (unlikely(have_sigbus_pending
)) {
2856 qemu_mutex_lock_iothread();
2857 kvm_arch_on_sigbus_vcpu(cpu
, pending_sigbus_code
,
2858 pending_sigbus_addr
);
2859 have_sigbus_pending
= false;
2860 qemu_mutex_unlock_iothread();
2865 if (run_ret
== -EINTR
|| run_ret
== -EAGAIN
) {
2866 DPRINTF("io window exit\n");
2867 kvm_eat_signals(cpu
);
2868 ret
= EXCP_INTERRUPT
;
2871 fprintf(stderr
, "error: kvm run failed %s\n",
2872 strerror(-run_ret
));
2874 if (run_ret
== -EBUSY
) {
2876 "This is probably because your SMT is enabled.\n"
2877 "VCPU can only run on primary threads with all "
2878 "secondary threads offline.\n");
2885 trace_kvm_run_exit(cpu
->cpu_index
, run
->exit_reason
);
2886 switch (run
->exit_reason
) {
2888 DPRINTF("handle_io\n");
2889 /* Called outside BQL */
2890 kvm_handle_io(run
->io
.port
, attrs
,
2891 (uint8_t *)run
+ run
->io
.data_offset
,
2898 DPRINTF("handle_mmio\n");
2899 /* Called outside BQL */
2900 address_space_rw(&address_space_memory
,
2901 run
->mmio
.phys_addr
, attrs
,
2904 run
->mmio
.is_write
);
2907 case KVM_EXIT_IRQ_WINDOW_OPEN
:
2908 DPRINTF("irq_window_open\n");
2909 ret
= EXCP_INTERRUPT
;
2911 case KVM_EXIT_SHUTDOWN
:
2912 DPRINTF("shutdown\n");
2913 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
2914 ret
= EXCP_INTERRUPT
;
2916 case KVM_EXIT_UNKNOWN
:
2917 fprintf(stderr
, "KVM: unknown exit, hardware reason %" PRIx64
"\n",
2918 (uint64_t)run
->hw
.hardware_exit_reason
);
2921 case KVM_EXIT_INTERNAL_ERROR
:
2922 ret
= kvm_handle_internal_error(cpu
, run
);
2924 case KVM_EXIT_DIRTY_RING_FULL
:
2926 * We shouldn't continue if the dirty ring of this vcpu is
2927 * still full. Got kicked by KVM_RESET_DIRTY_RINGS.
2929 trace_kvm_dirty_ring_full(cpu
->cpu_index
);
2930 qemu_mutex_lock_iothread();
2932 * We throttle vCPU by making it sleep once it exit from kernel
2933 * due to dirty ring full. In the dirtylimit scenario, reaping
2934 * all vCPUs after a single vCPU dirty ring get full result in
2935 * the miss of sleep, so just reap the ring-fulled vCPU.
2937 if (dirtylimit_in_service()) {
2938 kvm_dirty_ring_reap(kvm_state
, cpu
);
2940 kvm_dirty_ring_reap(kvm_state
, NULL
);
2942 qemu_mutex_unlock_iothread();
2943 dirtylimit_vcpu_execute(cpu
);
2946 case KVM_EXIT_SYSTEM_EVENT
:
2947 switch (run
->system_event
.type
) {
2948 case KVM_SYSTEM_EVENT_SHUTDOWN
:
2949 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN
);
2950 ret
= EXCP_INTERRUPT
;
2952 case KVM_SYSTEM_EVENT_RESET
:
2953 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
2954 ret
= EXCP_INTERRUPT
;
2956 case KVM_SYSTEM_EVENT_CRASH
:
2957 kvm_cpu_synchronize_state(cpu
);
2958 qemu_mutex_lock_iothread();
2959 qemu_system_guest_panicked(cpu_get_crash_info(cpu
));
2960 qemu_mutex_unlock_iothread();
2964 DPRINTF("kvm_arch_handle_exit\n");
2965 ret
= kvm_arch_handle_exit(cpu
, run
);
2970 DPRINTF("kvm_arch_handle_exit\n");
2971 ret
= kvm_arch_handle_exit(cpu
, run
);
2977 qemu_mutex_lock_iothread();
2980 cpu_dump_state(cpu
, stderr
, CPU_DUMP_CODE
);
2981 vm_stop(RUN_STATE_INTERNAL_ERROR
);
2984 qatomic_set(&cpu
->exit_request
, 0);
2988 int kvm_ioctl(KVMState
*s
, int type
, ...)
2995 arg
= va_arg(ap
, void *);
2998 trace_kvm_ioctl(type
, arg
);
2999 ret
= ioctl(s
->fd
, type
, arg
);
3006 int kvm_vm_ioctl(KVMState
*s
, int type
, ...)
3013 arg
= va_arg(ap
, void *);
3016 trace_kvm_vm_ioctl(type
, arg
);
3017 ret
= ioctl(s
->vmfd
, type
, arg
);
3024 int kvm_vcpu_ioctl(CPUState
*cpu
, int type
, ...)
3031 arg
= va_arg(ap
, void *);
3034 trace_kvm_vcpu_ioctl(cpu
->cpu_index
, type
, arg
);
3035 ret
= ioctl(cpu
->kvm_fd
, type
, arg
);
3042 int kvm_device_ioctl(int fd
, int type
, ...)
3049 arg
= va_arg(ap
, void *);
3052 trace_kvm_device_ioctl(fd
, type
, arg
);
3053 ret
= ioctl(fd
, type
, arg
);
3060 int kvm_vm_check_attr(KVMState
*s
, uint32_t group
, uint64_t attr
)
3063 struct kvm_device_attr attribute
= {
3068 if (!kvm_vm_attributes_allowed
) {
3072 ret
= kvm_vm_ioctl(s
, KVM_HAS_DEVICE_ATTR
, &attribute
);
3073 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
3077 int kvm_device_check_attr(int dev_fd
, uint32_t group
, uint64_t attr
)
3079 struct kvm_device_attr attribute
= {
3085 return kvm_device_ioctl(dev_fd
, KVM_HAS_DEVICE_ATTR
, &attribute
) ? 0 : 1;
3088 int kvm_device_access(int fd
, int group
, uint64_t attr
,
3089 void *val
, bool write
, Error
**errp
)
3091 struct kvm_device_attr kvmattr
;
3095 kvmattr
.group
= group
;
3096 kvmattr
.attr
= attr
;
3097 kvmattr
.addr
= (uintptr_t)val
;
3099 err
= kvm_device_ioctl(fd
,
3100 write
? KVM_SET_DEVICE_ATTR
: KVM_GET_DEVICE_ATTR
,
3103 error_setg_errno(errp
, -err
,
3104 "KVM_%s_DEVICE_ATTR failed: Group %d "
3105 "attr 0x%016" PRIx64
,
3106 write
? "SET" : "GET", group
, attr
);
3111 bool kvm_has_sync_mmu(void)
3113 return kvm_state
->sync_mmu
;
3116 int kvm_has_vcpu_events(void)
3118 return kvm_state
->vcpu_events
;
3121 int kvm_has_robust_singlestep(void)
3123 return kvm_state
->robust_singlestep
;
3126 int kvm_has_debugregs(void)
3128 return kvm_state
->debugregs
;
3131 int kvm_max_nested_state_length(void)
3133 return kvm_state
->max_nested_state_len
;
3136 int kvm_has_many_ioeventfds(void)
3138 if (!kvm_enabled()) {
3141 return kvm_state
->many_ioeventfds
;
3144 int kvm_has_gsi_routing(void)
3146 #ifdef KVM_CAP_IRQ_ROUTING
3147 return kvm_check_extension(kvm_state
, KVM_CAP_IRQ_ROUTING
);
3153 int kvm_has_intx_set_mask(void)
3155 return kvm_state
->intx_set_mask
;
3158 bool kvm_arm_supports_user_irq(void)
3160 return kvm_check_extension(kvm_state
, KVM_CAP_ARM_USER_IRQ
);
3163 #ifdef KVM_CAP_SET_GUEST_DEBUG
3164 struct kvm_sw_breakpoint
*kvm_find_sw_breakpoint(CPUState
*cpu
,
3167 struct kvm_sw_breakpoint
*bp
;
3169 QTAILQ_FOREACH(bp
, &cpu
->kvm_state
->kvm_sw_breakpoints
, entry
) {
3177 int kvm_sw_breakpoints_active(CPUState
*cpu
)
3179 return !QTAILQ_EMPTY(&cpu
->kvm_state
->kvm_sw_breakpoints
);
3182 struct kvm_set_guest_debug_data
{
3183 struct kvm_guest_debug dbg
;
3187 static void kvm_invoke_set_guest_debug(CPUState
*cpu
, run_on_cpu_data data
)
3189 struct kvm_set_guest_debug_data
*dbg_data
=
3190 (struct kvm_set_guest_debug_data
*) data
.host_ptr
;
3192 dbg_data
->err
= kvm_vcpu_ioctl(cpu
, KVM_SET_GUEST_DEBUG
,
3196 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
3198 struct kvm_set_guest_debug_data data
;
3200 data
.dbg
.control
= reinject_trap
;
3202 if (cpu
->singlestep_enabled
) {
3203 data
.dbg
.control
|= KVM_GUESTDBG_ENABLE
| KVM_GUESTDBG_SINGLESTEP
;
3205 if (cpu
->singlestep_enabled
& SSTEP_NOIRQ
) {
3206 data
.dbg
.control
|= KVM_GUESTDBG_BLOCKIRQ
;
3209 kvm_arch_update_guest_debug(cpu
, &data
.dbg
);
3211 run_on_cpu(cpu
, kvm_invoke_set_guest_debug
,
3212 RUN_ON_CPU_HOST_PTR(&data
));
3216 bool kvm_supports_guest_debug(void)
3218 /* probed during kvm_init() */
3219 return kvm_has_guest_debug
;
3222 int kvm_insert_breakpoint(CPUState
*cpu
, int type
, hwaddr addr
, hwaddr len
)
3224 struct kvm_sw_breakpoint
*bp
;
3227 if (type
== GDB_BREAKPOINT_SW
) {
3228 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
3234 bp
= g_new(struct kvm_sw_breakpoint
, 1);
3237 err
= kvm_arch_insert_sw_breakpoint(cpu
, bp
);
3243 QTAILQ_INSERT_HEAD(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
3245 err
= kvm_arch_insert_hw_breakpoint(addr
, len
, type
);
3252 err
= kvm_update_guest_debug(cpu
, 0);
3260 int kvm_remove_breakpoint(CPUState
*cpu
, int type
, hwaddr addr
, hwaddr len
)
3262 struct kvm_sw_breakpoint
*bp
;
3265 if (type
== GDB_BREAKPOINT_SW
) {
3266 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
3271 if (bp
->use_count
> 1) {
3276 err
= kvm_arch_remove_sw_breakpoint(cpu
, bp
);
3281 QTAILQ_REMOVE(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
3284 err
= kvm_arch_remove_hw_breakpoint(addr
, len
, type
);
3291 err
= kvm_update_guest_debug(cpu
, 0);
3299 void kvm_remove_all_breakpoints(CPUState
*cpu
)
3301 struct kvm_sw_breakpoint
*bp
, *next
;
3302 KVMState
*s
= cpu
->kvm_state
;
3305 QTAILQ_FOREACH_SAFE(bp
, &s
->kvm_sw_breakpoints
, entry
, next
) {
3306 if (kvm_arch_remove_sw_breakpoint(cpu
, bp
) != 0) {
3307 /* Try harder to find a CPU that currently sees the breakpoint. */
3308 CPU_FOREACH(tmpcpu
) {
3309 if (kvm_arch_remove_sw_breakpoint(tmpcpu
, bp
) == 0) {
3314 QTAILQ_REMOVE(&s
->kvm_sw_breakpoints
, bp
, entry
);
3317 kvm_arch_remove_all_hw_breakpoints();
3320 kvm_update_guest_debug(cpu
, 0);
3324 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
3326 static int kvm_set_signal_mask(CPUState
*cpu
, const sigset_t
*sigset
)
3328 KVMState
*s
= kvm_state
;
3329 struct kvm_signal_mask
*sigmask
;
3332 sigmask
= g_malloc(sizeof(*sigmask
) + sizeof(*sigset
));
3334 sigmask
->len
= s
->sigmask_len
;
3335 memcpy(sigmask
->sigset
, sigset
, sizeof(*sigset
));
3336 r
= kvm_vcpu_ioctl(cpu
, KVM_SET_SIGNAL_MASK
, sigmask
);
3342 static void kvm_ipi_signal(int sig
)
3345 assert(kvm_immediate_exit
);
3346 kvm_cpu_kick(current_cpu
);
3350 void kvm_init_cpu_signals(CPUState
*cpu
)
3354 struct sigaction sigact
;
3356 memset(&sigact
, 0, sizeof(sigact
));
3357 sigact
.sa_handler
= kvm_ipi_signal
;
3358 sigaction(SIG_IPI
, &sigact
, NULL
);
3360 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
3361 #if defined KVM_HAVE_MCE_INJECTION
3362 sigdelset(&set
, SIGBUS
);
3363 pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
3365 sigdelset(&set
, SIG_IPI
);
3366 if (kvm_immediate_exit
) {
3367 r
= pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
3369 r
= kvm_set_signal_mask(cpu
, &set
);
3372 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(-r
));
3377 /* Called asynchronously in VCPU thread. */
3378 int kvm_on_sigbus_vcpu(CPUState
*cpu
, int code
, void *addr
)
3380 #ifdef KVM_HAVE_MCE_INJECTION
3381 if (have_sigbus_pending
) {
3384 have_sigbus_pending
= true;
3385 pending_sigbus_addr
= addr
;
3386 pending_sigbus_code
= code
;
3387 qatomic_set(&cpu
->exit_request
, 1);
3394 /* Called synchronously (via signalfd) in main thread. */
3395 int kvm_on_sigbus(int code
, void *addr
)
3397 #ifdef KVM_HAVE_MCE_INJECTION
3398 /* Action required MCE kills the process if SIGBUS is blocked. Because
3399 * that's what happens in the I/O thread, where we handle MCE via signalfd,
3400 * we can only get action optional here.
3402 assert(code
!= BUS_MCEERR_AR
);
3403 kvm_arch_on_sigbus_vcpu(first_cpu
, code
, addr
);
3410 int kvm_create_device(KVMState
*s
, uint64_t type
, bool test
)
3413 struct kvm_create_device create_dev
;
3415 create_dev
.type
= type
;
3417 create_dev
.flags
= test
? KVM_CREATE_DEVICE_TEST
: 0;
3419 if (!kvm_check_extension(s
, KVM_CAP_DEVICE_CTRL
)) {
3423 ret
= kvm_vm_ioctl(s
, KVM_CREATE_DEVICE
, &create_dev
);
3428 return test
? 0 : create_dev
.fd
;
3431 bool kvm_device_supported(int vmfd
, uint64_t type
)
3433 struct kvm_create_device create_dev
= {
3436 .flags
= KVM_CREATE_DEVICE_TEST
,
3439 if (ioctl(vmfd
, KVM_CHECK_EXTENSION
, KVM_CAP_DEVICE_CTRL
) <= 0) {
3443 return (ioctl(vmfd
, KVM_CREATE_DEVICE
, &create_dev
) >= 0);
3446 int kvm_set_one_reg(CPUState
*cs
, uint64_t id
, void *source
)
3448 struct kvm_one_reg reg
;
3452 reg
.addr
= (uintptr_t) source
;
3453 r
= kvm_vcpu_ioctl(cs
, KVM_SET_ONE_REG
, ®
);
3455 trace_kvm_failed_reg_set(id
, strerror(-r
));
3460 int kvm_get_one_reg(CPUState
*cs
, uint64_t id
, void *target
)
3462 struct kvm_one_reg reg
;
3466 reg
.addr
= (uintptr_t) target
;
3467 r
= kvm_vcpu_ioctl(cs
, KVM_GET_ONE_REG
, ®
);
3469 trace_kvm_failed_reg_get(id
, strerror(-r
));
3474 static bool kvm_accel_has_memory(MachineState
*ms
, AddressSpace
*as
,
3475 hwaddr start_addr
, hwaddr size
)
3477 KVMState
*kvm
= KVM_STATE(ms
->accelerator
);
3480 for (i
= 0; i
< kvm
->nr_as
; ++i
) {
3481 if (kvm
->as
[i
].as
== as
&& kvm
->as
[i
].ml
) {
3482 size
= MIN(kvm_max_slot_size
, size
);
3483 return NULL
!= kvm_lookup_matching_slot(kvm
->as
[i
].ml
,
3491 static void kvm_get_kvm_shadow_mem(Object
*obj
, Visitor
*v
,
3492 const char *name
, void *opaque
,
3495 KVMState
*s
= KVM_STATE(obj
);
3496 int64_t value
= s
->kvm_shadow_mem
;
3498 visit_type_int(v
, name
, &value
, errp
);
3501 static void kvm_set_kvm_shadow_mem(Object
*obj
, Visitor
*v
,
3502 const char *name
, void *opaque
,
3505 KVMState
*s
= KVM_STATE(obj
);
3509 error_setg(errp
, "Cannot set properties after the accelerator has been initialized");
3513 if (!visit_type_int(v
, name
, &value
, errp
)) {
3517 s
->kvm_shadow_mem
= value
;
3520 static void kvm_set_kernel_irqchip(Object
*obj
, Visitor
*v
,
3521 const char *name
, void *opaque
,
3524 KVMState
*s
= KVM_STATE(obj
);
3528 error_setg(errp
, "Cannot set properties after the accelerator has been initialized");
3532 if (!visit_type_OnOffSplit(v
, name
, &mode
, errp
)) {
3536 case ON_OFF_SPLIT_ON
:
3537 s
->kernel_irqchip_allowed
= true;
3538 s
->kernel_irqchip_required
= true;
3539 s
->kernel_irqchip_split
= ON_OFF_AUTO_OFF
;
3541 case ON_OFF_SPLIT_OFF
:
3542 s
->kernel_irqchip_allowed
= false;
3543 s
->kernel_irqchip_required
= false;
3544 s
->kernel_irqchip_split
= ON_OFF_AUTO_OFF
;
3546 case ON_OFF_SPLIT_SPLIT
:
3547 s
->kernel_irqchip_allowed
= true;
3548 s
->kernel_irqchip_required
= true;
3549 s
->kernel_irqchip_split
= ON_OFF_AUTO_ON
;
3552 /* The value was checked in visit_type_OnOffSplit() above. If
3553 * we get here, then something is wrong in QEMU.
3559 bool kvm_kernel_irqchip_allowed(void)
3561 return kvm_state
->kernel_irqchip_allowed
;
3564 bool kvm_kernel_irqchip_required(void)
3566 return kvm_state
->kernel_irqchip_required
;
3569 bool kvm_kernel_irqchip_split(void)
3571 return kvm_state
->kernel_irqchip_split
== ON_OFF_AUTO_ON
;
3574 static void kvm_get_dirty_ring_size(Object
*obj
, Visitor
*v
,
3575 const char *name
, void *opaque
,
3578 KVMState
*s
= KVM_STATE(obj
);
3579 uint32_t value
= s
->kvm_dirty_ring_size
;
3581 visit_type_uint32(v
, name
, &value
, errp
);
3584 static void kvm_set_dirty_ring_size(Object
*obj
, Visitor
*v
,
3585 const char *name
, void *opaque
,
3588 KVMState
*s
= KVM_STATE(obj
);
3589 Error
*error
= NULL
;
3593 error_setg(errp
, "Cannot set properties after the accelerator has been initialized");
3597 visit_type_uint32(v
, name
, &value
, &error
);
3599 error_propagate(errp
, error
);
3602 if (value
& (value
- 1)) {
3603 error_setg(errp
, "dirty-ring-size must be a power of two.");
3607 s
->kvm_dirty_ring_size
= value
;
3610 static void kvm_accel_instance_init(Object
*obj
)
3612 KVMState
*s
= KVM_STATE(obj
);
3616 s
->kvm_shadow_mem
= -1;
3617 s
->kernel_irqchip_allowed
= true;
3618 s
->kernel_irqchip_split
= ON_OFF_AUTO_AUTO
;
3619 /* KVM dirty ring is by default off */
3620 s
->kvm_dirty_ring_size
= 0;
3621 s
->notify_vmexit
= NOTIFY_VMEXIT_OPTION_RUN
;
3622 s
->notify_window
= 0;
3626 * kvm_gdbstub_sstep_flags():
3628 * Returns: SSTEP_* flags that KVM supports for guest debug. The
3629 * support is probed during kvm_init()
3631 static int kvm_gdbstub_sstep_flags(void)
3633 return kvm_sstep_flags
;
3636 static void kvm_accel_class_init(ObjectClass
*oc
, void *data
)
3638 AccelClass
*ac
= ACCEL_CLASS(oc
);
3640 ac
->init_machine
= kvm_init
;
3641 ac
->has_memory
= kvm_accel_has_memory
;
3642 ac
->allowed
= &kvm_allowed
;
3643 ac
->gdbstub_supported_sstep_flags
= kvm_gdbstub_sstep_flags
;
3645 object_class_property_add(oc
, "kernel-irqchip", "on|off|split",
3646 NULL
, kvm_set_kernel_irqchip
,
3648 object_class_property_set_description(oc
, "kernel-irqchip",
3649 "Configure KVM in-kernel irqchip");
3651 object_class_property_add(oc
, "kvm-shadow-mem", "int",
3652 kvm_get_kvm_shadow_mem
, kvm_set_kvm_shadow_mem
,
3654 object_class_property_set_description(oc
, "kvm-shadow-mem",
3655 "KVM shadow MMU size");
3657 object_class_property_add(oc
, "dirty-ring-size", "uint32",
3658 kvm_get_dirty_ring_size
, kvm_set_dirty_ring_size
,
3660 object_class_property_set_description(oc
, "dirty-ring-size",
3661 "Size of KVM dirty page ring buffer (default: 0, i.e. use bitmap)");
3663 kvm_arch_accel_class_init(oc
);
3666 static const TypeInfo kvm_accel_type
= {
3667 .name
= TYPE_KVM_ACCEL
,
3668 .parent
= TYPE_ACCEL
,
3669 .instance_init
= kvm_accel_instance_init
,
3670 .class_init
= kvm_accel_class_init
,
3671 .instance_size
= sizeof(KVMState
),
3674 static void kvm_type_init(void)
3676 type_register_static(&kvm_accel_type
);
3679 type_init(kvm_type_init
);
3681 typedef struct StatsArgs
{
3682 union StatsResultsType
{
3683 StatsResultList
**stats
;
3684 StatsSchemaList
**schema
;
3690 static StatsList
*add_kvmstat_entry(struct kvm_stats_desc
*pdesc
,
3691 uint64_t *stats_data
,
3692 StatsList
*stats_list
,
3697 uint64List
*val_list
= NULL
;
3699 /* Only add stats that we understand. */
3700 switch (pdesc
->flags
& KVM_STATS_TYPE_MASK
) {
3701 case KVM_STATS_TYPE_CUMULATIVE
:
3702 case KVM_STATS_TYPE_INSTANT
:
3703 case KVM_STATS_TYPE_PEAK
:
3704 case KVM_STATS_TYPE_LINEAR_HIST
:
3705 case KVM_STATS_TYPE_LOG_HIST
:
3711 switch (pdesc
->flags
& KVM_STATS_UNIT_MASK
) {
3712 case KVM_STATS_UNIT_NONE
:
3713 case KVM_STATS_UNIT_BYTES
:
3714 case KVM_STATS_UNIT_CYCLES
:
3715 case KVM_STATS_UNIT_SECONDS
:
3716 case KVM_STATS_UNIT_BOOLEAN
:
3722 switch (pdesc
->flags
& KVM_STATS_BASE_MASK
) {
3723 case KVM_STATS_BASE_POW10
:
3724 case KVM_STATS_BASE_POW2
:
3730 /* Alloc and populate data list */
3731 stats
= g_new0(Stats
, 1);
3732 stats
->name
= g_strdup(pdesc
->name
);
3733 stats
->value
= g_new0(StatsValue
, 1);;
3735 if ((pdesc
->flags
& KVM_STATS_UNIT_MASK
) == KVM_STATS_UNIT_BOOLEAN
) {
3736 stats
->value
->u
.boolean
= *stats_data
;
3737 stats
->value
->type
= QTYPE_QBOOL
;
3738 } else if (pdesc
->size
== 1) {
3739 stats
->value
->u
.scalar
= *stats_data
;
3740 stats
->value
->type
= QTYPE_QNUM
;
3743 for (i
= 0; i
< pdesc
->size
; i
++) {
3744 QAPI_LIST_PREPEND(val_list
, stats_data
[i
]);
3746 stats
->value
->u
.list
= val_list
;
3747 stats
->value
->type
= QTYPE_QLIST
;
3750 QAPI_LIST_PREPEND(stats_list
, stats
);
3754 static StatsSchemaValueList
*add_kvmschema_entry(struct kvm_stats_desc
*pdesc
,
3755 StatsSchemaValueList
*list
,
3758 StatsSchemaValueList
*schema_entry
= g_new0(StatsSchemaValueList
, 1);
3759 schema_entry
->value
= g_new0(StatsSchemaValue
, 1);
3761 switch (pdesc
->flags
& KVM_STATS_TYPE_MASK
) {
3762 case KVM_STATS_TYPE_CUMULATIVE
:
3763 schema_entry
->value
->type
= STATS_TYPE_CUMULATIVE
;
3765 case KVM_STATS_TYPE_INSTANT
:
3766 schema_entry
->value
->type
= STATS_TYPE_INSTANT
;
3768 case KVM_STATS_TYPE_PEAK
:
3769 schema_entry
->value
->type
= STATS_TYPE_PEAK
;
3771 case KVM_STATS_TYPE_LINEAR_HIST
:
3772 schema_entry
->value
->type
= STATS_TYPE_LINEAR_HISTOGRAM
;
3773 schema_entry
->value
->bucket_size
= pdesc
->bucket_size
;
3774 schema_entry
->value
->has_bucket_size
= true;
3776 case KVM_STATS_TYPE_LOG_HIST
:
3777 schema_entry
->value
->type
= STATS_TYPE_LOG2_HISTOGRAM
;
3783 switch (pdesc
->flags
& KVM_STATS_UNIT_MASK
) {
3784 case KVM_STATS_UNIT_NONE
:
3786 case KVM_STATS_UNIT_BOOLEAN
:
3787 schema_entry
->value
->has_unit
= true;
3788 schema_entry
->value
->unit
= STATS_UNIT_BOOLEAN
;
3790 case KVM_STATS_UNIT_BYTES
:
3791 schema_entry
->value
->has_unit
= true;
3792 schema_entry
->value
->unit
= STATS_UNIT_BYTES
;
3794 case KVM_STATS_UNIT_CYCLES
:
3795 schema_entry
->value
->has_unit
= true;
3796 schema_entry
->value
->unit
= STATS_UNIT_CYCLES
;
3798 case KVM_STATS_UNIT_SECONDS
:
3799 schema_entry
->value
->has_unit
= true;
3800 schema_entry
->value
->unit
= STATS_UNIT_SECONDS
;
3806 schema_entry
->value
->exponent
= pdesc
->exponent
;
3807 if (pdesc
->exponent
) {
3808 switch (pdesc
->flags
& KVM_STATS_BASE_MASK
) {
3809 case KVM_STATS_BASE_POW10
:
3810 schema_entry
->value
->has_base
= true;
3811 schema_entry
->value
->base
= 10;
3813 case KVM_STATS_BASE_POW2
:
3814 schema_entry
->value
->has_base
= true;
3815 schema_entry
->value
->base
= 2;
3822 schema_entry
->value
->name
= g_strdup(pdesc
->name
);
3823 schema_entry
->next
= list
;
3824 return schema_entry
;
3826 g_free(schema_entry
->value
);
3827 g_free(schema_entry
);
3831 /* Cached stats descriptors */
3832 typedef struct StatsDescriptors
{
3833 const char *ident
; /* cache key, currently the StatsTarget */
3834 struct kvm_stats_desc
*kvm_stats_desc
;
3835 struct kvm_stats_header kvm_stats_header
;
3836 QTAILQ_ENTRY(StatsDescriptors
) next
;
3839 static QTAILQ_HEAD(, StatsDescriptors
) stats_descriptors
=
3840 QTAILQ_HEAD_INITIALIZER(stats_descriptors
);
3843 * Return the descriptors for 'target', that either have already been read
3844 * or are retrieved from 'stats_fd'.
3846 static StatsDescriptors
*find_stats_descriptors(StatsTarget target
, int stats_fd
,
3849 StatsDescriptors
*descriptors
;
3851 struct kvm_stats_desc
*kvm_stats_desc
;
3852 struct kvm_stats_header
*kvm_stats_header
;
3856 ident
= StatsTarget_str(target
);
3857 QTAILQ_FOREACH(descriptors
, &stats_descriptors
, next
) {
3858 if (g_str_equal(descriptors
->ident
, ident
)) {
3863 descriptors
= g_new0(StatsDescriptors
, 1);
3865 /* Read stats header */
3866 kvm_stats_header
= &descriptors
->kvm_stats_header
;
3867 ret
= read(stats_fd
, kvm_stats_header
, sizeof(*kvm_stats_header
));
3868 if (ret
!= sizeof(*kvm_stats_header
)) {
3869 error_setg(errp
, "KVM stats: failed to read stats header: "
3870 "expected %zu actual %zu",
3871 sizeof(*kvm_stats_header
), ret
);
3872 g_free(descriptors
);
3875 size_desc
= sizeof(*kvm_stats_desc
) + kvm_stats_header
->name_size
;
3877 /* Read stats descriptors */
3878 kvm_stats_desc
= g_malloc0_n(kvm_stats_header
->num_desc
, size_desc
);
3879 ret
= pread(stats_fd
, kvm_stats_desc
,
3880 size_desc
* kvm_stats_header
->num_desc
,
3881 kvm_stats_header
->desc_offset
);
3883 if (ret
!= size_desc
* kvm_stats_header
->num_desc
) {
3884 error_setg(errp
, "KVM stats: failed to read stats descriptors: "
3885 "expected %zu actual %zu",
3886 size_desc
* kvm_stats_header
->num_desc
, ret
);
3887 g_free(descriptors
);
3888 g_free(kvm_stats_desc
);
3891 descriptors
->kvm_stats_desc
= kvm_stats_desc
;
3892 descriptors
->ident
= ident
;
3893 QTAILQ_INSERT_TAIL(&stats_descriptors
, descriptors
, next
);
3897 static void query_stats(StatsResultList
**result
, StatsTarget target
,
3898 strList
*names
, int stats_fd
, Error
**errp
)
3900 struct kvm_stats_desc
*kvm_stats_desc
;
3901 struct kvm_stats_header
*kvm_stats_header
;
3902 StatsDescriptors
*descriptors
;
3903 g_autofree
uint64_t *stats_data
= NULL
;
3904 struct kvm_stats_desc
*pdesc
;
3905 StatsList
*stats_list
= NULL
;
3906 size_t size_desc
, size_data
= 0;
3910 descriptors
= find_stats_descriptors(target
, stats_fd
, errp
);
3915 kvm_stats_header
= &descriptors
->kvm_stats_header
;
3916 kvm_stats_desc
= descriptors
->kvm_stats_desc
;
3917 size_desc
= sizeof(*kvm_stats_desc
) + kvm_stats_header
->name_size
;
3919 /* Tally the total data size; read schema data */
3920 for (i
= 0; i
< kvm_stats_header
->num_desc
; ++i
) {
3921 pdesc
= (void *)kvm_stats_desc
+ i
* size_desc
;
3922 size_data
+= pdesc
->size
* sizeof(*stats_data
);
3925 stats_data
= g_malloc0(size_data
);
3926 ret
= pread(stats_fd
, stats_data
, size_data
, kvm_stats_header
->data_offset
);
3928 if (ret
!= size_data
) {
3929 error_setg(errp
, "KVM stats: failed to read data: "
3930 "expected %zu actual %zu", size_data
, ret
);
3934 for (i
= 0; i
< kvm_stats_header
->num_desc
; ++i
) {
3936 pdesc
= (void *)kvm_stats_desc
+ i
* size_desc
;
3938 /* Add entry to the list */
3939 stats
= (void *)stats_data
+ pdesc
->offset
;
3940 if (!apply_str_list_filter(pdesc
->name
, names
)) {
3943 stats_list
= add_kvmstat_entry(pdesc
, stats
, stats_list
, errp
);
3951 case STATS_TARGET_VM
:
3952 add_stats_entry(result
, STATS_PROVIDER_KVM
, NULL
, stats_list
);
3954 case STATS_TARGET_VCPU
:
3955 add_stats_entry(result
, STATS_PROVIDER_KVM
,
3956 current_cpu
->parent_obj
.canonical_path
,
3960 g_assert_not_reached();
3964 static void query_stats_schema(StatsSchemaList
**result
, StatsTarget target
,
3965 int stats_fd
, Error
**errp
)
3967 struct kvm_stats_desc
*kvm_stats_desc
;
3968 struct kvm_stats_header
*kvm_stats_header
;
3969 StatsDescriptors
*descriptors
;
3970 struct kvm_stats_desc
*pdesc
;
3971 StatsSchemaValueList
*stats_list
= NULL
;
3975 descriptors
= find_stats_descriptors(target
, stats_fd
, errp
);
3980 kvm_stats_header
= &descriptors
->kvm_stats_header
;
3981 kvm_stats_desc
= descriptors
->kvm_stats_desc
;
3982 size_desc
= sizeof(*kvm_stats_desc
) + kvm_stats_header
->name_size
;
3984 /* Tally the total data size; read schema data */
3985 for (i
= 0; i
< kvm_stats_header
->num_desc
; ++i
) {
3986 pdesc
= (void *)kvm_stats_desc
+ i
* size_desc
;
3987 stats_list
= add_kvmschema_entry(pdesc
, stats_list
, errp
);
3990 add_stats_schema(result
, STATS_PROVIDER_KVM
, target
, stats_list
);
3993 static void query_stats_vcpu(CPUState
*cpu
, run_on_cpu_data data
)
3995 StatsArgs
*kvm_stats_args
= (StatsArgs
*) data
.host_ptr
;
3996 int stats_fd
= kvm_vcpu_ioctl(cpu
, KVM_GET_STATS_FD
, NULL
);
3997 Error
*local_err
= NULL
;
3999 if (stats_fd
== -1) {
4000 error_setg_errno(&local_err
, errno
, "KVM stats: ioctl failed");
4001 error_propagate(kvm_stats_args
->errp
, local_err
);
4004 query_stats(kvm_stats_args
->result
.stats
, STATS_TARGET_VCPU
,
4005 kvm_stats_args
->names
, stats_fd
, kvm_stats_args
->errp
);
4009 static void query_stats_schema_vcpu(CPUState
*cpu
, run_on_cpu_data data
)
4011 StatsArgs
*kvm_stats_args
= (StatsArgs
*) data
.host_ptr
;
4012 int stats_fd
= kvm_vcpu_ioctl(cpu
, KVM_GET_STATS_FD
, NULL
);
4013 Error
*local_err
= NULL
;
4015 if (stats_fd
== -1) {
4016 error_setg_errno(&local_err
, errno
, "KVM stats: ioctl failed");
4017 error_propagate(kvm_stats_args
->errp
, local_err
);
4020 query_stats_schema(kvm_stats_args
->result
.schema
, STATS_TARGET_VCPU
, stats_fd
,
4021 kvm_stats_args
->errp
);
4025 static void query_stats_cb(StatsResultList
**result
, StatsTarget target
,
4026 strList
*names
, strList
*targets
, Error
**errp
)
4028 KVMState
*s
= kvm_state
;
4033 case STATS_TARGET_VM
:
4035 stats_fd
= kvm_vm_ioctl(s
, KVM_GET_STATS_FD
, NULL
);
4036 if (stats_fd
== -1) {
4037 error_setg_errno(errp
, errno
, "KVM stats: ioctl failed");
4040 query_stats(result
, target
, names
, stats_fd
, errp
);
4044 case STATS_TARGET_VCPU
:
4046 StatsArgs stats_args
;
4047 stats_args
.result
.stats
= result
;
4048 stats_args
.names
= names
;
4049 stats_args
.errp
= errp
;
4051 if (!apply_str_list_filter(cpu
->parent_obj
.canonical_path
, targets
)) {
4054 run_on_cpu(cpu
, query_stats_vcpu
, RUN_ON_CPU_HOST_PTR(&stats_args
));
4063 void query_stats_schemas_cb(StatsSchemaList
**result
, Error
**errp
)
4065 StatsArgs stats_args
;
4066 KVMState
*s
= kvm_state
;
4069 stats_fd
= kvm_vm_ioctl(s
, KVM_GET_STATS_FD
, NULL
);
4070 if (stats_fd
== -1) {
4071 error_setg_errno(errp
, errno
, "KVM stats: ioctl failed");
4074 query_stats_schema(result
, STATS_TARGET_VM
, stats_fd
, errp
);
4078 stats_args
.result
.schema
= result
;
4079 stats_args
.errp
= errp
;
4080 run_on_cpu(first_cpu
, query_stats_schema_vcpu
, RUN_ON_CPU_HOST_PTR(&stats_args
));