kvm: dirty-ring: Fix race with vcpu creation
[qemu/kevin.git] / accel / kvm / kvm-all.c
blobcf3a88d90e92b2696674e597f39b9c62bb5db526
1 /*
2 * QEMU KVM support
4 * Copyright IBM, Corp. 2008
5 * Red Hat, Inc. 2008
7 * Authors:
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>
18 #include <poll.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 "sysemu/accel-blocker.h"
35 #include "qemu/bswap.h"
36 #include "exec/memory.h"
37 #include "exec/ram_addr.h"
38 #include "qemu/event_notifier.h"
39 #include "qemu/main-loop.h"
40 #include "trace.h"
41 #include "hw/irq.h"
42 #include "qapi/visitor.h"
43 #include "qapi/qapi-types-common.h"
44 #include "qapi/qapi-visit-common.h"
45 #include "sysemu/reset.h"
46 #include "qemu/guest-random.h"
47 #include "sysemu/hw_accel.h"
48 #include "kvm-cpus.h"
49 #include "sysemu/dirtylimit.h"
50 #include "qemu/range.h"
52 #include "hw/boards.h"
53 #include "sysemu/stats.h"
55 /* This check must be after config-host.h is included */
56 #ifdef CONFIG_EVENTFD
57 #include <sys/eventfd.h>
58 #endif
60 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
61 * need to use the real host PAGE_SIZE, as that's what KVM will use.
63 #ifdef PAGE_SIZE
64 #undef PAGE_SIZE
65 #endif
66 #define PAGE_SIZE qemu_real_host_page_size()
68 #ifndef KVM_GUESTDBG_BLOCKIRQ
69 #define KVM_GUESTDBG_BLOCKIRQ 0
70 #endif
72 //#define DEBUG_KVM
74 #ifdef DEBUG_KVM
75 #define DPRINTF(fmt, ...) \
76 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
77 #else
78 #define DPRINTF(fmt, ...) \
79 do { } while (0)
80 #endif
82 struct KVMParkedVcpu {
83 unsigned long vcpu_id;
84 int kvm_fd;
85 QLIST_ENTRY(KVMParkedVcpu) node;
88 KVMState *kvm_state;
89 bool kvm_kernel_irqchip;
90 bool kvm_split_irqchip;
91 bool kvm_async_interrupts_allowed;
92 bool kvm_halt_in_kernel_allowed;
93 bool kvm_eventfds_allowed;
94 bool kvm_irqfds_allowed;
95 bool kvm_resamplefds_allowed;
96 bool kvm_msi_via_irqfd_allowed;
97 bool kvm_gsi_routing_allowed;
98 bool kvm_gsi_direct_mapping;
99 bool kvm_allowed;
100 bool kvm_readonly_mem_allowed;
101 bool kvm_vm_attributes_allowed;
102 bool kvm_direct_msi_allowed;
103 bool kvm_ioeventfd_any_length_allowed;
104 bool kvm_msi_use_devid;
105 bool kvm_has_guest_debug;
106 static int kvm_sstep_flags;
107 static bool kvm_immediate_exit;
108 static hwaddr kvm_max_slot_size = ~0;
110 static const KVMCapabilityInfo kvm_required_capabilites[] = {
111 KVM_CAP_INFO(USER_MEMORY),
112 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
113 KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS),
114 KVM_CAP_LAST_INFO
117 static NotifierList kvm_irqchip_change_notifiers =
118 NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers);
120 struct KVMResampleFd {
121 int gsi;
122 EventNotifier *resample_event;
123 QLIST_ENTRY(KVMResampleFd) node;
125 typedef struct KVMResampleFd KVMResampleFd;
128 * Only used with split irqchip where we need to do the resample fd
129 * kick for the kernel from userspace.
131 static QLIST_HEAD(, KVMResampleFd) kvm_resample_fd_list =
132 QLIST_HEAD_INITIALIZER(kvm_resample_fd_list);
134 static QemuMutex kml_slots_lock;
136 #define kvm_slots_lock() qemu_mutex_lock(&kml_slots_lock)
137 #define kvm_slots_unlock() qemu_mutex_unlock(&kml_slots_lock)
139 static void kvm_slot_init_dirty_bitmap(KVMSlot *mem);
141 static inline void kvm_resample_fd_remove(int gsi)
143 KVMResampleFd *rfd;
145 QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
146 if (rfd->gsi == gsi) {
147 QLIST_REMOVE(rfd, node);
148 g_free(rfd);
149 break;
154 static inline void kvm_resample_fd_insert(int gsi, EventNotifier *event)
156 KVMResampleFd *rfd = g_new0(KVMResampleFd, 1);
158 rfd->gsi = gsi;
159 rfd->resample_event = event;
161 QLIST_INSERT_HEAD(&kvm_resample_fd_list, rfd, node);
164 void kvm_resample_fd_notify(int gsi)
166 KVMResampleFd *rfd;
168 QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
169 if (rfd->gsi == gsi) {
170 event_notifier_set(rfd->resample_event);
171 trace_kvm_resample_fd_notify(gsi);
172 return;
177 int kvm_get_max_memslots(void)
179 KVMState *s = KVM_STATE(current_accel());
181 return s->nr_slots;
184 /* Called with KVMMemoryListener.slots_lock held */
185 static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
187 KVMState *s = kvm_state;
188 int i;
190 for (i = 0; i < s->nr_slots; i++) {
191 if (kml->slots[i].memory_size == 0) {
192 return &kml->slots[i];
196 return NULL;
199 bool kvm_has_free_slot(MachineState *ms)
201 KVMState *s = KVM_STATE(ms->accelerator);
202 bool result;
203 KVMMemoryListener *kml = &s->memory_listener;
205 kvm_slots_lock();
206 result = !!kvm_get_free_slot(kml);
207 kvm_slots_unlock();
209 return result;
212 /* Called with KVMMemoryListener.slots_lock held */
213 static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
215 KVMSlot *slot = kvm_get_free_slot(kml);
217 if (slot) {
218 return slot;
221 fprintf(stderr, "%s: no free slot available\n", __func__);
222 abort();
225 static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
226 hwaddr start_addr,
227 hwaddr size)
229 KVMState *s = kvm_state;
230 int i;
232 for (i = 0; i < s->nr_slots; i++) {
233 KVMSlot *mem = &kml->slots[i];
235 if (start_addr == mem->start_addr && size == mem->memory_size) {
236 return mem;
240 return NULL;
244 * Calculate and align the start address and the size of the section.
245 * Return the size. If the size is 0, the aligned section is empty.
247 static hwaddr kvm_align_section(MemoryRegionSection *section,
248 hwaddr *start)
250 hwaddr size = int128_get64(section->size);
251 hwaddr delta, aligned;
253 /* kvm works in page size chunks, but the function may be called
254 with sub-page size and unaligned start address. Pad the start
255 address to next and truncate size to previous page boundary. */
256 aligned = ROUND_UP(section->offset_within_address_space,
257 qemu_real_host_page_size());
258 delta = aligned - section->offset_within_address_space;
259 *start = aligned;
260 if (delta > size) {
261 return 0;
264 return (size - delta) & qemu_real_host_page_mask();
267 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
268 hwaddr *phys_addr)
270 KVMMemoryListener *kml = &s->memory_listener;
271 int i, ret = 0;
273 kvm_slots_lock();
274 for (i = 0; i < s->nr_slots; i++) {
275 KVMSlot *mem = &kml->slots[i];
277 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
278 *phys_addr = mem->start_addr + (ram - mem->ram);
279 ret = 1;
280 break;
283 kvm_slots_unlock();
285 return ret;
288 static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot, bool new)
290 KVMState *s = kvm_state;
291 struct kvm_userspace_memory_region mem;
292 int ret;
294 mem.slot = slot->slot | (kml->as_id << 16);
295 mem.guest_phys_addr = slot->start_addr;
296 mem.userspace_addr = (unsigned long)slot->ram;
297 mem.flags = slot->flags;
299 if (slot->memory_size && !new && (mem.flags ^ slot->old_flags) & KVM_MEM_READONLY) {
300 /* Set the slot size to 0 before setting the slot to the desired
301 * value. This is needed based on KVM commit 75d61fbc. */
302 mem.memory_size = 0;
303 ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
304 if (ret < 0) {
305 goto err;
308 mem.memory_size = slot->memory_size;
309 ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
310 slot->old_flags = mem.flags;
311 err:
312 trace_kvm_set_user_memory(mem.slot, mem.flags, mem.guest_phys_addr,
313 mem.memory_size, mem.userspace_addr, ret);
314 if (ret < 0) {
315 error_report("%s: KVM_SET_USER_MEMORY_REGION failed, slot=%d,"
316 " start=0x%" PRIx64 ", size=0x%" PRIx64 ": %s",
317 __func__, mem.slot, slot->start_addr,
318 (uint64_t)mem.memory_size, strerror(errno));
320 return ret;
323 static int do_kvm_destroy_vcpu(CPUState *cpu)
325 KVMState *s = kvm_state;
326 long mmap_size;
327 struct KVMParkedVcpu *vcpu = NULL;
328 int ret = 0;
330 DPRINTF("kvm_destroy_vcpu\n");
332 ret = kvm_arch_destroy_vcpu(cpu);
333 if (ret < 0) {
334 goto err;
337 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
338 if (mmap_size < 0) {
339 ret = mmap_size;
340 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
341 goto err;
344 ret = munmap(cpu->kvm_run, mmap_size);
345 if (ret < 0) {
346 goto err;
349 if (cpu->kvm_dirty_gfns) {
350 ret = munmap(cpu->kvm_dirty_gfns, s->kvm_dirty_ring_bytes);
351 if (ret < 0) {
352 goto err;
356 vcpu = g_malloc0(sizeof(*vcpu));
357 vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
358 vcpu->kvm_fd = cpu->kvm_fd;
359 QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
360 err:
361 return ret;
364 void kvm_destroy_vcpu(CPUState *cpu)
366 if (do_kvm_destroy_vcpu(cpu) < 0) {
367 error_report("kvm_destroy_vcpu failed");
368 exit(EXIT_FAILURE);
372 static int kvm_get_vcpu(KVMState *s, unsigned long vcpu_id)
374 struct KVMParkedVcpu *cpu;
376 QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
377 if (cpu->vcpu_id == vcpu_id) {
378 int kvm_fd;
380 QLIST_REMOVE(cpu, node);
381 kvm_fd = cpu->kvm_fd;
382 g_free(cpu);
383 return kvm_fd;
387 return kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)vcpu_id);
390 int kvm_init_vcpu(CPUState *cpu, Error **errp)
392 KVMState *s = kvm_state;
393 long mmap_size;
394 int ret;
396 trace_kvm_init_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
398 ret = kvm_get_vcpu(s, kvm_arch_vcpu_id(cpu));
399 if (ret < 0) {
400 error_setg_errno(errp, -ret, "kvm_init_vcpu: kvm_get_vcpu failed (%lu)",
401 kvm_arch_vcpu_id(cpu));
402 goto err;
405 cpu->kvm_fd = ret;
406 cpu->kvm_state = s;
407 cpu->vcpu_dirty = true;
408 cpu->dirty_pages = 0;
409 cpu->throttle_us_per_full = 0;
411 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
412 if (mmap_size < 0) {
413 ret = mmap_size;
414 error_setg_errno(errp, -mmap_size,
415 "kvm_init_vcpu: KVM_GET_VCPU_MMAP_SIZE failed");
416 goto err;
419 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
420 cpu->kvm_fd, 0);
421 if (cpu->kvm_run == MAP_FAILED) {
422 ret = -errno;
423 error_setg_errno(errp, ret,
424 "kvm_init_vcpu: mmap'ing vcpu state failed (%lu)",
425 kvm_arch_vcpu_id(cpu));
426 goto err;
429 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
430 s->coalesced_mmio_ring =
431 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
434 if (s->kvm_dirty_ring_size) {
435 /* Use MAP_SHARED to share pages with the kernel */
436 cpu->kvm_dirty_gfns = mmap(NULL, s->kvm_dirty_ring_bytes,
437 PROT_READ | PROT_WRITE, MAP_SHARED,
438 cpu->kvm_fd,
439 PAGE_SIZE * KVM_DIRTY_LOG_PAGE_OFFSET);
440 if (cpu->kvm_dirty_gfns == MAP_FAILED) {
441 ret = -errno;
442 DPRINTF("mmap'ing vcpu dirty gfns failed: %d\n", ret);
443 goto err;
447 ret = kvm_arch_init_vcpu(cpu);
448 if (ret < 0) {
449 error_setg_errno(errp, -ret,
450 "kvm_init_vcpu: kvm_arch_init_vcpu failed (%lu)",
451 kvm_arch_vcpu_id(cpu));
453 err:
454 return ret;
458 * dirty pages logging control
461 static int kvm_mem_flags(MemoryRegion *mr)
463 bool readonly = mr->readonly || memory_region_is_romd(mr);
464 int flags = 0;
466 if (memory_region_get_dirty_log_mask(mr) != 0) {
467 flags |= KVM_MEM_LOG_DIRTY_PAGES;
469 if (readonly && kvm_readonly_mem_allowed) {
470 flags |= KVM_MEM_READONLY;
472 return flags;
475 /* Called with KVMMemoryListener.slots_lock held */
476 static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
477 MemoryRegion *mr)
479 mem->flags = kvm_mem_flags(mr);
481 /* If nothing changed effectively, no need to issue ioctl */
482 if (mem->flags == mem->old_flags) {
483 return 0;
486 kvm_slot_init_dirty_bitmap(mem);
487 return kvm_set_user_memory_region(kml, mem, false);
490 static int kvm_section_update_flags(KVMMemoryListener *kml,
491 MemoryRegionSection *section)
493 hwaddr start_addr, size, slot_size;
494 KVMSlot *mem;
495 int ret = 0;
497 size = kvm_align_section(section, &start_addr);
498 if (!size) {
499 return 0;
502 kvm_slots_lock();
504 while (size && !ret) {
505 slot_size = MIN(kvm_max_slot_size, size);
506 mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
507 if (!mem) {
508 /* We don't have a slot if we want to trap every access. */
509 goto out;
512 ret = kvm_slot_update_flags(kml, mem, section->mr);
513 start_addr += slot_size;
514 size -= slot_size;
517 out:
518 kvm_slots_unlock();
519 return ret;
522 static void kvm_log_start(MemoryListener *listener,
523 MemoryRegionSection *section,
524 int old, int new)
526 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
527 int r;
529 if (old != 0) {
530 return;
533 r = kvm_section_update_flags(kml, section);
534 if (r < 0) {
535 abort();
539 static void kvm_log_stop(MemoryListener *listener,
540 MemoryRegionSection *section,
541 int old, int new)
543 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
544 int r;
546 if (new != 0) {
547 return;
550 r = kvm_section_update_flags(kml, section);
551 if (r < 0) {
552 abort();
556 /* get kvm's dirty pages bitmap and update qemu's */
557 static void kvm_slot_sync_dirty_pages(KVMSlot *slot)
559 ram_addr_t start = slot->ram_start_offset;
560 ram_addr_t pages = slot->memory_size / qemu_real_host_page_size();
562 cpu_physical_memory_set_dirty_lebitmap(slot->dirty_bmap, start, pages);
565 static void kvm_slot_reset_dirty_pages(KVMSlot *slot)
567 memset(slot->dirty_bmap, 0, slot->dirty_bmap_size);
570 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
572 /* Allocate the dirty bitmap for a slot */
573 static void kvm_slot_init_dirty_bitmap(KVMSlot *mem)
575 if (!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) || mem->dirty_bmap) {
576 return;
580 * XXX bad kernel interface alert
581 * For dirty bitmap, kernel allocates array of size aligned to
582 * bits-per-long. But for case when the kernel is 64bits and
583 * the userspace is 32bits, userspace can't align to the same
584 * bits-per-long, since sizeof(long) is different between kernel
585 * and user space. This way, userspace will provide buffer which
586 * may be 4 bytes less than the kernel will use, resulting in
587 * userspace memory corruption (which is not detectable by valgrind
588 * too, in most cases).
589 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
590 * a hope that sizeof(long) won't become >8 any time soon.
592 * Note: the granule of kvm dirty log is qemu_real_host_page_size.
593 * And mem->memory_size is aligned to it (otherwise this mem can't
594 * be registered to KVM).
596 hwaddr bitmap_size = ALIGN(mem->memory_size / qemu_real_host_page_size(),
597 /*HOST_LONG_BITS*/ 64) / 8;
598 mem->dirty_bmap = g_malloc0(bitmap_size);
599 mem->dirty_bmap_size = bitmap_size;
603 * Sync dirty bitmap from kernel to KVMSlot.dirty_bmap, return true if
604 * succeeded, false otherwise
606 static bool kvm_slot_get_dirty_log(KVMState *s, KVMSlot *slot)
608 struct kvm_dirty_log d = {};
609 int ret;
611 d.dirty_bitmap = slot->dirty_bmap;
612 d.slot = slot->slot | (slot->as_id << 16);
613 ret = kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d);
615 if (ret == -ENOENT) {
616 /* kernel does not have dirty bitmap in this slot */
617 ret = 0;
619 if (ret) {
620 error_report_once("%s: KVM_GET_DIRTY_LOG failed with %d",
621 __func__, ret);
623 return ret == 0;
626 /* Should be with all slots_lock held for the address spaces. */
627 static void kvm_dirty_ring_mark_page(KVMState *s, uint32_t as_id,
628 uint32_t slot_id, uint64_t offset)
630 KVMMemoryListener *kml;
631 KVMSlot *mem;
633 if (as_id >= s->nr_as) {
634 return;
637 kml = s->as[as_id].ml;
638 mem = &kml->slots[slot_id];
640 if (!mem->memory_size || offset >=
641 (mem->memory_size / qemu_real_host_page_size())) {
642 return;
645 set_bit(offset, mem->dirty_bmap);
648 static bool dirty_gfn_is_dirtied(struct kvm_dirty_gfn *gfn)
651 * Read the flags before the value. Pairs with barrier in
652 * KVM's kvm_dirty_ring_push() function.
654 return qatomic_load_acquire(&gfn->flags) == KVM_DIRTY_GFN_F_DIRTY;
657 static void dirty_gfn_set_collected(struct kvm_dirty_gfn *gfn)
660 * Use a store-release so that the CPU that executes KVM_RESET_DIRTY_RINGS
661 * sees the full content of the ring:
663 * CPU0 CPU1 CPU2
664 * ------------------------------------------------------------------------------
665 * fill gfn0
666 * store-rel flags for gfn0
667 * load-acq flags for gfn0
668 * store-rel RESET for gfn0
669 * ioctl(RESET_RINGS)
670 * load-acq flags for gfn0
671 * check if flags have RESET
673 * The synchronization goes from CPU2 to CPU0 to CPU1.
675 qatomic_store_release(&gfn->flags, KVM_DIRTY_GFN_F_RESET);
679 * Should be with all slots_lock held for the address spaces. It returns the
680 * dirty page we've collected on this dirty ring.
682 static uint32_t kvm_dirty_ring_reap_one(KVMState *s, CPUState *cpu)
684 struct kvm_dirty_gfn *dirty_gfns = cpu->kvm_dirty_gfns, *cur;
685 uint32_t ring_size = s->kvm_dirty_ring_size;
686 uint32_t count = 0, fetch = cpu->kvm_fetch_index;
689 * It's possible that we race with vcpu creation code where the vcpu is
690 * put onto the vcpus list but not yet initialized the dirty ring
691 * structures. If so, skip it.
693 if (!cpu->created) {
694 return 0;
697 assert(dirty_gfns && ring_size);
698 trace_kvm_dirty_ring_reap_vcpu(cpu->cpu_index);
700 while (true) {
701 cur = &dirty_gfns[fetch % ring_size];
702 if (!dirty_gfn_is_dirtied(cur)) {
703 break;
705 kvm_dirty_ring_mark_page(s, cur->slot >> 16, cur->slot & 0xffff,
706 cur->offset);
707 dirty_gfn_set_collected(cur);
708 trace_kvm_dirty_ring_page(cpu->cpu_index, fetch, cur->offset);
709 fetch++;
710 count++;
712 cpu->kvm_fetch_index = fetch;
713 cpu->dirty_pages += count;
715 return count;
718 /* Must be with slots_lock held */
719 static uint64_t kvm_dirty_ring_reap_locked(KVMState *s, CPUState* cpu)
721 int ret;
722 uint64_t total = 0;
723 int64_t stamp;
725 stamp = get_clock();
727 if (cpu) {
728 total = kvm_dirty_ring_reap_one(s, cpu);
729 } else {
730 CPU_FOREACH(cpu) {
731 total += kvm_dirty_ring_reap_one(s, cpu);
735 if (total) {
736 ret = kvm_vm_ioctl(s, KVM_RESET_DIRTY_RINGS);
737 assert(ret == total);
740 stamp = get_clock() - stamp;
742 if (total) {
743 trace_kvm_dirty_ring_reap(total, stamp / 1000);
746 return total;
750 * Currently for simplicity, we must hold BQL before calling this. We can
751 * consider to drop the BQL if we're clear with all the race conditions.
753 static uint64_t kvm_dirty_ring_reap(KVMState *s, CPUState *cpu)
755 uint64_t total;
758 * We need to lock all kvm slots for all address spaces here,
759 * because:
761 * (1) We need to mark dirty for dirty bitmaps in multiple slots
762 * and for tons of pages, so it's better to take the lock here
763 * once rather than once per page. And more importantly,
765 * (2) We must _NOT_ publish dirty bits to the other threads
766 * (e.g., the migration thread) via the kvm memory slot dirty
767 * bitmaps before correctly re-protect those dirtied pages.
768 * Otherwise we can have potential risk of data corruption if
769 * the page data is read in the other thread before we do
770 * reset below.
772 kvm_slots_lock();
773 total = kvm_dirty_ring_reap_locked(s, cpu);
774 kvm_slots_unlock();
776 return total;
779 static void do_kvm_cpu_synchronize_kick(CPUState *cpu, run_on_cpu_data arg)
781 /* No need to do anything */
785 * Kick all vcpus out in a synchronized way. When returned, we
786 * guarantee that every vcpu has been kicked and at least returned to
787 * userspace once.
789 static void kvm_cpu_synchronize_kick_all(void)
791 CPUState *cpu;
793 CPU_FOREACH(cpu) {
794 run_on_cpu(cpu, do_kvm_cpu_synchronize_kick, RUN_ON_CPU_NULL);
799 * Flush all the existing dirty pages to the KVM slot buffers. When
800 * this call returns, we guarantee that all the touched dirty pages
801 * before calling this function have been put into the per-kvmslot
802 * dirty bitmap.
804 * This function must be called with BQL held.
806 static void kvm_dirty_ring_flush(void)
808 trace_kvm_dirty_ring_flush(0);
810 * The function needs to be serialized. Since this function
811 * should always be with BQL held, serialization is guaranteed.
812 * However, let's be sure of it.
814 assert(qemu_mutex_iothread_locked());
816 * First make sure to flush the hardware buffers by kicking all
817 * vcpus out in a synchronous way.
819 kvm_cpu_synchronize_kick_all();
820 kvm_dirty_ring_reap(kvm_state, NULL);
821 trace_kvm_dirty_ring_flush(1);
825 * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
827 * This function will first try to fetch dirty bitmap from the kernel,
828 * and then updates qemu's dirty bitmap.
830 * NOTE: caller must be with kml->slots_lock held.
832 * @kml: the KVM memory listener object
833 * @section: the memory section to sync the dirty bitmap with
835 static void kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
836 MemoryRegionSection *section)
838 KVMState *s = kvm_state;
839 KVMSlot *mem;
840 hwaddr start_addr, size;
841 hwaddr slot_size;
843 size = kvm_align_section(section, &start_addr);
844 while (size) {
845 slot_size = MIN(kvm_max_slot_size, size);
846 mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
847 if (!mem) {
848 /* We don't have a slot if we want to trap every access. */
849 return;
851 if (kvm_slot_get_dirty_log(s, mem)) {
852 kvm_slot_sync_dirty_pages(mem);
854 start_addr += slot_size;
855 size -= slot_size;
859 /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
860 #define KVM_CLEAR_LOG_SHIFT 6
861 #define KVM_CLEAR_LOG_ALIGN (qemu_real_host_page_size() << KVM_CLEAR_LOG_SHIFT)
862 #define KVM_CLEAR_LOG_MASK (-KVM_CLEAR_LOG_ALIGN)
864 static int kvm_log_clear_one_slot(KVMSlot *mem, int as_id, uint64_t start,
865 uint64_t size)
867 KVMState *s = kvm_state;
868 uint64_t end, bmap_start, start_delta, bmap_npages;
869 struct kvm_clear_dirty_log d;
870 unsigned long *bmap_clear = NULL, psize = qemu_real_host_page_size();
871 int ret;
874 * We need to extend either the start or the size or both to
875 * satisfy the KVM interface requirement. Firstly, do the start
876 * page alignment on 64 host pages
878 bmap_start = start & KVM_CLEAR_LOG_MASK;
879 start_delta = start - bmap_start;
880 bmap_start /= psize;
883 * The kernel interface has restriction on the size too, that either:
885 * (1) the size is 64 host pages aligned (just like the start), or
886 * (2) the size fills up until the end of the KVM memslot.
888 bmap_npages = DIV_ROUND_UP(size + start_delta, KVM_CLEAR_LOG_ALIGN)
889 << KVM_CLEAR_LOG_SHIFT;
890 end = mem->memory_size / psize;
891 if (bmap_npages > end - bmap_start) {
892 bmap_npages = end - bmap_start;
894 start_delta /= psize;
897 * Prepare the bitmap to clear dirty bits. Here we must guarantee
898 * that we won't clear any unknown dirty bits otherwise we might
899 * accidentally clear some set bits which are not yet synced from
900 * the kernel into QEMU's bitmap, then we'll lose track of the
901 * guest modifications upon those pages (which can directly lead
902 * to guest data loss or panic after migration).
904 * Layout of the KVMSlot.dirty_bmap:
906 * |<-------- bmap_npages -----------..>|
907 * [1]
908 * start_delta size
909 * |----------------|-------------|------------------|------------|
910 * ^ ^ ^ ^
911 * | | | |
912 * start bmap_start (start) end
913 * of memslot of memslot
915 * [1] bmap_npages can be aligned to either 64 pages or the end of slot
918 assert(bmap_start % BITS_PER_LONG == 0);
919 /* We should never do log_clear before log_sync */
920 assert(mem->dirty_bmap);
921 if (start_delta || bmap_npages - size / psize) {
922 /* Slow path - we need to manipulate a temp bitmap */
923 bmap_clear = bitmap_new(bmap_npages);
924 bitmap_copy_with_src_offset(bmap_clear, mem->dirty_bmap,
925 bmap_start, start_delta + size / psize);
927 * We need to fill the holes at start because that was not
928 * specified by the caller and we extended the bitmap only for
929 * 64 pages alignment
931 bitmap_clear(bmap_clear, 0, start_delta);
932 d.dirty_bitmap = bmap_clear;
933 } else {
935 * Fast path - both start and size align well with BITS_PER_LONG
936 * (or the end of memory slot)
938 d.dirty_bitmap = mem->dirty_bmap + BIT_WORD(bmap_start);
941 d.first_page = bmap_start;
942 /* It should never overflow. If it happens, say something */
943 assert(bmap_npages <= UINT32_MAX);
944 d.num_pages = bmap_npages;
945 d.slot = mem->slot | (as_id << 16);
947 ret = kvm_vm_ioctl(s, KVM_CLEAR_DIRTY_LOG, &d);
948 if (ret < 0 && ret != -ENOENT) {
949 error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
950 "start=0x%"PRIx64", size=0x%"PRIx32", errno=%d",
951 __func__, d.slot, (uint64_t)d.first_page,
952 (uint32_t)d.num_pages, ret);
953 } else {
954 ret = 0;
955 trace_kvm_clear_dirty_log(d.slot, d.first_page, d.num_pages);
959 * After we have updated the remote dirty bitmap, we update the
960 * cached bitmap as well for the memslot, then if another user
961 * clears the same region we know we shouldn't clear it again on
962 * the remote otherwise it's data loss as well.
964 bitmap_clear(mem->dirty_bmap, bmap_start + start_delta,
965 size / psize);
966 /* This handles the NULL case well */
967 g_free(bmap_clear);
968 return ret;
973 * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
975 * NOTE: this will be a no-op if we haven't enabled manual dirty log
976 * protection in the host kernel because in that case this operation
977 * will be done within log_sync().
979 * @kml: the kvm memory listener
980 * @section: the memory range to clear dirty bitmap
982 static int kvm_physical_log_clear(KVMMemoryListener *kml,
983 MemoryRegionSection *section)
985 KVMState *s = kvm_state;
986 uint64_t start, size, offset, count;
987 KVMSlot *mem;
988 int ret = 0, i;
990 if (!s->manual_dirty_log_protect) {
991 /* No need to do explicit clear */
992 return ret;
995 start = section->offset_within_address_space;
996 size = int128_get64(section->size);
998 if (!size) {
999 /* Nothing more we can do... */
1000 return ret;
1003 kvm_slots_lock();
1005 for (i = 0; i < s->nr_slots; i++) {
1006 mem = &kml->slots[i];
1007 /* Discard slots that are empty or do not overlap the section */
1008 if (!mem->memory_size ||
1009 mem->start_addr > start + size - 1 ||
1010 start > mem->start_addr + mem->memory_size - 1) {
1011 continue;
1014 if (start >= mem->start_addr) {
1015 /* The slot starts before section or is aligned to it. */
1016 offset = start - mem->start_addr;
1017 count = MIN(mem->memory_size - offset, size);
1018 } else {
1019 /* The slot starts after section. */
1020 offset = 0;
1021 count = MIN(mem->memory_size, size - (mem->start_addr - start));
1023 ret = kvm_log_clear_one_slot(mem, kml->as_id, offset, count);
1024 if (ret < 0) {
1025 break;
1029 kvm_slots_unlock();
1031 return ret;
1034 static void kvm_coalesce_mmio_region(MemoryListener *listener,
1035 MemoryRegionSection *secion,
1036 hwaddr start, hwaddr size)
1038 KVMState *s = kvm_state;
1040 if (s->coalesced_mmio) {
1041 struct kvm_coalesced_mmio_zone zone;
1043 zone.addr = start;
1044 zone.size = size;
1045 zone.pad = 0;
1047 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
1051 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
1052 MemoryRegionSection *secion,
1053 hwaddr start, hwaddr size)
1055 KVMState *s = kvm_state;
1057 if (s->coalesced_mmio) {
1058 struct kvm_coalesced_mmio_zone zone;
1060 zone.addr = start;
1061 zone.size = size;
1062 zone.pad = 0;
1064 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
1068 static void kvm_coalesce_pio_add(MemoryListener *listener,
1069 MemoryRegionSection *section,
1070 hwaddr start, hwaddr size)
1072 KVMState *s = kvm_state;
1074 if (s->coalesced_pio) {
1075 struct kvm_coalesced_mmio_zone zone;
1077 zone.addr = start;
1078 zone.size = size;
1079 zone.pio = 1;
1081 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
1085 static void kvm_coalesce_pio_del(MemoryListener *listener,
1086 MemoryRegionSection *section,
1087 hwaddr start, hwaddr size)
1089 KVMState *s = kvm_state;
1091 if (s->coalesced_pio) {
1092 struct kvm_coalesced_mmio_zone zone;
1094 zone.addr = start;
1095 zone.size = size;
1096 zone.pio = 1;
1098 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
1102 static MemoryListener kvm_coalesced_pio_listener = {
1103 .name = "kvm-coalesced-pio",
1104 .coalesced_io_add = kvm_coalesce_pio_add,
1105 .coalesced_io_del = kvm_coalesce_pio_del,
1108 int kvm_check_extension(KVMState *s, unsigned int extension)
1110 int ret;
1112 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
1113 if (ret < 0) {
1114 ret = 0;
1117 return ret;
1120 int kvm_vm_check_extension(KVMState *s, unsigned int extension)
1122 int ret;
1124 ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
1125 if (ret < 0) {
1126 /* VM wide version not implemented, use global one instead */
1127 ret = kvm_check_extension(s, extension);
1130 return ret;
1133 typedef struct HWPoisonPage {
1134 ram_addr_t ram_addr;
1135 QLIST_ENTRY(HWPoisonPage) list;
1136 } HWPoisonPage;
1138 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
1139 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
1141 static void kvm_unpoison_all(void *param)
1143 HWPoisonPage *page, *next_page;
1145 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
1146 QLIST_REMOVE(page, list);
1147 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
1148 g_free(page);
1152 void kvm_hwpoison_page_add(ram_addr_t ram_addr)
1154 HWPoisonPage *page;
1156 QLIST_FOREACH(page, &hwpoison_page_list, list) {
1157 if (page->ram_addr == ram_addr) {
1158 return;
1161 page = g_new(HWPoisonPage, 1);
1162 page->ram_addr = ram_addr;
1163 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
1166 static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
1168 #if HOST_BIG_ENDIAN != TARGET_BIG_ENDIAN
1169 /* The kernel expects ioeventfd values in HOST_BIG_ENDIAN
1170 * endianness, but the memory core hands them in target endianness.
1171 * For example, PPC is always treated as big-endian even if running
1172 * on KVM and on PPC64LE. Correct here.
1174 switch (size) {
1175 case 2:
1176 val = bswap16(val);
1177 break;
1178 case 4:
1179 val = bswap32(val);
1180 break;
1182 #endif
1183 return val;
1186 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
1187 bool assign, uint32_t size, bool datamatch)
1189 int ret;
1190 struct kvm_ioeventfd iofd = {
1191 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
1192 .addr = addr,
1193 .len = size,
1194 .flags = 0,
1195 .fd = fd,
1198 trace_kvm_set_ioeventfd_mmio(fd, (uint64_t)addr, val, assign, size,
1199 datamatch);
1200 if (!kvm_enabled()) {
1201 return -ENOSYS;
1204 if (datamatch) {
1205 iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
1207 if (!assign) {
1208 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1211 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
1213 if (ret < 0) {
1214 return -errno;
1217 return 0;
1220 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
1221 bool assign, uint32_t size, bool datamatch)
1223 struct kvm_ioeventfd kick = {
1224 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
1225 .addr = addr,
1226 .flags = KVM_IOEVENTFD_FLAG_PIO,
1227 .len = size,
1228 .fd = fd,
1230 int r;
1231 trace_kvm_set_ioeventfd_pio(fd, addr, val, assign, size, datamatch);
1232 if (!kvm_enabled()) {
1233 return -ENOSYS;
1235 if (datamatch) {
1236 kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
1238 if (!assign) {
1239 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1241 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
1242 if (r < 0) {
1243 return r;
1245 return 0;
1249 static int kvm_check_many_ioeventfds(void)
1251 /* Userspace can use ioeventfd for io notification. This requires a host
1252 * that supports eventfd(2) and an I/O thread; since eventfd does not
1253 * support SIGIO it cannot interrupt the vcpu.
1255 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
1256 * can avoid creating too many ioeventfds.
1258 #if defined(CONFIG_EVENTFD)
1259 int ioeventfds[7];
1260 int i, ret = 0;
1261 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
1262 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
1263 if (ioeventfds[i] < 0) {
1264 break;
1266 ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
1267 if (ret < 0) {
1268 close(ioeventfds[i]);
1269 break;
1273 /* Decide whether many devices are supported or not */
1274 ret = i == ARRAY_SIZE(ioeventfds);
1276 while (i-- > 0) {
1277 kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
1278 close(ioeventfds[i]);
1280 return ret;
1281 #else
1282 return 0;
1283 #endif
1286 static const KVMCapabilityInfo *
1287 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
1289 while (list->name) {
1290 if (!kvm_check_extension(s, list->value)) {
1291 return list;
1293 list++;
1295 return NULL;
1298 void kvm_set_max_memslot_size(hwaddr max_slot_size)
1300 g_assert(
1301 ROUND_UP(max_slot_size, qemu_real_host_page_size()) == max_slot_size
1303 kvm_max_slot_size = max_slot_size;
1306 /* Called with KVMMemoryListener.slots_lock held */
1307 static void kvm_set_phys_mem(KVMMemoryListener *kml,
1308 MemoryRegionSection *section, bool add)
1310 KVMSlot *mem;
1311 int err;
1312 MemoryRegion *mr = section->mr;
1313 bool writable = !mr->readonly && !mr->rom_device;
1314 hwaddr start_addr, size, slot_size, mr_offset;
1315 ram_addr_t ram_start_offset;
1316 void *ram;
1318 if (!memory_region_is_ram(mr)) {
1319 if (writable || !kvm_readonly_mem_allowed) {
1320 return;
1321 } else if (!mr->romd_mode) {
1322 /* If the memory device is not in romd_mode, then we actually want
1323 * to remove the kvm memory slot so all accesses will trap. */
1324 add = false;
1328 size = kvm_align_section(section, &start_addr);
1329 if (!size) {
1330 return;
1333 /* The offset of the kvmslot within the memory region */
1334 mr_offset = section->offset_within_region + start_addr -
1335 section->offset_within_address_space;
1337 /* use aligned delta to align the ram address and offset */
1338 ram = memory_region_get_ram_ptr(mr) + mr_offset;
1339 ram_start_offset = memory_region_get_ram_addr(mr) + mr_offset;
1341 if (!add) {
1342 do {
1343 slot_size = MIN(kvm_max_slot_size, size);
1344 mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
1345 if (!mem) {
1346 return;
1348 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1350 * NOTE: We should be aware of the fact that here we're only
1351 * doing a best effort to sync dirty bits. No matter whether
1352 * we're using dirty log or dirty ring, we ignored two facts:
1354 * (1) dirty bits can reside in hardware buffers (PML)
1356 * (2) after we collected dirty bits here, pages can be dirtied
1357 * again before we do the final KVM_SET_USER_MEMORY_REGION to
1358 * remove the slot.
1360 * Not easy. Let's cross the fingers until it's fixed.
1362 if (kvm_state->kvm_dirty_ring_size) {
1363 kvm_dirty_ring_reap_locked(kvm_state, NULL);
1364 } else {
1365 kvm_slot_get_dirty_log(kvm_state, mem);
1367 kvm_slot_sync_dirty_pages(mem);
1370 /* unregister the slot */
1371 g_free(mem->dirty_bmap);
1372 mem->dirty_bmap = NULL;
1373 mem->memory_size = 0;
1374 mem->flags = 0;
1375 err = kvm_set_user_memory_region(kml, mem, false);
1376 if (err) {
1377 fprintf(stderr, "%s: error unregistering slot: %s\n",
1378 __func__, strerror(-err));
1379 abort();
1381 start_addr += slot_size;
1382 size -= slot_size;
1383 } while (size);
1384 return;
1387 /* register the new slot */
1388 do {
1389 slot_size = MIN(kvm_max_slot_size, size);
1390 mem = kvm_alloc_slot(kml);
1391 mem->as_id = kml->as_id;
1392 mem->memory_size = slot_size;
1393 mem->start_addr = start_addr;
1394 mem->ram_start_offset = ram_start_offset;
1395 mem->ram = ram;
1396 mem->flags = kvm_mem_flags(mr);
1397 kvm_slot_init_dirty_bitmap(mem);
1398 err = kvm_set_user_memory_region(kml, mem, true);
1399 if (err) {
1400 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
1401 strerror(-err));
1402 abort();
1404 start_addr += slot_size;
1405 ram_start_offset += slot_size;
1406 ram += slot_size;
1407 size -= slot_size;
1408 } while (size);
1411 static void *kvm_dirty_ring_reaper_thread(void *data)
1413 KVMState *s = data;
1414 struct KVMDirtyRingReaper *r = &s->reaper;
1416 rcu_register_thread();
1418 trace_kvm_dirty_ring_reaper("init");
1420 while (true) {
1421 r->reaper_state = KVM_DIRTY_RING_REAPER_WAIT;
1422 trace_kvm_dirty_ring_reaper("wait");
1424 * TODO: provide a smarter timeout rather than a constant?
1426 sleep(1);
1428 /* keep sleeping so that dirtylimit not be interfered by reaper */
1429 if (dirtylimit_in_service()) {
1430 continue;
1433 trace_kvm_dirty_ring_reaper("wakeup");
1434 r->reaper_state = KVM_DIRTY_RING_REAPER_REAPING;
1436 qemu_mutex_lock_iothread();
1437 kvm_dirty_ring_reap(s, NULL);
1438 qemu_mutex_unlock_iothread();
1440 r->reaper_iteration++;
1443 trace_kvm_dirty_ring_reaper("exit");
1445 rcu_unregister_thread();
1447 return NULL;
1450 static int kvm_dirty_ring_reaper_init(KVMState *s)
1452 struct KVMDirtyRingReaper *r = &s->reaper;
1454 qemu_thread_create(&r->reaper_thr, "kvm-reaper",
1455 kvm_dirty_ring_reaper_thread,
1456 s, QEMU_THREAD_JOINABLE);
1458 return 0;
1461 static void kvm_region_add(MemoryListener *listener,
1462 MemoryRegionSection *section)
1464 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1465 KVMMemoryUpdate *update;
1467 update = g_new0(KVMMemoryUpdate, 1);
1468 update->section = *section;
1470 QSIMPLEQ_INSERT_TAIL(&kml->transaction_add, update, next);
1473 static void kvm_region_del(MemoryListener *listener,
1474 MemoryRegionSection *section)
1476 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1477 KVMMemoryUpdate *update;
1479 update = g_new0(KVMMemoryUpdate, 1);
1480 update->section = *section;
1482 QSIMPLEQ_INSERT_TAIL(&kml->transaction_del, update, next);
1485 static void kvm_region_commit(MemoryListener *listener)
1487 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener,
1488 listener);
1489 KVMMemoryUpdate *u1, *u2;
1490 bool need_inhibit = false;
1492 if (QSIMPLEQ_EMPTY(&kml->transaction_add) &&
1493 QSIMPLEQ_EMPTY(&kml->transaction_del)) {
1494 return;
1498 * We have to be careful when regions to add overlap with ranges to remove.
1499 * We have to simulate atomic KVM memslot updates by making sure no ioctl()
1500 * is currently active.
1502 * The lists are order by addresses, so it's easy to find overlaps.
1504 u1 = QSIMPLEQ_FIRST(&kml->transaction_del);
1505 u2 = QSIMPLEQ_FIRST(&kml->transaction_add);
1506 while (u1 && u2) {
1507 Range r1, r2;
1509 range_init_nofail(&r1, u1->section.offset_within_address_space,
1510 int128_get64(u1->section.size));
1511 range_init_nofail(&r2, u2->section.offset_within_address_space,
1512 int128_get64(u2->section.size));
1514 if (range_overlaps_range(&r1, &r2)) {
1515 need_inhibit = true;
1516 break;
1518 if (range_lob(&r1) < range_lob(&r2)) {
1519 u1 = QSIMPLEQ_NEXT(u1, next);
1520 } else {
1521 u2 = QSIMPLEQ_NEXT(u2, next);
1525 kvm_slots_lock();
1526 if (need_inhibit) {
1527 accel_ioctl_inhibit_begin();
1530 /* Remove all memslots before adding the new ones. */
1531 while (!QSIMPLEQ_EMPTY(&kml->transaction_del)) {
1532 u1 = QSIMPLEQ_FIRST(&kml->transaction_del);
1533 QSIMPLEQ_REMOVE_HEAD(&kml->transaction_del, next);
1535 kvm_set_phys_mem(kml, &u1->section, false);
1536 memory_region_unref(u1->section.mr);
1538 g_free(u1);
1540 while (!QSIMPLEQ_EMPTY(&kml->transaction_add)) {
1541 u1 = QSIMPLEQ_FIRST(&kml->transaction_add);
1542 QSIMPLEQ_REMOVE_HEAD(&kml->transaction_add, next);
1544 memory_region_ref(u1->section.mr);
1545 kvm_set_phys_mem(kml, &u1->section, true);
1547 g_free(u1);
1550 if (need_inhibit) {
1551 accel_ioctl_inhibit_end();
1553 kvm_slots_unlock();
1556 static void kvm_log_sync(MemoryListener *listener,
1557 MemoryRegionSection *section)
1559 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1561 kvm_slots_lock();
1562 kvm_physical_sync_dirty_bitmap(kml, section);
1563 kvm_slots_unlock();
1566 static void kvm_log_sync_global(MemoryListener *l)
1568 KVMMemoryListener *kml = container_of(l, KVMMemoryListener, listener);
1569 KVMState *s = kvm_state;
1570 KVMSlot *mem;
1571 int i;
1573 /* Flush all kernel dirty addresses into KVMSlot dirty bitmap */
1574 kvm_dirty_ring_flush();
1577 * TODO: make this faster when nr_slots is big while there are
1578 * only a few used slots (small VMs).
1580 kvm_slots_lock();
1581 for (i = 0; i < s->nr_slots; i++) {
1582 mem = &kml->slots[i];
1583 if (mem->memory_size && mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1584 kvm_slot_sync_dirty_pages(mem);
1586 * This is not needed by KVM_GET_DIRTY_LOG because the
1587 * ioctl will unconditionally overwrite the whole region.
1588 * However kvm dirty ring has no such side effect.
1590 kvm_slot_reset_dirty_pages(mem);
1593 kvm_slots_unlock();
1596 static void kvm_log_clear(MemoryListener *listener,
1597 MemoryRegionSection *section)
1599 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1600 int r;
1602 r = kvm_physical_log_clear(kml, section);
1603 if (r < 0) {
1604 error_report_once("%s: kvm log clear failed: mr=%s "
1605 "offset=%"HWADDR_PRIx" size=%"PRIx64, __func__,
1606 section->mr->name, section->offset_within_region,
1607 int128_get64(section->size));
1608 abort();
1612 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
1613 MemoryRegionSection *section,
1614 bool match_data, uint64_t data,
1615 EventNotifier *e)
1617 int fd = event_notifier_get_fd(e);
1618 int r;
1620 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
1621 data, true, int128_get64(section->size),
1622 match_data);
1623 if (r < 0) {
1624 fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1625 __func__, strerror(-r), -r);
1626 abort();
1630 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
1631 MemoryRegionSection *section,
1632 bool match_data, uint64_t data,
1633 EventNotifier *e)
1635 int fd = event_notifier_get_fd(e);
1636 int r;
1638 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
1639 data, false, int128_get64(section->size),
1640 match_data);
1641 if (r < 0) {
1642 fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1643 __func__, strerror(-r), -r);
1644 abort();
1648 static void kvm_io_ioeventfd_add(MemoryListener *listener,
1649 MemoryRegionSection *section,
1650 bool match_data, uint64_t data,
1651 EventNotifier *e)
1653 int fd = event_notifier_get_fd(e);
1654 int r;
1656 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
1657 data, true, int128_get64(section->size),
1658 match_data);
1659 if (r < 0) {
1660 fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1661 __func__, strerror(-r), -r);
1662 abort();
1666 static void kvm_io_ioeventfd_del(MemoryListener *listener,
1667 MemoryRegionSection *section,
1668 bool match_data, uint64_t data,
1669 EventNotifier *e)
1672 int fd = event_notifier_get_fd(e);
1673 int r;
1675 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
1676 data, false, int128_get64(section->size),
1677 match_data);
1678 if (r < 0) {
1679 fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1680 __func__, strerror(-r), -r);
1681 abort();
1685 void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
1686 AddressSpace *as, int as_id, const char *name)
1688 int i;
1690 kml->slots = g_new0(KVMSlot, s->nr_slots);
1691 kml->as_id = as_id;
1693 for (i = 0; i < s->nr_slots; i++) {
1694 kml->slots[i].slot = i;
1697 QSIMPLEQ_INIT(&kml->transaction_add);
1698 QSIMPLEQ_INIT(&kml->transaction_del);
1700 kml->listener.region_add = kvm_region_add;
1701 kml->listener.region_del = kvm_region_del;
1702 kml->listener.commit = kvm_region_commit;
1703 kml->listener.log_start = kvm_log_start;
1704 kml->listener.log_stop = kvm_log_stop;
1705 kml->listener.priority = 10;
1706 kml->listener.name = name;
1708 if (s->kvm_dirty_ring_size) {
1709 kml->listener.log_sync_global = kvm_log_sync_global;
1710 } else {
1711 kml->listener.log_sync = kvm_log_sync;
1712 kml->listener.log_clear = kvm_log_clear;
1715 memory_listener_register(&kml->listener, as);
1717 for (i = 0; i < s->nr_as; ++i) {
1718 if (!s->as[i].as) {
1719 s->as[i].as = as;
1720 s->as[i].ml = kml;
1721 break;
1726 static MemoryListener kvm_io_listener = {
1727 .name = "kvm-io",
1728 .eventfd_add = kvm_io_ioeventfd_add,
1729 .eventfd_del = kvm_io_ioeventfd_del,
1730 .priority = 10,
1733 int kvm_set_irq(KVMState *s, int irq, int level)
1735 struct kvm_irq_level event;
1736 int ret;
1738 assert(kvm_async_interrupts_enabled());
1740 event.level = level;
1741 event.irq = irq;
1742 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
1743 if (ret < 0) {
1744 perror("kvm_set_irq");
1745 abort();
1748 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
1751 #ifdef KVM_CAP_IRQ_ROUTING
1752 typedef struct KVMMSIRoute {
1753 struct kvm_irq_routing_entry kroute;
1754 QTAILQ_ENTRY(KVMMSIRoute) entry;
1755 } KVMMSIRoute;
1757 static void set_gsi(KVMState *s, unsigned int gsi)
1759 set_bit(gsi, s->used_gsi_bitmap);
1762 static void clear_gsi(KVMState *s, unsigned int gsi)
1764 clear_bit(gsi, s->used_gsi_bitmap);
1767 void kvm_init_irq_routing(KVMState *s)
1769 int gsi_count, i;
1771 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
1772 if (gsi_count > 0) {
1773 /* Round up so we can search ints using ffs */
1774 s->used_gsi_bitmap = bitmap_new(gsi_count);
1775 s->gsi_count = gsi_count;
1778 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
1779 s->nr_allocated_irq_routes = 0;
1781 if (!kvm_direct_msi_allowed) {
1782 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
1783 QTAILQ_INIT(&s->msi_hashtab[i]);
1787 kvm_arch_init_irq_routing(s);
1790 void kvm_irqchip_commit_routes(KVMState *s)
1792 int ret;
1794 if (kvm_gsi_direct_mapping()) {
1795 return;
1798 if (!kvm_gsi_routing_enabled()) {
1799 return;
1802 s->irq_routes->flags = 0;
1803 trace_kvm_irqchip_commit_routes();
1804 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1805 assert(ret == 0);
1808 static void kvm_add_routing_entry(KVMState *s,
1809 struct kvm_irq_routing_entry *entry)
1811 struct kvm_irq_routing_entry *new;
1812 int n, size;
1814 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1815 n = s->nr_allocated_irq_routes * 2;
1816 if (n < 64) {
1817 n = 64;
1819 size = sizeof(struct kvm_irq_routing);
1820 size += n * sizeof(*new);
1821 s->irq_routes = g_realloc(s->irq_routes, size);
1822 s->nr_allocated_irq_routes = n;
1824 n = s->irq_routes->nr++;
1825 new = &s->irq_routes->entries[n];
1827 *new = *entry;
1829 set_gsi(s, entry->gsi);
1832 static int kvm_update_routing_entry(KVMState *s,
1833 struct kvm_irq_routing_entry *new_entry)
1835 struct kvm_irq_routing_entry *entry;
1836 int n;
1838 for (n = 0; n < s->irq_routes->nr; n++) {
1839 entry = &s->irq_routes->entries[n];
1840 if (entry->gsi != new_entry->gsi) {
1841 continue;
1844 if(!memcmp(entry, new_entry, sizeof *entry)) {
1845 return 0;
1848 *entry = *new_entry;
1850 return 0;
1853 return -ESRCH;
1856 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1858 struct kvm_irq_routing_entry e = {};
1860 assert(pin < s->gsi_count);
1862 e.gsi = irq;
1863 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1864 e.flags = 0;
1865 e.u.irqchip.irqchip = irqchip;
1866 e.u.irqchip.pin = pin;
1867 kvm_add_routing_entry(s, &e);
1870 void kvm_irqchip_release_virq(KVMState *s, int virq)
1872 struct kvm_irq_routing_entry *e;
1873 int i;
1875 if (kvm_gsi_direct_mapping()) {
1876 return;
1879 for (i = 0; i < s->irq_routes->nr; i++) {
1880 e = &s->irq_routes->entries[i];
1881 if (e->gsi == virq) {
1882 s->irq_routes->nr--;
1883 *e = s->irq_routes->entries[s->irq_routes->nr];
1886 clear_gsi(s, virq);
1887 kvm_arch_release_virq_post(virq);
1888 trace_kvm_irqchip_release_virq(virq);
1891 void kvm_irqchip_add_change_notifier(Notifier *n)
1893 notifier_list_add(&kvm_irqchip_change_notifiers, n);
1896 void kvm_irqchip_remove_change_notifier(Notifier *n)
1898 notifier_remove(n);
1901 void kvm_irqchip_change_notify(void)
1903 notifier_list_notify(&kvm_irqchip_change_notifiers, NULL);
1906 static unsigned int kvm_hash_msi(uint32_t data)
1908 /* This is optimized for IA32 MSI layout. However, no other arch shall
1909 * repeat the mistake of not providing a direct MSI injection API. */
1910 return data & 0xff;
1913 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1915 KVMMSIRoute *route, *next;
1916 unsigned int hash;
1918 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1919 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1920 kvm_irqchip_release_virq(s, route->kroute.gsi);
1921 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1922 g_free(route);
1927 static int kvm_irqchip_get_virq(KVMState *s)
1929 int next_virq;
1932 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1933 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1934 * number can succeed even though a new route entry cannot be added.
1935 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1937 if (!kvm_direct_msi_allowed && s->irq_routes->nr == s->gsi_count) {
1938 kvm_flush_dynamic_msi_routes(s);
1941 /* Return the lowest unused GSI in the bitmap */
1942 next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
1943 if (next_virq >= s->gsi_count) {
1944 return -ENOSPC;
1945 } else {
1946 return next_virq;
1950 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1952 unsigned int hash = kvm_hash_msi(msg.data);
1953 KVMMSIRoute *route;
1955 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1956 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1957 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1958 route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1959 return route;
1962 return NULL;
1965 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1967 struct kvm_msi msi;
1968 KVMMSIRoute *route;
1970 if (kvm_direct_msi_allowed) {
1971 msi.address_lo = (uint32_t)msg.address;
1972 msi.address_hi = msg.address >> 32;
1973 msi.data = le32_to_cpu(msg.data);
1974 msi.flags = 0;
1975 memset(msi.pad, 0, sizeof(msi.pad));
1977 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1980 route = kvm_lookup_msi_route(s, msg);
1981 if (!route) {
1982 int virq;
1984 virq = kvm_irqchip_get_virq(s);
1985 if (virq < 0) {
1986 return virq;
1989 route = g_new0(KVMMSIRoute, 1);
1990 route->kroute.gsi = virq;
1991 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1992 route->kroute.flags = 0;
1993 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1994 route->kroute.u.msi.address_hi = msg.address >> 32;
1995 route->kroute.u.msi.data = le32_to_cpu(msg.data);
1997 kvm_add_routing_entry(s, &route->kroute);
1998 kvm_irqchip_commit_routes(s);
2000 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
2001 entry);
2004 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
2006 return kvm_set_irq(s, route->kroute.gsi, 1);
2009 int kvm_irqchip_add_msi_route(KVMRouteChange *c, int vector, PCIDevice *dev)
2011 struct kvm_irq_routing_entry kroute = {};
2012 int virq;
2013 KVMState *s = c->s;
2014 MSIMessage msg = {0, 0};
2016 if (pci_available && dev) {
2017 msg = pci_get_msi_message(dev, vector);
2020 if (kvm_gsi_direct_mapping()) {
2021 return kvm_arch_msi_data_to_gsi(msg.data);
2024 if (!kvm_gsi_routing_enabled()) {
2025 return -ENOSYS;
2028 virq = kvm_irqchip_get_virq(s);
2029 if (virq < 0) {
2030 return virq;
2033 kroute.gsi = virq;
2034 kroute.type = KVM_IRQ_ROUTING_MSI;
2035 kroute.flags = 0;
2036 kroute.u.msi.address_lo = (uint32_t)msg.address;
2037 kroute.u.msi.address_hi = msg.address >> 32;
2038 kroute.u.msi.data = le32_to_cpu(msg.data);
2039 if (pci_available && kvm_msi_devid_required()) {
2040 kroute.flags = KVM_MSI_VALID_DEVID;
2041 kroute.u.msi.devid = pci_requester_id(dev);
2043 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
2044 kvm_irqchip_release_virq(s, virq);
2045 return -EINVAL;
2048 trace_kvm_irqchip_add_msi_route(dev ? dev->name : (char *)"N/A",
2049 vector, virq);
2051 kvm_add_routing_entry(s, &kroute);
2052 kvm_arch_add_msi_route_post(&kroute, vector, dev);
2053 c->changes++;
2055 return virq;
2058 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
2059 PCIDevice *dev)
2061 struct kvm_irq_routing_entry kroute = {};
2063 if (kvm_gsi_direct_mapping()) {
2064 return 0;
2067 if (!kvm_irqchip_in_kernel()) {
2068 return -ENOSYS;
2071 kroute.gsi = virq;
2072 kroute.type = KVM_IRQ_ROUTING_MSI;
2073 kroute.flags = 0;
2074 kroute.u.msi.address_lo = (uint32_t)msg.address;
2075 kroute.u.msi.address_hi = msg.address >> 32;
2076 kroute.u.msi.data = le32_to_cpu(msg.data);
2077 if (pci_available && kvm_msi_devid_required()) {
2078 kroute.flags = KVM_MSI_VALID_DEVID;
2079 kroute.u.msi.devid = pci_requester_id(dev);
2081 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
2082 return -EINVAL;
2085 trace_kvm_irqchip_update_msi_route(virq);
2087 return kvm_update_routing_entry(s, &kroute);
2090 static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
2091 EventNotifier *resample, int virq,
2092 bool assign)
2094 int fd = event_notifier_get_fd(event);
2095 int rfd = resample ? event_notifier_get_fd(resample) : -1;
2097 struct kvm_irqfd irqfd = {
2098 .fd = fd,
2099 .gsi = virq,
2100 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
2103 if (rfd != -1) {
2104 assert(assign);
2105 if (kvm_irqchip_is_split()) {
2107 * When the slow irqchip (e.g. IOAPIC) is in the
2108 * userspace, KVM kernel resamplefd will not work because
2109 * the EOI of the interrupt will be delivered to userspace
2110 * instead, so the KVM kernel resamplefd kick will be
2111 * skipped. The userspace here mimics what the kernel
2112 * provides with resamplefd, remember the resamplefd and
2113 * kick it when we receive EOI of this IRQ.
2115 * This is hackery because IOAPIC is mostly bypassed
2116 * (except EOI broadcasts) when irqfd is used. However
2117 * this can bring much performance back for split irqchip
2118 * with INTx IRQs (for VFIO, this gives 93% perf of the
2119 * full fast path, which is 46% perf boost comparing to
2120 * the INTx slow path).
2122 kvm_resample_fd_insert(virq, resample);
2123 } else {
2124 irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
2125 irqfd.resamplefd = rfd;
2127 } else if (!assign) {
2128 if (kvm_irqchip_is_split()) {
2129 kvm_resample_fd_remove(virq);
2133 if (!kvm_irqfds_enabled()) {
2134 return -ENOSYS;
2137 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
2140 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
2142 struct kvm_irq_routing_entry kroute = {};
2143 int virq;
2145 if (!kvm_gsi_routing_enabled()) {
2146 return -ENOSYS;
2149 virq = kvm_irqchip_get_virq(s);
2150 if (virq < 0) {
2151 return virq;
2154 kroute.gsi = virq;
2155 kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
2156 kroute.flags = 0;
2157 kroute.u.adapter.summary_addr = adapter->summary_addr;
2158 kroute.u.adapter.ind_addr = adapter->ind_addr;
2159 kroute.u.adapter.summary_offset = adapter->summary_offset;
2160 kroute.u.adapter.ind_offset = adapter->ind_offset;
2161 kroute.u.adapter.adapter_id = adapter->adapter_id;
2163 kvm_add_routing_entry(s, &kroute);
2165 return virq;
2168 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
2170 struct kvm_irq_routing_entry kroute = {};
2171 int virq;
2173 if (!kvm_gsi_routing_enabled()) {
2174 return -ENOSYS;
2176 if (!kvm_check_extension(s, KVM_CAP_HYPERV_SYNIC)) {
2177 return -ENOSYS;
2179 virq = kvm_irqchip_get_virq(s);
2180 if (virq < 0) {
2181 return virq;
2184 kroute.gsi = virq;
2185 kroute.type = KVM_IRQ_ROUTING_HV_SINT;
2186 kroute.flags = 0;
2187 kroute.u.hv_sint.vcpu = vcpu;
2188 kroute.u.hv_sint.sint = sint;
2190 kvm_add_routing_entry(s, &kroute);
2191 kvm_irqchip_commit_routes(s);
2193 return virq;
2196 #else /* !KVM_CAP_IRQ_ROUTING */
2198 void kvm_init_irq_routing(KVMState *s)
2202 void kvm_irqchip_release_virq(KVMState *s, int virq)
2206 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
2208 abort();
2211 int kvm_irqchip_add_msi_route(KVMRouteChange *c, int vector, PCIDevice *dev)
2213 return -ENOSYS;
2216 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
2218 return -ENOSYS;
2221 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
2223 return -ENOSYS;
2226 static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
2227 EventNotifier *resample, int virq,
2228 bool assign)
2230 abort();
2233 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
2235 return -ENOSYS;
2237 #endif /* !KVM_CAP_IRQ_ROUTING */
2239 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
2240 EventNotifier *rn, int virq)
2242 return kvm_irqchip_assign_irqfd(s, n, rn, virq, true);
2245 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
2246 int virq)
2248 return kvm_irqchip_assign_irqfd(s, n, NULL, virq, false);
2251 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
2252 EventNotifier *rn, qemu_irq irq)
2254 gpointer key, gsi;
2255 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
2257 if (!found) {
2258 return -ENXIO;
2260 return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
2263 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
2264 qemu_irq irq)
2266 gpointer key, gsi;
2267 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
2269 if (!found) {
2270 return -ENXIO;
2272 return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
2275 void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
2277 g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
2280 static void kvm_irqchip_create(KVMState *s)
2282 int ret;
2284 assert(s->kernel_irqchip_split != ON_OFF_AUTO_AUTO);
2285 if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
2287 } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
2288 ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
2289 if (ret < 0) {
2290 fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
2291 exit(1);
2293 } else {
2294 return;
2297 /* First probe and see if there's a arch-specific hook to create the
2298 * in-kernel irqchip for us */
2299 ret = kvm_arch_irqchip_create(s);
2300 if (ret == 0) {
2301 if (s->kernel_irqchip_split == ON_OFF_AUTO_ON) {
2302 error_report("Split IRQ chip mode not supported.");
2303 exit(1);
2304 } else {
2305 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
2308 if (ret < 0) {
2309 fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
2310 exit(1);
2313 kvm_kernel_irqchip = true;
2314 /* If we have an in-kernel IRQ chip then we must have asynchronous
2315 * interrupt delivery (though the reverse is not necessarily true)
2317 kvm_async_interrupts_allowed = true;
2318 kvm_halt_in_kernel_allowed = true;
2320 kvm_init_irq_routing(s);
2322 s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
2325 /* Find number of supported CPUs using the recommended
2326 * procedure from the kernel API documentation to cope with
2327 * older kernels that may be missing capabilities.
2329 static int kvm_recommended_vcpus(KVMState *s)
2331 int ret = kvm_vm_check_extension(s, KVM_CAP_NR_VCPUS);
2332 return (ret) ? ret : 4;
2335 static int kvm_max_vcpus(KVMState *s)
2337 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
2338 return (ret) ? ret : kvm_recommended_vcpus(s);
2341 static int kvm_max_vcpu_id(KVMState *s)
2343 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
2344 return (ret) ? ret : kvm_max_vcpus(s);
2347 bool kvm_vcpu_id_is_valid(int vcpu_id)
2349 KVMState *s = KVM_STATE(current_accel());
2350 return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
2353 bool kvm_dirty_ring_enabled(void)
2355 return kvm_state->kvm_dirty_ring_size ? true : false;
2358 static void query_stats_cb(StatsResultList **result, StatsTarget target,
2359 strList *names, strList *targets, Error **errp);
2360 static void query_stats_schemas_cb(StatsSchemaList **result, Error **errp);
2362 uint32_t kvm_dirty_ring_size(void)
2364 return kvm_state->kvm_dirty_ring_size;
2367 static int kvm_init(MachineState *ms)
2369 MachineClass *mc = MACHINE_GET_CLASS(ms);
2370 static const char upgrade_note[] =
2371 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
2372 "(see http://sourceforge.net/projects/kvm).\n";
2373 const struct {
2374 const char *name;
2375 int num;
2376 } num_cpus[] = {
2377 { "SMP", ms->smp.cpus },
2378 { "hotpluggable", ms->smp.max_cpus },
2379 { /* end of list */ }
2380 }, *nc = num_cpus;
2381 int soft_vcpus_limit, hard_vcpus_limit;
2382 KVMState *s;
2383 const KVMCapabilityInfo *missing_cap;
2384 int ret;
2385 int type = 0;
2386 uint64_t dirty_log_manual_caps;
2388 qemu_mutex_init(&kml_slots_lock);
2390 s = KVM_STATE(ms->accelerator);
2393 * On systems where the kernel can support different base page
2394 * sizes, host page size may be different from TARGET_PAGE_SIZE,
2395 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
2396 * page size for the system though.
2398 assert(TARGET_PAGE_SIZE <= qemu_real_host_page_size());
2400 s->sigmask_len = 8;
2401 accel_blocker_init();
2403 #ifdef KVM_CAP_SET_GUEST_DEBUG
2404 QTAILQ_INIT(&s->kvm_sw_breakpoints);
2405 #endif
2406 QLIST_INIT(&s->kvm_parked_vcpus);
2407 s->fd = qemu_open_old("/dev/kvm", O_RDWR);
2408 if (s->fd == -1) {
2409 fprintf(stderr, "Could not access KVM kernel module: %m\n");
2410 ret = -errno;
2411 goto err;
2414 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
2415 if (ret < KVM_API_VERSION) {
2416 if (ret >= 0) {
2417 ret = -EINVAL;
2419 fprintf(stderr, "kvm version too old\n");
2420 goto err;
2423 if (ret > KVM_API_VERSION) {
2424 ret = -EINVAL;
2425 fprintf(stderr, "kvm version not supported\n");
2426 goto err;
2429 kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
2430 s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
2432 /* If unspecified, use the default value */
2433 if (!s->nr_slots) {
2434 s->nr_slots = 32;
2437 s->nr_as = kvm_check_extension(s, KVM_CAP_MULTI_ADDRESS_SPACE);
2438 if (s->nr_as <= 1) {
2439 s->nr_as = 1;
2441 s->as = g_new0(struct KVMAs, s->nr_as);
2443 if (object_property_find(OBJECT(current_machine), "kvm-type")) {
2444 g_autofree char *kvm_type = object_property_get_str(OBJECT(current_machine),
2445 "kvm-type",
2446 &error_abort);
2447 type = mc->kvm_type(ms, kvm_type);
2448 } else if (mc->kvm_type) {
2449 type = mc->kvm_type(ms, NULL);
2452 do {
2453 ret = kvm_ioctl(s, KVM_CREATE_VM, type);
2454 } while (ret == -EINTR);
2456 if (ret < 0) {
2457 fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
2458 strerror(-ret));
2460 #ifdef TARGET_S390X
2461 if (ret == -EINVAL) {
2462 fprintf(stderr,
2463 "Host kernel setup problem detected. Please verify:\n");
2464 fprintf(stderr, "- for kernels supporting the switch_amode or"
2465 " user_mode parameters, whether\n");
2466 fprintf(stderr,
2467 " user space is running in primary address space\n");
2468 fprintf(stderr,
2469 "- for kernels supporting the vm.allocate_pgste sysctl, "
2470 "whether it is enabled\n");
2472 #elif defined(TARGET_PPC)
2473 if (ret == -EINVAL) {
2474 fprintf(stderr,
2475 "PPC KVM module is not loaded. Try modprobe kvm_%s.\n",
2476 (type == 2) ? "pr" : "hv");
2478 #endif
2479 goto err;
2482 s->vmfd = ret;
2484 /* check the vcpu limits */
2485 soft_vcpus_limit = kvm_recommended_vcpus(s);
2486 hard_vcpus_limit = kvm_max_vcpus(s);
2488 while (nc->name) {
2489 if (nc->num > soft_vcpus_limit) {
2490 warn_report("Number of %s cpus requested (%d) exceeds "
2491 "the recommended cpus supported by KVM (%d)",
2492 nc->name, nc->num, soft_vcpus_limit);
2494 if (nc->num > hard_vcpus_limit) {
2495 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
2496 "the maximum cpus supported by KVM (%d)\n",
2497 nc->name, nc->num, hard_vcpus_limit);
2498 exit(1);
2501 nc++;
2504 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
2505 if (!missing_cap) {
2506 missing_cap =
2507 kvm_check_extension_list(s, kvm_arch_required_capabilities);
2509 if (missing_cap) {
2510 ret = -EINVAL;
2511 fprintf(stderr, "kvm does not support %s\n%s",
2512 missing_cap->name, upgrade_note);
2513 goto err;
2516 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
2517 s->coalesced_pio = s->coalesced_mmio &&
2518 kvm_check_extension(s, KVM_CAP_COALESCED_PIO);
2521 * Enable KVM dirty ring if supported, otherwise fall back to
2522 * dirty logging mode
2524 if (s->kvm_dirty_ring_size > 0) {
2525 uint64_t ring_bytes;
2527 ring_bytes = s->kvm_dirty_ring_size * sizeof(struct kvm_dirty_gfn);
2529 /* Read the max supported pages */
2530 ret = kvm_vm_check_extension(s, KVM_CAP_DIRTY_LOG_RING);
2531 if (ret > 0) {
2532 if (ring_bytes > ret) {
2533 error_report("KVM dirty ring size %" PRIu32 " too big "
2534 "(maximum is %ld). Please use a smaller value.",
2535 s->kvm_dirty_ring_size,
2536 (long)ret / sizeof(struct kvm_dirty_gfn));
2537 ret = -EINVAL;
2538 goto err;
2541 ret = kvm_vm_enable_cap(s, KVM_CAP_DIRTY_LOG_RING, 0, ring_bytes);
2542 if (ret) {
2543 error_report("Enabling of KVM dirty ring failed: %s. "
2544 "Suggested minimum value is 1024.", strerror(-ret));
2545 goto err;
2548 s->kvm_dirty_ring_bytes = ring_bytes;
2549 } else {
2550 warn_report("KVM dirty ring not available, using bitmap method");
2551 s->kvm_dirty_ring_size = 0;
2556 * KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is not needed when dirty ring is
2557 * enabled. More importantly, KVM_DIRTY_LOG_INITIALLY_SET will assume no
2558 * page is wr-protected initially, which is against how kvm dirty ring is
2559 * usage - kvm dirty ring requires all pages are wr-protected at the very
2560 * beginning. Enabling this feature for dirty ring causes data corruption.
2562 * TODO: Without KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 and kvm clear dirty log,
2563 * we may expect a higher stall time when starting the migration. In the
2564 * future we can enable KVM_CLEAR_DIRTY_LOG to work with dirty ring too:
2565 * instead of clearing dirty bit, it can be a way to explicitly wr-protect
2566 * guest pages.
2568 if (!s->kvm_dirty_ring_size) {
2569 dirty_log_manual_caps =
2570 kvm_check_extension(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
2571 dirty_log_manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
2572 KVM_DIRTY_LOG_INITIALLY_SET);
2573 s->manual_dirty_log_protect = dirty_log_manual_caps;
2574 if (dirty_log_manual_caps) {
2575 ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0,
2576 dirty_log_manual_caps);
2577 if (ret) {
2578 warn_report("Trying to enable capability %"PRIu64" of "
2579 "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
2580 "Falling back to the legacy mode. ",
2581 dirty_log_manual_caps);
2582 s->manual_dirty_log_protect = 0;
2587 #ifdef KVM_CAP_VCPU_EVENTS
2588 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
2589 #endif
2591 s->robust_singlestep =
2592 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
2594 #ifdef KVM_CAP_DEBUGREGS
2595 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
2596 #endif
2598 s->max_nested_state_len = kvm_check_extension(s, KVM_CAP_NESTED_STATE);
2600 #ifdef KVM_CAP_IRQ_ROUTING
2601 kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
2602 #endif
2604 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
2606 s->irq_set_ioctl = KVM_IRQ_LINE;
2607 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
2608 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
2611 kvm_readonly_mem_allowed =
2612 (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
2614 kvm_eventfds_allowed =
2615 (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
2617 kvm_irqfds_allowed =
2618 (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
2620 kvm_resamplefds_allowed =
2621 (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
2623 kvm_vm_attributes_allowed =
2624 (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
2626 kvm_ioeventfd_any_length_allowed =
2627 (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
2629 #ifdef KVM_CAP_SET_GUEST_DEBUG
2630 kvm_has_guest_debug =
2631 (kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG) > 0);
2632 #endif
2634 kvm_sstep_flags = 0;
2635 if (kvm_has_guest_debug) {
2636 kvm_sstep_flags = SSTEP_ENABLE;
2638 #if defined KVM_CAP_SET_GUEST_DEBUG2
2639 int guest_debug_flags =
2640 kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG2);
2642 if (guest_debug_flags & KVM_GUESTDBG_BLOCKIRQ) {
2643 kvm_sstep_flags |= SSTEP_NOIRQ;
2645 #endif
2648 kvm_state = s;
2650 ret = kvm_arch_init(ms, s);
2651 if (ret < 0) {
2652 goto err;
2655 if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
2656 s->kernel_irqchip_split = mc->default_kernel_irqchip_split ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
2659 qemu_register_reset(kvm_unpoison_all, NULL);
2661 if (s->kernel_irqchip_allowed) {
2662 kvm_irqchip_create(s);
2665 if (kvm_eventfds_allowed) {
2666 s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
2667 s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
2669 s->memory_listener.listener.coalesced_io_add = kvm_coalesce_mmio_region;
2670 s->memory_listener.listener.coalesced_io_del = kvm_uncoalesce_mmio_region;
2672 kvm_memory_listener_register(s, &s->memory_listener,
2673 &address_space_memory, 0, "kvm-memory");
2674 if (kvm_eventfds_allowed) {
2675 memory_listener_register(&kvm_io_listener,
2676 &address_space_io);
2678 memory_listener_register(&kvm_coalesced_pio_listener,
2679 &address_space_io);
2681 s->many_ioeventfds = kvm_check_many_ioeventfds();
2683 s->sync_mmu = !!kvm_vm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2684 if (!s->sync_mmu) {
2685 ret = ram_block_discard_disable(true);
2686 assert(!ret);
2689 if (s->kvm_dirty_ring_size) {
2690 ret = kvm_dirty_ring_reaper_init(s);
2691 if (ret) {
2692 goto err;
2696 if (kvm_check_extension(kvm_state, KVM_CAP_BINARY_STATS_FD)) {
2697 add_stats_callbacks(STATS_PROVIDER_KVM, query_stats_cb,
2698 query_stats_schemas_cb);
2701 return 0;
2703 err:
2704 assert(ret < 0);
2705 if (s->vmfd >= 0) {
2706 close(s->vmfd);
2708 if (s->fd != -1) {
2709 close(s->fd);
2711 g_free(s->memory_listener.slots);
2713 return ret;
2716 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
2718 s->sigmask_len = sigmask_len;
2721 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
2722 int size, uint32_t count)
2724 int i;
2725 uint8_t *ptr = data;
2727 for (i = 0; i < count; i++) {
2728 address_space_rw(&address_space_io, port, attrs,
2729 ptr, size,
2730 direction == KVM_EXIT_IO_OUT);
2731 ptr += size;
2735 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
2737 fprintf(stderr, "KVM internal error. Suberror: %d\n",
2738 run->internal.suberror);
2740 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
2741 int i;
2743 for (i = 0; i < run->internal.ndata; ++i) {
2744 fprintf(stderr, "extra data[%d]: 0x%016"PRIx64"\n",
2745 i, (uint64_t)run->internal.data[i]);
2748 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
2749 fprintf(stderr, "emulation failure\n");
2750 if (!kvm_arch_stop_on_emulation_error(cpu)) {
2751 cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2752 return EXCP_INTERRUPT;
2755 /* FIXME: Should trigger a qmp message to let management know
2756 * something went wrong.
2758 return -1;
2761 void kvm_flush_coalesced_mmio_buffer(void)
2763 KVMState *s = kvm_state;
2765 if (s->coalesced_flush_in_progress) {
2766 return;
2769 s->coalesced_flush_in_progress = true;
2771 if (s->coalesced_mmio_ring) {
2772 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
2773 while (ring->first != ring->last) {
2774 struct kvm_coalesced_mmio *ent;
2776 ent = &ring->coalesced_mmio[ring->first];
2778 if (ent->pio == 1) {
2779 address_space_write(&address_space_io, ent->phys_addr,
2780 MEMTXATTRS_UNSPECIFIED, ent->data,
2781 ent->len);
2782 } else {
2783 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
2785 smp_wmb();
2786 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
2790 s->coalesced_flush_in_progress = false;
2793 bool kvm_cpu_check_are_resettable(void)
2795 return kvm_arch_cpu_check_are_resettable();
2798 static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
2800 if (!cpu->vcpu_dirty) {
2801 kvm_arch_get_registers(cpu);
2802 cpu->vcpu_dirty = true;
2806 void kvm_cpu_synchronize_state(CPUState *cpu)
2808 if (!cpu->vcpu_dirty) {
2809 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
2813 static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
2815 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
2816 cpu->vcpu_dirty = false;
2819 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
2821 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
2824 static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
2826 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
2827 cpu->vcpu_dirty = false;
2830 void kvm_cpu_synchronize_post_init(CPUState *cpu)
2832 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
2835 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
2837 cpu->vcpu_dirty = true;
2840 void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
2842 run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
2845 #ifdef KVM_HAVE_MCE_INJECTION
2846 static __thread void *pending_sigbus_addr;
2847 static __thread int pending_sigbus_code;
2848 static __thread bool have_sigbus_pending;
2849 #endif
2851 static void kvm_cpu_kick(CPUState *cpu)
2853 qatomic_set(&cpu->kvm_run->immediate_exit, 1);
2856 static void kvm_cpu_kick_self(void)
2858 if (kvm_immediate_exit) {
2859 kvm_cpu_kick(current_cpu);
2860 } else {
2861 qemu_cpu_kick_self();
2865 static void kvm_eat_signals(CPUState *cpu)
2867 struct timespec ts = { 0, 0 };
2868 siginfo_t siginfo;
2869 sigset_t waitset;
2870 sigset_t chkset;
2871 int r;
2873 if (kvm_immediate_exit) {
2874 qatomic_set(&cpu->kvm_run->immediate_exit, 0);
2875 /* Write kvm_run->immediate_exit before the cpu->exit_request
2876 * write in kvm_cpu_exec.
2878 smp_wmb();
2879 return;
2882 sigemptyset(&waitset);
2883 sigaddset(&waitset, SIG_IPI);
2885 do {
2886 r = sigtimedwait(&waitset, &siginfo, &ts);
2887 if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
2888 perror("sigtimedwait");
2889 exit(1);
2892 r = sigpending(&chkset);
2893 if (r == -1) {
2894 perror("sigpending");
2895 exit(1);
2897 } while (sigismember(&chkset, SIG_IPI));
2900 int kvm_cpu_exec(CPUState *cpu)
2902 struct kvm_run *run = cpu->kvm_run;
2903 int ret, run_ret;
2905 DPRINTF("kvm_cpu_exec()\n");
2907 if (kvm_arch_process_async_events(cpu)) {
2908 qatomic_set(&cpu->exit_request, 0);
2909 return EXCP_HLT;
2912 qemu_mutex_unlock_iothread();
2913 cpu_exec_start(cpu);
2915 do {
2916 MemTxAttrs attrs;
2918 if (cpu->vcpu_dirty) {
2919 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
2920 cpu->vcpu_dirty = false;
2923 kvm_arch_pre_run(cpu, run);
2924 if (qatomic_read(&cpu->exit_request)) {
2925 DPRINTF("interrupt exit requested\n");
2927 * KVM requires us to reenter the kernel after IO exits to complete
2928 * instruction emulation. This self-signal will ensure that we
2929 * leave ASAP again.
2931 kvm_cpu_kick_self();
2934 /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2935 * Matching barrier in kvm_eat_signals.
2937 smp_rmb();
2939 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
2941 attrs = kvm_arch_post_run(cpu, run);
2943 #ifdef KVM_HAVE_MCE_INJECTION
2944 if (unlikely(have_sigbus_pending)) {
2945 qemu_mutex_lock_iothread();
2946 kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
2947 pending_sigbus_addr);
2948 have_sigbus_pending = false;
2949 qemu_mutex_unlock_iothread();
2951 #endif
2953 if (run_ret < 0) {
2954 if (run_ret == -EINTR || run_ret == -EAGAIN) {
2955 DPRINTF("io window exit\n");
2956 kvm_eat_signals(cpu);
2957 ret = EXCP_INTERRUPT;
2958 break;
2960 fprintf(stderr, "error: kvm run failed %s\n",
2961 strerror(-run_ret));
2962 #ifdef TARGET_PPC
2963 if (run_ret == -EBUSY) {
2964 fprintf(stderr,
2965 "This is probably because your SMT is enabled.\n"
2966 "VCPU can only run on primary threads with all "
2967 "secondary threads offline.\n");
2969 #endif
2970 ret = -1;
2971 break;
2974 trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
2975 switch (run->exit_reason) {
2976 case KVM_EXIT_IO:
2977 DPRINTF("handle_io\n");
2978 /* Called outside BQL */
2979 kvm_handle_io(run->io.port, attrs,
2980 (uint8_t *)run + run->io.data_offset,
2981 run->io.direction,
2982 run->io.size,
2983 run->io.count);
2984 ret = 0;
2985 break;
2986 case KVM_EXIT_MMIO:
2987 DPRINTF("handle_mmio\n");
2988 /* Called outside BQL */
2989 address_space_rw(&address_space_memory,
2990 run->mmio.phys_addr, attrs,
2991 run->mmio.data,
2992 run->mmio.len,
2993 run->mmio.is_write);
2994 ret = 0;
2995 break;
2996 case KVM_EXIT_IRQ_WINDOW_OPEN:
2997 DPRINTF("irq_window_open\n");
2998 ret = EXCP_INTERRUPT;
2999 break;
3000 case KVM_EXIT_SHUTDOWN:
3001 DPRINTF("shutdown\n");
3002 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
3003 ret = EXCP_INTERRUPT;
3004 break;
3005 case KVM_EXIT_UNKNOWN:
3006 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
3007 (uint64_t)run->hw.hardware_exit_reason);
3008 ret = -1;
3009 break;
3010 case KVM_EXIT_INTERNAL_ERROR:
3011 ret = kvm_handle_internal_error(cpu, run);
3012 break;
3013 case KVM_EXIT_DIRTY_RING_FULL:
3015 * We shouldn't continue if the dirty ring of this vcpu is
3016 * still full. Got kicked by KVM_RESET_DIRTY_RINGS.
3018 trace_kvm_dirty_ring_full(cpu->cpu_index);
3019 qemu_mutex_lock_iothread();
3021 * We throttle vCPU by making it sleep once it exit from kernel
3022 * due to dirty ring full. In the dirtylimit scenario, reaping
3023 * all vCPUs after a single vCPU dirty ring get full result in
3024 * the miss of sleep, so just reap the ring-fulled vCPU.
3026 if (dirtylimit_in_service()) {
3027 kvm_dirty_ring_reap(kvm_state, cpu);
3028 } else {
3029 kvm_dirty_ring_reap(kvm_state, NULL);
3031 qemu_mutex_unlock_iothread();
3032 dirtylimit_vcpu_execute(cpu);
3033 ret = 0;
3034 break;
3035 case KVM_EXIT_SYSTEM_EVENT:
3036 switch (run->system_event.type) {
3037 case KVM_SYSTEM_EVENT_SHUTDOWN:
3038 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
3039 ret = EXCP_INTERRUPT;
3040 break;
3041 case KVM_SYSTEM_EVENT_RESET:
3042 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
3043 ret = EXCP_INTERRUPT;
3044 break;
3045 case KVM_SYSTEM_EVENT_CRASH:
3046 kvm_cpu_synchronize_state(cpu);
3047 qemu_mutex_lock_iothread();
3048 qemu_system_guest_panicked(cpu_get_crash_info(cpu));
3049 qemu_mutex_unlock_iothread();
3050 ret = 0;
3051 break;
3052 default:
3053 DPRINTF("kvm_arch_handle_exit\n");
3054 ret = kvm_arch_handle_exit(cpu, run);
3055 break;
3057 break;
3058 default:
3059 DPRINTF("kvm_arch_handle_exit\n");
3060 ret = kvm_arch_handle_exit(cpu, run);
3061 break;
3063 } while (ret == 0);
3065 cpu_exec_end(cpu);
3066 qemu_mutex_lock_iothread();
3068 if (ret < 0) {
3069 cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
3070 vm_stop(RUN_STATE_INTERNAL_ERROR);
3073 qatomic_set(&cpu->exit_request, 0);
3074 return ret;
3077 int kvm_ioctl(KVMState *s, int type, ...)
3079 int ret;
3080 void *arg;
3081 va_list ap;
3083 va_start(ap, type);
3084 arg = va_arg(ap, void *);
3085 va_end(ap);
3087 trace_kvm_ioctl(type, arg);
3088 ret = ioctl(s->fd, type, arg);
3089 if (ret == -1) {
3090 ret = -errno;
3092 return ret;
3095 int kvm_vm_ioctl(KVMState *s, int type, ...)
3097 int ret;
3098 void *arg;
3099 va_list ap;
3101 va_start(ap, type);
3102 arg = va_arg(ap, void *);
3103 va_end(ap);
3105 trace_kvm_vm_ioctl(type, arg);
3106 accel_ioctl_begin();
3107 ret = ioctl(s->vmfd, type, arg);
3108 accel_ioctl_end();
3109 if (ret == -1) {
3110 ret = -errno;
3112 return ret;
3115 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
3117 int ret;
3118 void *arg;
3119 va_list ap;
3121 va_start(ap, type);
3122 arg = va_arg(ap, void *);
3123 va_end(ap);
3125 trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
3126 accel_cpu_ioctl_begin(cpu);
3127 ret = ioctl(cpu->kvm_fd, type, arg);
3128 accel_cpu_ioctl_end(cpu);
3129 if (ret == -1) {
3130 ret = -errno;
3132 return ret;
3135 int kvm_device_ioctl(int fd, int type, ...)
3137 int ret;
3138 void *arg;
3139 va_list ap;
3141 va_start(ap, type);
3142 arg = va_arg(ap, void *);
3143 va_end(ap);
3145 trace_kvm_device_ioctl(fd, type, arg);
3146 accel_ioctl_begin();
3147 ret = ioctl(fd, type, arg);
3148 accel_ioctl_end();
3149 if (ret == -1) {
3150 ret = -errno;
3152 return ret;
3155 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
3157 int ret;
3158 struct kvm_device_attr attribute = {
3159 .group = group,
3160 .attr = attr,
3163 if (!kvm_vm_attributes_allowed) {
3164 return 0;
3167 ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
3168 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
3169 return ret ? 0 : 1;
3172 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
3174 struct kvm_device_attr attribute = {
3175 .group = group,
3176 .attr = attr,
3177 .flags = 0,
3180 return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
3183 int kvm_device_access(int fd, int group, uint64_t attr,
3184 void *val, bool write, Error **errp)
3186 struct kvm_device_attr kvmattr;
3187 int err;
3189 kvmattr.flags = 0;
3190 kvmattr.group = group;
3191 kvmattr.attr = attr;
3192 kvmattr.addr = (uintptr_t)val;
3194 err = kvm_device_ioctl(fd,
3195 write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
3196 &kvmattr);
3197 if (err < 0) {
3198 error_setg_errno(errp, -err,
3199 "KVM_%s_DEVICE_ATTR failed: Group %d "
3200 "attr 0x%016" PRIx64,
3201 write ? "SET" : "GET", group, attr);
3203 return err;
3206 bool kvm_has_sync_mmu(void)
3208 return kvm_state->sync_mmu;
3211 int kvm_has_vcpu_events(void)
3213 return kvm_state->vcpu_events;
3216 int kvm_has_robust_singlestep(void)
3218 return kvm_state->robust_singlestep;
3221 int kvm_has_debugregs(void)
3223 return kvm_state->debugregs;
3226 int kvm_max_nested_state_length(void)
3228 return kvm_state->max_nested_state_len;
3231 int kvm_has_many_ioeventfds(void)
3233 if (!kvm_enabled()) {
3234 return 0;
3236 return kvm_state->many_ioeventfds;
3239 int kvm_has_gsi_routing(void)
3241 #ifdef KVM_CAP_IRQ_ROUTING
3242 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
3243 #else
3244 return false;
3245 #endif
3248 int kvm_has_intx_set_mask(void)
3250 return kvm_state->intx_set_mask;
3253 bool kvm_arm_supports_user_irq(void)
3255 return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
3258 #ifdef KVM_CAP_SET_GUEST_DEBUG
3259 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
3260 target_ulong pc)
3262 struct kvm_sw_breakpoint *bp;
3264 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
3265 if (bp->pc == pc) {
3266 return bp;
3269 return NULL;
3272 int kvm_sw_breakpoints_active(CPUState *cpu)
3274 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
3277 struct kvm_set_guest_debug_data {
3278 struct kvm_guest_debug dbg;
3279 int err;
3282 static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
3284 struct kvm_set_guest_debug_data *dbg_data =
3285 (struct kvm_set_guest_debug_data *) data.host_ptr;
3287 dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
3288 &dbg_data->dbg);
3291 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
3293 struct kvm_set_guest_debug_data data;
3295 data.dbg.control = reinject_trap;
3297 if (cpu->singlestep_enabled) {
3298 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
3300 if (cpu->singlestep_enabled & SSTEP_NOIRQ) {
3301 data.dbg.control |= KVM_GUESTDBG_BLOCKIRQ;
3304 kvm_arch_update_guest_debug(cpu, &data.dbg);
3306 run_on_cpu(cpu, kvm_invoke_set_guest_debug,
3307 RUN_ON_CPU_HOST_PTR(&data));
3308 return data.err;
3311 bool kvm_supports_guest_debug(void)
3313 /* probed during kvm_init() */
3314 return kvm_has_guest_debug;
3317 int kvm_insert_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
3319 struct kvm_sw_breakpoint *bp;
3320 int err;
3322 if (type == GDB_BREAKPOINT_SW) {
3323 bp = kvm_find_sw_breakpoint(cpu, addr);
3324 if (bp) {
3325 bp->use_count++;
3326 return 0;
3329 bp = g_new(struct kvm_sw_breakpoint, 1);
3330 bp->pc = addr;
3331 bp->use_count = 1;
3332 err = kvm_arch_insert_sw_breakpoint(cpu, bp);
3333 if (err) {
3334 g_free(bp);
3335 return err;
3338 QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
3339 } else {
3340 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
3341 if (err) {
3342 return err;
3346 CPU_FOREACH(cpu) {
3347 err = kvm_update_guest_debug(cpu, 0);
3348 if (err) {
3349 return err;
3352 return 0;
3355 int kvm_remove_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
3357 struct kvm_sw_breakpoint *bp;
3358 int err;
3360 if (type == GDB_BREAKPOINT_SW) {
3361 bp = kvm_find_sw_breakpoint(cpu, addr);
3362 if (!bp) {
3363 return -ENOENT;
3366 if (bp->use_count > 1) {
3367 bp->use_count--;
3368 return 0;
3371 err = kvm_arch_remove_sw_breakpoint(cpu, bp);
3372 if (err) {
3373 return err;
3376 QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
3377 g_free(bp);
3378 } else {
3379 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
3380 if (err) {
3381 return err;
3385 CPU_FOREACH(cpu) {
3386 err = kvm_update_guest_debug(cpu, 0);
3387 if (err) {
3388 return err;
3391 return 0;
3394 void kvm_remove_all_breakpoints(CPUState *cpu)
3396 struct kvm_sw_breakpoint *bp, *next;
3397 KVMState *s = cpu->kvm_state;
3398 CPUState *tmpcpu;
3400 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
3401 if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
3402 /* Try harder to find a CPU that currently sees the breakpoint. */
3403 CPU_FOREACH(tmpcpu) {
3404 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
3405 break;
3409 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
3410 g_free(bp);
3412 kvm_arch_remove_all_hw_breakpoints();
3414 CPU_FOREACH(cpu) {
3415 kvm_update_guest_debug(cpu, 0);
3419 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
3421 static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
3423 KVMState *s = kvm_state;
3424 struct kvm_signal_mask *sigmask;
3425 int r;
3427 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
3429 sigmask->len = s->sigmask_len;
3430 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
3431 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
3432 g_free(sigmask);
3434 return r;
3437 static void kvm_ipi_signal(int sig)
3439 if (current_cpu) {
3440 assert(kvm_immediate_exit);
3441 kvm_cpu_kick(current_cpu);
3445 void kvm_init_cpu_signals(CPUState *cpu)
3447 int r;
3448 sigset_t set;
3449 struct sigaction sigact;
3451 memset(&sigact, 0, sizeof(sigact));
3452 sigact.sa_handler = kvm_ipi_signal;
3453 sigaction(SIG_IPI, &sigact, NULL);
3455 pthread_sigmask(SIG_BLOCK, NULL, &set);
3456 #if defined KVM_HAVE_MCE_INJECTION
3457 sigdelset(&set, SIGBUS);
3458 pthread_sigmask(SIG_SETMASK, &set, NULL);
3459 #endif
3460 sigdelset(&set, SIG_IPI);
3461 if (kvm_immediate_exit) {
3462 r = pthread_sigmask(SIG_SETMASK, &set, NULL);
3463 } else {
3464 r = kvm_set_signal_mask(cpu, &set);
3466 if (r) {
3467 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
3468 exit(1);
3472 /* Called asynchronously in VCPU thread. */
3473 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
3475 #ifdef KVM_HAVE_MCE_INJECTION
3476 if (have_sigbus_pending) {
3477 return 1;
3479 have_sigbus_pending = true;
3480 pending_sigbus_addr = addr;
3481 pending_sigbus_code = code;
3482 qatomic_set(&cpu->exit_request, 1);
3483 return 0;
3484 #else
3485 return 1;
3486 #endif
3489 /* Called synchronously (via signalfd) in main thread. */
3490 int kvm_on_sigbus(int code, void *addr)
3492 #ifdef KVM_HAVE_MCE_INJECTION
3493 /* Action required MCE kills the process if SIGBUS is blocked. Because
3494 * that's what happens in the I/O thread, where we handle MCE via signalfd,
3495 * we can only get action optional here.
3497 assert(code != BUS_MCEERR_AR);
3498 kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
3499 return 0;
3500 #else
3501 return 1;
3502 #endif
3505 int kvm_create_device(KVMState *s, uint64_t type, bool test)
3507 int ret;
3508 struct kvm_create_device create_dev;
3510 create_dev.type = type;
3511 create_dev.fd = -1;
3512 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
3514 if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
3515 return -ENOTSUP;
3518 ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
3519 if (ret) {
3520 return ret;
3523 return test ? 0 : create_dev.fd;
3526 bool kvm_device_supported(int vmfd, uint64_t type)
3528 struct kvm_create_device create_dev = {
3529 .type = type,
3530 .fd = -1,
3531 .flags = KVM_CREATE_DEVICE_TEST,
3534 if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
3535 return false;
3538 return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
3541 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
3543 struct kvm_one_reg reg;
3544 int r;
3546 reg.id = id;
3547 reg.addr = (uintptr_t) source;
3548 r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
3549 if (r) {
3550 trace_kvm_failed_reg_set(id, strerror(-r));
3552 return r;
3555 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
3557 struct kvm_one_reg reg;
3558 int r;
3560 reg.id = id;
3561 reg.addr = (uintptr_t) target;
3562 r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
3563 if (r) {
3564 trace_kvm_failed_reg_get(id, strerror(-r));
3566 return r;
3569 static bool kvm_accel_has_memory(MachineState *ms, AddressSpace *as,
3570 hwaddr start_addr, hwaddr size)
3572 KVMState *kvm = KVM_STATE(ms->accelerator);
3573 int i;
3575 for (i = 0; i < kvm->nr_as; ++i) {
3576 if (kvm->as[i].as == as && kvm->as[i].ml) {
3577 size = MIN(kvm_max_slot_size, size);
3578 return NULL != kvm_lookup_matching_slot(kvm->as[i].ml,
3579 start_addr, size);
3583 return false;
3586 static void kvm_get_kvm_shadow_mem(Object *obj, Visitor *v,
3587 const char *name, void *opaque,
3588 Error **errp)
3590 KVMState *s = KVM_STATE(obj);
3591 int64_t value = s->kvm_shadow_mem;
3593 visit_type_int(v, name, &value, errp);
3596 static void kvm_set_kvm_shadow_mem(Object *obj, Visitor *v,
3597 const char *name, void *opaque,
3598 Error **errp)
3600 KVMState *s = KVM_STATE(obj);
3601 int64_t value;
3603 if (s->fd != -1) {
3604 error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3605 return;
3608 if (!visit_type_int(v, name, &value, errp)) {
3609 return;
3612 s->kvm_shadow_mem = value;
3615 static void kvm_set_kernel_irqchip(Object *obj, Visitor *v,
3616 const char *name, void *opaque,
3617 Error **errp)
3619 KVMState *s = KVM_STATE(obj);
3620 OnOffSplit mode;
3622 if (s->fd != -1) {
3623 error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3624 return;
3627 if (!visit_type_OnOffSplit(v, name, &mode, errp)) {
3628 return;
3630 switch (mode) {
3631 case ON_OFF_SPLIT_ON:
3632 s->kernel_irqchip_allowed = true;
3633 s->kernel_irqchip_required = true;
3634 s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3635 break;
3636 case ON_OFF_SPLIT_OFF:
3637 s->kernel_irqchip_allowed = false;
3638 s->kernel_irqchip_required = false;
3639 s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3640 break;
3641 case ON_OFF_SPLIT_SPLIT:
3642 s->kernel_irqchip_allowed = true;
3643 s->kernel_irqchip_required = true;
3644 s->kernel_irqchip_split = ON_OFF_AUTO_ON;
3645 break;
3646 default:
3647 /* The value was checked in visit_type_OnOffSplit() above. If
3648 * we get here, then something is wrong in QEMU.
3650 abort();
3654 bool kvm_kernel_irqchip_allowed(void)
3656 return kvm_state->kernel_irqchip_allowed;
3659 bool kvm_kernel_irqchip_required(void)
3661 return kvm_state->kernel_irqchip_required;
3664 bool kvm_kernel_irqchip_split(void)
3666 return kvm_state->kernel_irqchip_split == ON_OFF_AUTO_ON;
3669 static void kvm_get_dirty_ring_size(Object *obj, Visitor *v,
3670 const char *name, void *opaque,
3671 Error **errp)
3673 KVMState *s = KVM_STATE(obj);
3674 uint32_t value = s->kvm_dirty_ring_size;
3676 visit_type_uint32(v, name, &value, errp);
3679 static void kvm_set_dirty_ring_size(Object *obj, Visitor *v,
3680 const char *name, void *opaque,
3681 Error **errp)
3683 KVMState *s = KVM_STATE(obj);
3684 uint32_t value;
3686 if (s->fd != -1) {
3687 error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3688 return;
3691 if (!visit_type_uint32(v, name, &value, errp)) {
3692 return;
3694 if (value & (value - 1)) {
3695 error_setg(errp, "dirty-ring-size must be a power of two.");
3696 return;
3699 s->kvm_dirty_ring_size = value;
3702 static void kvm_accel_instance_init(Object *obj)
3704 KVMState *s = KVM_STATE(obj);
3706 s->fd = -1;
3707 s->vmfd = -1;
3708 s->kvm_shadow_mem = -1;
3709 s->kernel_irqchip_allowed = true;
3710 s->kernel_irqchip_split = ON_OFF_AUTO_AUTO;
3711 /* KVM dirty ring is by default off */
3712 s->kvm_dirty_ring_size = 0;
3713 s->notify_vmexit = NOTIFY_VMEXIT_OPTION_RUN;
3714 s->notify_window = 0;
3715 s->xen_version = 0;
3716 s->xen_gnttab_max_frames = 64;
3717 s->xen_evtchn_max_pirq = 256;
3721 * kvm_gdbstub_sstep_flags():
3723 * Returns: SSTEP_* flags that KVM supports for guest debug. The
3724 * support is probed during kvm_init()
3726 static int kvm_gdbstub_sstep_flags(void)
3728 return kvm_sstep_flags;
3731 static void kvm_accel_class_init(ObjectClass *oc, void *data)
3733 AccelClass *ac = ACCEL_CLASS(oc);
3734 ac->name = "KVM";
3735 ac->init_machine = kvm_init;
3736 ac->has_memory = kvm_accel_has_memory;
3737 ac->allowed = &kvm_allowed;
3738 ac->gdbstub_supported_sstep_flags = kvm_gdbstub_sstep_flags;
3740 object_class_property_add(oc, "kernel-irqchip", "on|off|split",
3741 NULL, kvm_set_kernel_irqchip,
3742 NULL, NULL);
3743 object_class_property_set_description(oc, "kernel-irqchip",
3744 "Configure KVM in-kernel irqchip");
3746 object_class_property_add(oc, "kvm-shadow-mem", "int",
3747 kvm_get_kvm_shadow_mem, kvm_set_kvm_shadow_mem,
3748 NULL, NULL);
3749 object_class_property_set_description(oc, "kvm-shadow-mem",
3750 "KVM shadow MMU size");
3752 object_class_property_add(oc, "dirty-ring-size", "uint32",
3753 kvm_get_dirty_ring_size, kvm_set_dirty_ring_size,
3754 NULL, NULL);
3755 object_class_property_set_description(oc, "dirty-ring-size",
3756 "Size of KVM dirty page ring buffer (default: 0, i.e. use bitmap)");
3758 kvm_arch_accel_class_init(oc);
3761 static const TypeInfo kvm_accel_type = {
3762 .name = TYPE_KVM_ACCEL,
3763 .parent = TYPE_ACCEL,
3764 .instance_init = kvm_accel_instance_init,
3765 .class_init = kvm_accel_class_init,
3766 .instance_size = sizeof(KVMState),
3769 static void kvm_type_init(void)
3771 type_register_static(&kvm_accel_type);
3774 type_init(kvm_type_init);
3776 typedef struct StatsArgs {
3777 union StatsResultsType {
3778 StatsResultList **stats;
3779 StatsSchemaList **schema;
3780 } result;
3781 strList *names;
3782 Error **errp;
3783 } StatsArgs;
3785 static StatsList *add_kvmstat_entry(struct kvm_stats_desc *pdesc,
3786 uint64_t *stats_data,
3787 StatsList *stats_list,
3788 Error **errp)
3791 Stats *stats;
3792 uint64List *val_list = NULL;
3794 /* Only add stats that we understand. */
3795 switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
3796 case KVM_STATS_TYPE_CUMULATIVE:
3797 case KVM_STATS_TYPE_INSTANT:
3798 case KVM_STATS_TYPE_PEAK:
3799 case KVM_STATS_TYPE_LINEAR_HIST:
3800 case KVM_STATS_TYPE_LOG_HIST:
3801 break;
3802 default:
3803 return stats_list;
3806 switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
3807 case KVM_STATS_UNIT_NONE:
3808 case KVM_STATS_UNIT_BYTES:
3809 case KVM_STATS_UNIT_CYCLES:
3810 case KVM_STATS_UNIT_SECONDS:
3811 case KVM_STATS_UNIT_BOOLEAN:
3812 break;
3813 default:
3814 return stats_list;
3817 switch (pdesc->flags & KVM_STATS_BASE_MASK) {
3818 case KVM_STATS_BASE_POW10:
3819 case KVM_STATS_BASE_POW2:
3820 break;
3821 default:
3822 return stats_list;
3825 /* Alloc and populate data list */
3826 stats = g_new0(Stats, 1);
3827 stats->name = g_strdup(pdesc->name);
3828 stats->value = g_new0(StatsValue, 1);;
3830 if ((pdesc->flags & KVM_STATS_UNIT_MASK) == KVM_STATS_UNIT_BOOLEAN) {
3831 stats->value->u.boolean = *stats_data;
3832 stats->value->type = QTYPE_QBOOL;
3833 } else if (pdesc->size == 1) {
3834 stats->value->u.scalar = *stats_data;
3835 stats->value->type = QTYPE_QNUM;
3836 } else {
3837 int i;
3838 for (i = 0; i < pdesc->size; i++) {
3839 QAPI_LIST_PREPEND(val_list, stats_data[i]);
3841 stats->value->u.list = val_list;
3842 stats->value->type = QTYPE_QLIST;
3845 QAPI_LIST_PREPEND(stats_list, stats);
3846 return stats_list;
3849 static StatsSchemaValueList *add_kvmschema_entry(struct kvm_stats_desc *pdesc,
3850 StatsSchemaValueList *list,
3851 Error **errp)
3853 StatsSchemaValueList *schema_entry = g_new0(StatsSchemaValueList, 1);
3854 schema_entry->value = g_new0(StatsSchemaValue, 1);
3856 switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
3857 case KVM_STATS_TYPE_CUMULATIVE:
3858 schema_entry->value->type = STATS_TYPE_CUMULATIVE;
3859 break;
3860 case KVM_STATS_TYPE_INSTANT:
3861 schema_entry->value->type = STATS_TYPE_INSTANT;
3862 break;
3863 case KVM_STATS_TYPE_PEAK:
3864 schema_entry->value->type = STATS_TYPE_PEAK;
3865 break;
3866 case KVM_STATS_TYPE_LINEAR_HIST:
3867 schema_entry->value->type = STATS_TYPE_LINEAR_HISTOGRAM;
3868 schema_entry->value->bucket_size = pdesc->bucket_size;
3869 schema_entry->value->has_bucket_size = true;
3870 break;
3871 case KVM_STATS_TYPE_LOG_HIST:
3872 schema_entry->value->type = STATS_TYPE_LOG2_HISTOGRAM;
3873 break;
3874 default:
3875 goto exit;
3878 switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
3879 case KVM_STATS_UNIT_NONE:
3880 break;
3881 case KVM_STATS_UNIT_BOOLEAN:
3882 schema_entry->value->has_unit = true;
3883 schema_entry->value->unit = STATS_UNIT_BOOLEAN;
3884 break;
3885 case KVM_STATS_UNIT_BYTES:
3886 schema_entry->value->has_unit = true;
3887 schema_entry->value->unit = STATS_UNIT_BYTES;
3888 break;
3889 case KVM_STATS_UNIT_CYCLES:
3890 schema_entry->value->has_unit = true;
3891 schema_entry->value->unit = STATS_UNIT_CYCLES;
3892 break;
3893 case KVM_STATS_UNIT_SECONDS:
3894 schema_entry->value->has_unit = true;
3895 schema_entry->value->unit = STATS_UNIT_SECONDS;
3896 break;
3897 default:
3898 goto exit;
3901 schema_entry->value->exponent = pdesc->exponent;
3902 if (pdesc->exponent) {
3903 switch (pdesc->flags & KVM_STATS_BASE_MASK) {
3904 case KVM_STATS_BASE_POW10:
3905 schema_entry->value->has_base = true;
3906 schema_entry->value->base = 10;
3907 break;
3908 case KVM_STATS_BASE_POW2:
3909 schema_entry->value->has_base = true;
3910 schema_entry->value->base = 2;
3911 break;
3912 default:
3913 goto exit;
3917 schema_entry->value->name = g_strdup(pdesc->name);
3918 schema_entry->next = list;
3919 return schema_entry;
3920 exit:
3921 g_free(schema_entry->value);
3922 g_free(schema_entry);
3923 return list;
3926 /* Cached stats descriptors */
3927 typedef struct StatsDescriptors {
3928 const char *ident; /* cache key, currently the StatsTarget */
3929 struct kvm_stats_desc *kvm_stats_desc;
3930 struct kvm_stats_header kvm_stats_header;
3931 QTAILQ_ENTRY(StatsDescriptors) next;
3932 } StatsDescriptors;
3934 static QTAILQ_HEAD(, StatsDescriptors) stats_descriptors =
3935 QTAILQ_HEAD_INITIALIZER(stats_descriptors);
3938 * Return the descriptors for 'target', that either have already been read
3939 * or are retrieved from 'stats_fd'.
3941 static StatsDescriptors *find_stats_descriptors(StatsTarget target, int stats_fd,
3942 Error **errp)
3944 StatsDescriptors *descriptors;
3945 const char *ident;
3946 struct kvm_stats_desc *kvm_stats_desc;
3947 struct kvm_stats_header *kvm_stats_header;
3948 size_t size_desc;
3949 ssize_t ret;
3951 ident = StatsTarget_str(target);
3952 QTAILQ_FOREACH(descriptors, &stats_descriptors, next) {
3953 if (g_str_equal(descriptors->ident, ident)) {
3954 return descriptors;
3958 descriptors = g_new0(StatsDescriptors, 1);
3960 /* Read stats header */
3961 kvm_stats_header = &descriptors->kvm_stats_header;
3962 ret = read(stats_fd, kvm_stats_header, sizeof(*kvm_stats_header));
3963 if (ret != sizeof(*kvm_stats_header)) {
3964 error_setg(errp, "KVM stats: failed to read stats header: "
3965 "expected %zu actual %zu",
3966 sizeof(*kvm_stats_header), ret);
3967 g_free(descriptors);
3968 return NULL;
3970 size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
3972 /* Read stats descriptors */
3973 kvm_stats_desc = g_malloc0_n(kvm_stats_header->num_desc, size_desc);
3974 ret = pread(stats_fd, kvm_stats_desc,
3975 size_desc * kvm_stats_header->num_desc,
3976 kvm_stats_header->desc_offset);
3978 if (ret != size_desc * kvm_stats_header->num_desc) {
3979 error_setg(errp, "KVM stats: failed to read stats descriptors: "
3980 "expected %zu actual %zu",
3981 size_desc * kvm_stats_header->num_desc, ret);
3982 g_free(descriptors);
3983 g_free(kvm_stats_desc);
3984 return NULL;
3986 descriptors->kvm_stats_desc = kvm_stats_desc;
3987 descriptors->ident = ident;
3988 QTAILQ_INSERT_TAIL(&stats_descriptors, descriptors, next);
3989 return descriptors;
3992 static void query_stats(StatsResultList **result, StatsTarget target,
3993 strList *names, int stats_fd, Error **errp)
3995 struct kvm_stats_desc *kvm_stats_desc;
3996 struct kvm_stats_header *kvm_stats_header;
3997 StatsDescriptors *descriptors;
3998 g_autofree uint64_t *stats_data = NULL;
3999 struct kvm_stats_desc *pdesc;
4000 StatsList *stats_list = NULL;
4001 size_t size_desc, size_data = 0;
4002 ssize_t ret;
4003 int i;
4005 descriptors = find_stats_descriptors(target, stats_fd, errp);
4006 if (!descriptors) {
4007 return;
4010 kvm_stats_header = &descriptors->kvm_stats_header;
4011 kvm_stats_desc = descriptors->kvm_stats_desc;
4012 size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4014 /* Tally the total data size; read schema data */
4015 for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4016 pdesc = (void *)kvm_stats_desc + i * size_desc;
4017 size_data += pdesc->size * sizeof(*stats_data);
4020 stats_data = g_malloc0(size_data);
4021 ret = pread(stats_fd, stats_data, size_data, kvm_stats_header->data_offset);
4023 if (ret != size_data) {
4024 error_setg(errp, "KVM stats: failed to read data: "
4025 "expected %zu actual %zu", size_data, ret);
4026 return;
4029 for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4030 uint64_t *stats;
4031 pdesc = (void *)kvm_stats_desc + i * size_desc;
4033 /* Add entry to the list */
4034 stats = (void *)stats_data + pdesc->offset;
4035 if (!apply_str_list_filter(pdesc->name, names)) {
4036 continue;
4038 stats_list = add_kvmstat_entry(pdesc, stats, stats_list, errp);
4041 if (!stats_list) {
4042 return;
4045 switch (target) {
4046 case STATS_TARGET_VM:
4047 add_stats_entry(result, STATS_PROVIDER_KVM, NULL, stats_list);
4048 break;
4049 case STATS_TARGET_VCPU:
4050 add_stats_entry(result, STATS_PROVIDER_KVM,
4051 current_cpu->parent_obj.canonical_path,
4052 stats_list);
4053 break;
4054 default:
4055 g_assert_not_reached();
4059 static void query_stats_schema(StatsSchemaList **result, StatsTarget target,
4060 int stats_fd, Error **errp)
4062 struct kvm_stats_desc *kvm_stats_desc;
4063 struct kvm_stats_header *kvm_stats_header;
4064 StatsDescriptors *descriptors;
4065 struct kvm_stats_desc *pdesc;
4066 StatsSchemaValueList *stats_list = NULL;
4067 size_t size_desc;
4068 int i;
4070 descriptors = find_stats_descriptors(target, stats_fd, errp);
4071 if (!descriptors) {
4072 return;
4075 kvm_stats_header = &descriptors->kvm_stats_header;
4076 kvm_stats_desc = descriptors->kvm_stats_desc;
4077 size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4079 /* Tally the total data size; read schema data */
4080 for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4081 pdesc = (void *)kvm_stats_desc + i * size_desc;
4082 stats_list = add_kvmschema_entry(pdesc, stats_list, errp);
4085 add_stats_schema(result, STATS_PROVIDER_KVM, target, stats_list);
4088 static void query_stats_vcpu(CPUState *cpu, run_on_cpu_data data)
4090 StatsArgs *kvm_stats_args = (StatsArgs *) data.host_ptr;
4091 int stats_fd = kvm_vcpu_ioctl(cpu, KVM_GET_STATS_FD, NULL);
4092 Error *local_err = NULL;
4094 if (stats_fd == -1) {
4095 error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
4096 error_propagate(kvm_stats_args->errp, local_err);
4097 return;
4099 query_stats(kvm_stats_args->result.stats, STATS_TARGET_VCPU,
4100 kvm_stats_args->names, stats_fd, kvm_stats_args->errp);
4101 close(stats_fd);
4104 static void query_stats_schema_vcpu(CPUState *cpu, run_on_cpu_data data)
4106 StatsArgs *kvm_stats_args = (StatsArgs *) data.host_ptr;
4107 int stats_fd = kvm_vcpu_ioctl(cpu, KVM_GET_STATS_FD, NULL);
4108 Error *local_err = NULL;
4110 if (stats_fd == -1) {
4111 error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
4112 error_propagate(kvm_stats_args->errp, local_err);
4113 return;
4115 query_stats_schema(kvm_stats_args->result.schema, STATS_TARGET_VCPU, stats_fd,
4116 kvm_stats_args->errp);
4117 close(stats_fd);
4120 static void query_stats_cb(StatsResultList **result, StatsTarget target,
4121 strList *names, strList *targets, Error **errp)
4123 KVMState *s = kvm_state;
4124 CPUState *cpu;
4125 int stats_fd;
4127 switch (target) {
4128 case STATS_TARGET_VM:
4130 stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
4131 if (stats_fd == -1) {
4132 error_setg_errno(errp, errno, "KVM stats: ioctl failed");
4133 return;
4135 query_stats(result, target, names, stats_fd, errp);
4136 close(stats_fd);
4137 break;
4139 case STATS_TARGET_VCPU:
4141 StatsArgs stats_args;
4142 stats_args.result.stats = result;
4143 stats_args.names = names;
4144 stats_args.errp = errp;
4145 CPU_FOREACH(cpu) {
4146 if (!apply_str_list_filter(cpu->parent_obj.canonical_path, targets)) {
4147 continue;
4149 run_on_cpu(cpu, query_stats_vcpu, RUN_ON_CPU_HOST_PTR(&stats_args));
4151 break;
4153 default:
4154 break;
4158 void query_stats_schemas_cb(StatsSchemaList **result, Error **errp)
4160 StatsArgs stats_args;
4161 KVMState *s = kvm_state;
4162 int stats_fd;
4164 stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
4165 if (stats_fd == -1) {
4166 error_setg_errno(errp, errno, "KVM stats: ioctl failed");
4167 return;
4169 query_stats_schema(result, STATS_TARGET_VM, stats_fd, errp);
4170 close(stats_fd);
4172 if (first_cpu) {
4173 stats_args.result.schema = result;
4174 stats_args.errp = errp;
4175 run_on_cpu(first_cpu, query_stats_schema_vcpu, RUN_ON_CPU_HOST_PTR(&stats_args));