qga/commands-posix: Send CCW address on s390x with the fsinfo data
[qemu/ar7.git] / accel / kvm / kvm-all.c
blob389eaace7289c1e8a15bff0ed0c2fd494a49a128
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>
19 #include <linux/kvm.h>
21 #include "qemu/atomic.h"
22 #include "qemu/option.h"
23 #include "qemu/config-file.h"
24 #include "qemu/error-report.h"
25 #include "qapi/error.h"
26 #include "hw/pci/msi.h"
27 #include "hw/pci/msix.h"
28 #include "hw/s390x/adapter.h"
29 #include "exec/gdbstub.h"
30 #include "sysemu/kvm_int.h"
31 #include "sysemu/runstate.h"
32 #include "sysemu/cpus.h"
33 #include "sysemu/sysemu.h"
34 #include "qemu/bswap.h"
35 #include "exec/memory.h"
36 #include "exec/ram_addr.h"
37 #include "exec/address-spaces.h"
38 #include "qemu/event_notifier.h"
39 #include "qemu/main-loop.h"
40 #include "trace.h"
41 #include "hw/irq.h"
42 #include "sysemu/sev.h"
43 #include "qapi/visitor.h"
44 #include "qapi/qapi-types-common.h"
45 #include "qapi/qapi-visit-common.h"
46 #include "sysemu/reset.h"
47 #include "qemu/guest-random.h"
48 #include "sysemu/hw_accel.h"
49 #include "kvm-cpus.h"
51 #include "hw/boards.h"
53 /* This check must be after config-host.h is included */
54 #ifdef CONFIG_EVENTFD
55 #include <sys/eventfd.h>
56 #endif
58 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
59 * need to use the real host PAGE_SIZE, as that's what KVM will use.
61 #define PAGE_SIZE qemu_real_host_page_size
63 //#define DEBUG_KVM
65 #ifdef DEBUG_KVM
66 #define DPRINTF(fmt, ...) \
67 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
68 #else
69 #define DPRINTF(fmt, ...) \
70 do { } while (0)
71 #endif
73 #define KVM_MSI_HASHTAB_SIZE 256
75 struct KVMParkedVcpu {
76 unsigned long vcpu_id;
77 int kvm_fd;
78 QLIST_ENTRY(KVMParkedVcpu) node;
81 struct KVMState
83 AccelState parent_obj;
85 int nr_slots;
86 int fd;
87 int vmfd;
88 int coalesced_mmio;
89 int coalesced_pio;
90 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
91 bool coalesced_flush_in_progress;
92 int vcpu_events;
93 int robust_singlestep;
94 int debugregs;
95 #ifdef KVM_CAP_SET_GUEST_DEBUG
96 QTAILQ_HEAD(, kvm_sw_breakpoint) kvm_sw_breakpoints;
97 #endif
98 int max_nested_state_len;
99 int many_ioeventfds;
100 int intx_set_mask;
101 int kvm_shadow_mem;
102 bool kernel_irqchip_allowed;
103 bool kernel_irqchip_required;
104 OnOffAuto kernel_irqchip_split;
105 bool sync_mmu;
106 uint64_t manual_dirty_log_protect;
107 /* The man page (and posix) say ioctl numbers are signed int, but
108 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
109 * unsigned, and treating them as signed here can break things */
110 unsigned irq_set_ioctl;
111 unsigned int sigmask_len;
112 GHashTable *gsimap;
113 #ifdef KVM_CAP_IRQ_ROUTING
114 struct kvm_irq_routing *irq_routes;
115 int nr_allocated_irq_routes;
116 unsigned long *used_gsi_bitmap;
117 unsigned int gsi_count;
118 QTAILQ_HEAD(, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
119 #endif
120 KVMMemoryListener memory_listener;
121 QLIST_HEAD(, KVMParkedVcpu) kvm_parked_vcpus;
123 /* memory encryption */
124 void *memcrypt_handle;
125 int (*memcrypt_encrypt_data)(void *handle, uint8_t *ptr, uint64_t len);
127 /* For "info mtree -f" to tell if an MR is registered in KVM */
128 int nr_as;
129 struct KVMAs {
130 KVMMemoryListener *ml;
131 AddressSpace *as;
132 } *as;
135 KVMState *kvm_state;
136 bool kvm_kernel_irqchip;
137 bool kvm_split_irqchip;
138 bool kvm_async_interrupts_allowed;
139 bool kvm_halt_in_kernel_allowed;
140 bool kvm_eventfds_allowed;
141 bool kvm_irqfds_allowed;
142 bool kvm_resamplefds_allowed;
143 bool kvm_msi_via_irqfd_allowed;
144 bool kvm_gsi_routing_allowed;
145 bool kvm_gsi_direct_mapping;
146 bool kvm_allowed;
147 bool kvm_readonly_mem_allowed;
148 bool kvm_vm_attributes_allowed;
149 bool kvm_direct_msi_allowed;
150 bool kvm_ioeventfd_any_length_allowed;
151 bool kvm_msi_use_devid;
152 static bool kvm_immediate_exit;
153 static hwaddr kvm_max_slot_size = ~0;
155 static const KVMCapabilityInfo kvm_required_capabilites[] = {
156 KVM_CAP_INFO(USER_MEMORY),
157 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
158 KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS),
159 KVM_CAP_LAST_INFO
162 static NotifierList kvm_irqchip_change_notifiers =
163 NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers);
165 struct KVMResampleFd {
166 int gsi;
167 EventNotifier *resample_event;
168 QLIST_ENTRY(KVMResampleFd) node;
170 typedef struct KVMResampleFd KVMResampleFd;
173 * Only used with split irqchip where we need to do the resample fd
174 * kick for the kernel from userspace.
176 static QLIST_HEAD(, KVMResampleFd) kvm_resample_fd_list =
177 QLIST_HEAD_INITIALIZER(kvm_resample_fd_list);
179 #define kvm_slots_lock(kml) qemu_mutex_lock(&(kml)->slots_lock)
180 #define kvm_slots_unlock(kml) qemu_mutex_unlock(&(kml)->slots_lock)
182 static inline void kvm_resample_fd_remove(int gsi)
184 KVMResampleFd *rfd;
186 QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
187 if (rfd->gsi == gsi) {
188 QLIST_REMOVE(rfd, node);
189 g_free(rfd);
190 break;
195 static inline void kvm_resample_fd_insert(int gsi, EventNotifier *event)
197 KVMResampleFd *rfd = g_new0(KVMResampleFd, 1);
199 rfd->gsi = gsi;
200 rfd->resample_event = event;
202 QLIST_INSERT_HEAD(&kvm_resample_fd_list, rfd, node);
205 void kvm_resample_fd_notify(int gsi)
207 KVMResampleFd *rfd;
209 QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
210 if (rfd->gsi == gsi) {
211 event_notifier_set(rfd->resample_event);
212 trace_kvm_resample_fd_notify(gsi);
213 return;
218 int kvm_get_max_memslots(void)
220 KVMState *s = KVM_STATE(current_accel());
222 return s->nr_slots;
225 bool kvm_memcrypt_enabled(void)
227 if (kvm_state && kvm_state->memcrypt_handle) {
228 return true;
231 return false;
234 int kvm_memcrypt_encrypt_data(uint8_t *ptr, uint64_t len)
236 if (kvm_state->memcrypt_handle &&
237 kvm_state->memcrypt_encrypt_data) {
238 return kvm_state->memcrypt_encrypt_data(kvm_state->memcrypt_handle,
239 ptr, len);
242 return 1;
245 /* Called with KVMMemoryListener.slots_lock held */
246 static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
248 KVMState *s = kvm_state;
249 int i;
251 for (i = 0; i < s->nr_slots; i++) {
252 if (kml->slots[i].memory_size == 0) {
253 return &kml->slots[i];
257 return NULL;
260 bool kvm_has_free_slot(MachineState *ms)
262 KVMState *s = KVM_STATE(ms->accelerator);
263 bool result;
264 KVMMemoryListener *kml = &s->memory_listener;
266 kvm_slots_lock(kml);
267 result = !!kvm_get_free_slot(kml);
268 kvm_slots_unlock(kml);
270 return result;
273 /* Called with KVMMemoryListener.slots_lock held */
274 static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
276 KVMSlot *slot = kvm_get_free_slot(kml);
278 if (slot) {
279 return slot;
282 fprintf(stderr, "%s: no free slot available\n", __func__);
283 abort();
286 static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
287 hwaddr start_addr,
288 hwaddr size)
290 KVMState *s = kvm_state;
291 int i;
293 for (i = 0; i < s->nr_slots; i++) {
294 KVMSlot *mem = &kml->slots[i];
296 if (start_addr == mem->start_addr && size == mem->memory_size) {
297 return mem;
301 return NULL;
305 * Calculate and align the start address and the size of the section.
306 * Return the size. If the size is 0, the aligned section is empty.
308 static hwaddr kvm_align_section(MemoryRegionSection *section,
309 hwaddr *start)
311 hwaddr size = int128_get64(section->size);
312 hwaddr delta, aligned;
314 /* kvm works in page size chunks, but the function may be called
315 with sub-page size and unaligned start address. Pad the start
316 address to next and truncate size to previous page boundary. */
317 aligned = ROUND_UP(section->offset_within_address_space,
318 qemu_real_host_page_size);
319 delta = aligned - section->offset_within_address_space;
320 *start = aligned;
321 if (delta > size) {
322 return 0;
325 return (size - delta) & qemu_real_host_page_mask;
328 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
329 hwaddr *phys_addr)
331 KVMMemoryListener *kml = &s->memory_listener;
332 int i, ret = 0;
334 kvm_slots_lock(kml);
335 for (i = 0; i < s->nr_slots; i++) {
336 KVMSlot *mem = &kml->slots[i];
338 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
339 *phys_addr = mem->start_addr + (ram - mem->ram);
340 ret = 1;
341 break;
344 kvm_slots_unlock(kml);
346 return ret;
349 static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot, bool new)
351 KVMState *s = kvm_state;
352 struct kvm_userspace_memory_region mem;
353 int ret;
355 mem.slot = slot->slot | (kml->as_id << 16);
356 mem.guest_phys_addr = slot->start_addr;
357 mem.userspace_addr = (unsigned long)slot->ram;
358 mem.flags = slot->flags;
360 if (slot->memory_size && !new && (mem.flags ^ slot->old_flags) & KVM_MEM_READONLY) {
361 /* Set the slot size to 0 before setting the slot to the desired
362 * value. This is needed based on KVM commit 75d61fbc. */
363 mem.memory_size = 0;
364 ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
365 if (ret < 0) {
366 goto err;
369 mem.memory_size = slot->memory_size;
370 ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
371 slot->old_flags = mem.flags;
372 err:
373 trace_kvm_set_user_memory(mem.slot, mem.flags, mem.guest_phys_addr,
374 mem.memory_size, mem.userspace_addr, ret);
375 if (ret < 0) {
376 error_report("%s: KVM_SET_USER_MEMORY_REGION failed, slot=%d,"
377 " start=0x%" PRIx64 ", size=0x%" PRIx64 ": %s",
378 __func__, mem.slot, slot->start_addr,
379 (uint64_t)mem.memory_size, strerror(errno));
381 return ret;
384 static int do_kvm_destroy_vcpu(CPUState *cpu)
386 KVMState *s = kvm_state;
387 long mmap_size;
388 struct KVMParkedVcpu *vcpu = NULL;
389 int ret = 0;
391 DPRINTF("kvm_destroy_vcpu\n");
393 ret = kvm_arch_destroy_vcpu(cpu);
394 if (ret < 0) {
395 goto err;
398 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
399 if (mmap_size < 0) {
400 ret = mmap_size;
401 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
402 goto err;
405 ret = munmap(cpu->kvm_run, mmap_size);
406 if (ret < 0) {
407 goto err;
410 vcpu = g_malloc0(sizeof(*vcpu));
411 vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
412 vcpu->kvm_fd = cpu->kvm_fd;
413 QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
414 err:
415 return ret;
418 void kvm_destroy_vcpu(CPUState *cpu)
420 if (do_kvm_destroy_vcpu(cpu) < 0) {
421 error_report("kvm_destroy_vcpu failed");
422 exit(EXIT_FAILURE);
426 static int kvm_get_vcpu(KVMState *s, unsigned long vcpu_id)
428 struct KVMParkedVcpu *cpu;
430 QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
431 if (cpu->vcpu_id == vcpu_id) {
432 int kvm_fd;
434 QLIST_REMOVE(cpu, node);
435 kvm_fd = cpu->kvm_fd;
436 g_free(cpu);
437 return kvm_fd;
441 return kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)vcpu_id);
444 int kvm_init_vcpu(CPUState *cpu, Error **errp)
446 KVMState *s = kvm_state;
447 long mmap_size;
448 int ret;
450 trace_kvm_init_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
452 ret = kvm_get_vcpu(s, kvm_arch_vcpu_id(cpu));
453 if (ret < 0) {
454 error_setg_errno(errp, -ret, "kvm_init_vcpu: kvm_get_vcpu failed (%lu)",
455 kvm_arch_vcpu_id(cpu));
456 goto err;
459 cpu->kvm_fd = ret;
460 cpu->kvm_state = s;
461 cpu->vcpu_dirty = true;
463 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
464 if (mmap_size < 0) {
465 ret = mmap_size;
466 error_setg_errno(errp, -mmap_size,
467 "kvm_init_vcpu: KVM_GET_VCPU_MMAP_SIZE failed");
468 goto err;
471 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
472 cpu->kvm_fd, 0);
473 if (cpu->kvm_run == MAP_FAILED) {
474 ret = -errno;
475 error_setg_errno(errp, ret,
476 "kvm_init_vcpu: mmap'ing vcpu state failed (%lu)",
477 kvm_arch_vcpu_id(cpu));
478 goto err;
481 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
482 s->coalesced_mmio_ring =
483 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
486 ret = kvm_arch_init_vcpu(cpu);
487 if (ret < 0) {
488 error_setg_errno(errp, -ret,
489 "kvm_init_vcpu: kvm_arch_init_vcpu failed (%lu)",
490 kvm_arch_vcpu_id(cpu));
492 err:
493 return ret;
497 * dirty pages logging control
500 static int kvm_mem_flags(MemoryRegion *mr)
502 bool readonly = mr->readonly || memory_region_is_romd(mr);
503 int flags = 0;
505 if (memory_region_get_dirty_log_mask(mr) != 0) {
506 flags |= KVM_MEM_LOG_DIRTY_PAGES;
508 if (readonly && kvm_readonly_mem_allowed) {
509 flags |= KVM_MEM_READONLY;
511 return flags;
514 /* Called with KVMMemoryListener.slots_lock held */
515 static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
516 MemoryRegion *mr)
518 mem->flags = kvm_mem_flags(mr);
520 /* If nothing changed effectively, no need to issue ioctl */
521 if (mem->flags == mem->old_flags) {
522 return 0;
525 return kvm_set_user_memory_region(kml, mem, false);
528 static int kvm_section_update_flags(KVMMemoryListener *kml,
529 MemoryRegionSection *section)
531 hwaddr start_addr, size, slot_size;
532 KVMSlot *mem;
533 int ret = 0;
535 size = kvm_align_section(section, &start_addr);
536 if (!size) {
537 return 0;
540 kvm_slots_lock(kml);
542 while (size && !ret) {
543 slot_size = MIN(kvm_max_slot_size, size);
544 mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
545 if (!mem) {
546 /* We don't have a slot if we want to trap every access. */
547 goto out;
550 ret = kvm_slot_update_flags(kml, mem, section->mr);
551 start_addr += slot_size;
552 size -= slot_size;
555 out:
556 kvm_slots_unlock(kml);
557 return ret;
560 static void kvm_log_start(MemoryListener *listener,
561 MemoryRegionSection *section,
562 int old, int new)
564 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
565 int r;
567 if (old != 0) {
568 return;
571 r = kvm_section_update_flags(kml, section);
572 if (r < 0) {
573 abort();
577 static void kvm_log_stop(MemoryListener *listener,
578 MemoryRegionSection *section,
579 int old, int new)
581 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
582 int r;
584 if (new != 0) {
585 return;
588 r = kvm_section_update_flags(kml, section);
589 if (r < 0) {
590 abort();
594 /* get kvm's dirty pages bitmap and update qemu's */
595 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
596 unsigned long *bitmap)
598 ram_addr_t start = section->offset_within_region +
599 memory_region_get_ram_addr(section->mr);
600 ram_addr_t pages = int128_get64(section->size) / qemu_real_host_page_size;
602 cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
603 return 0;
606 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
608 /* Allocate the dirty bitmap for a slot */
609 static void kvm_memslot_init_dirty_bitmap(KVMSlot *mem)
612 * XXX bad kernel interface alert
613 * For dirty bitmap, kernel allocates array of size aligned to
614 * bits-per-long. But for case when the kernel is 64bits and
615 * the userspace is 32bits, userspace can't align to the same
616 * bits-per-long, since sizeof(long) is different between kernel
617 * and user space. This way, userspace will provide buffer which
618 * may be 4 bytes less than the kernel will use, resulting in
619 * userspace memory corruption (which is not detectable by valgrind
620 * too, in most cases).
621 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
622 * a hope that sizeof(long) won't become >8 any time soon.
624 hwaddr bitmap_size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
625 /*HOST_LONG_BITS*/ 64) / 8;
626 mem->dirty_bmap = g_malloc0(bitmap_size);
630 * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
632 * This function will first try to fetch dirty bitmap from the kernel,
633 * and then updates qemu's dirty bitmap.
635 * NOTE: caller must be with kml->slots_lock held.
637 * @kml: the KVM memory listener object
638 * @section: the memory section to sync the dirty bitmap with
640 static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
641 MemoryRegionSection *section)
643 KVMState *s = kvm_state;
644 struct kvm_dirty_log d = {};
645 KVMSlot *mem;
646 hwaddr start_addr, size;
647 hwaddr slot_size, slot_offset = 0;
648 int ret = 0;
650 size = kvm_align_section(section, &start_addr);
651 while (size) {
652 MemoryRegionSection subsection = *section;
654 slot_size = MIN(kvm_max_slot_size, size);
655 mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
656 if (!mem) {
657 /* We don't have a slot if we want to trap every access. */
658 goto out;
661 if (!mem->dirty_bmap) {
662 /* Allocate on the first log_sync, once and for all */
663 kvm_memslot_init_dirty_bitmap(mem);
666 d.dirty_bitmap = mem->dirty_bmap;
667 d.slot = mem->slot | (kml->as_id << 16);
668 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
669 DPRINTF("ioctl failed %d\n", errno);
670 ret = -1;
671 goto out;
674 subsection.offset_within_region += slot_offset;
675 subsection.size = int128_make64(slot_size);
676 kvm_get_dirty_pages_log_range(&subsection, d.dirty_bitmap);
678 slot_offset += slot_size;
679 start_addr += slot_size;
680 size -= slot_size;
682 out:
683 return ret;
686 /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
687 #define KVM_CLEAR_LOG_SHIFT 6
688 #define KVM_CLEAR_LOG_ALIGN (qemu_real_host_page_size << KVM_CLEAR_LOG_SHIFT)
689 #define KVM_CLEAR_LOG_MASK (-KVM_CLEAR_LOG_ALIGN)
691 static int kvm_log_clear_one_slot(KVMSlot *mem, int as_id, uint64_t start,
692 uint64_t size)
694 KVMState *s = kvm_state;
695 uint64_t end, bmap_start, start_delta, bmap_npages;
696 struct kvm_clear_dirty_log d;
697 unsigned long *bmap_clear = NULL, psize = qemu_real_host_page_size;
698 int ret;
701 * We need to extend either the start or the size or both to
702 * satisfy the KVM interface requirement. Firstly, do the start
703 * page alignment on 64 host pages
705 bmap_start = start & KVM_CLEAR_LOG_MASK;
706 start_delta = start - bmap_start;
707 bmap_start /= psize;
710 * The kernel interface has restriction on the size too, that either:
712 * (1) the size is 64 host pages aligned (just like the start), or
713 * (2) the size fills up until the end of the KVM memslot.
715 bmap_npages = DIV_ROUND_UP(size + start_delta, KVM_CLEAR_LOG_ALIGN)
716 << KVM_CLEAR_LOG_SHIFT;
717 end = mem->memory_size / psize;
718 if (bmap_npages > end - bmap_start) {
719 bmap_npages = end - bmap_start;
721 start_delta /= psize;
724 * Prepare the bitmap to clear dirty bits. Here we must guarantee
725 * that we won't clear any unknown dirty bits otherwise we might
726 * accidentally clear some set bits which are not yet synced from
727 * the kernel into QEMU's bitmap, then we'll lose track of the
728 * guest modifications upon those pages (which can directly lead
729 * to guest data loss or panic after migration).
731 * Layout of the KVMSlot.dirty_bmap:
733 * |<-------- bmap_npages -----------..>|
734 * [1]
735 * start_delta size
736 * |----------------|-------------|------------------|------------|
737 * ^ ^ ^ ^
738 * | | | |
739 * start bmap_start (start) end
740 * of memslot of memslot
742 * [1] bmap_npages can be aligned to either 64 pages or the end of slot
745 assert(bmap_start % BITS_PER_LONG == 0);
746 /* We should never do log_clear before log_sync */
747 assert(mem->dirty_bmap);
748 if (start_delta || bmap_npages - size / psize) {
749 /* Slow path - we need to manipulate a temp bitmap */
750 bmap_clear = bitmap_new(bmap_npages);
751 bitmap_copy_with_src_offset(bmap_clear, mem->dirty_bmap,
752 bmap_start, start_delta + size / psize);
754 * We need to fill the holes at start because that was not
755 * specified by the caller and we extended the bitmap only for
756 * 64 pages alignment
758 bitmap_clear(bmap_clear, 0, start_delta);
759 d.dirty_bitmap = bmap_clear;
760 } else {
762 * Fast path - both start and size align well with BITS_PER_LONG
763 * (or the end of memory slot)
765 d.dirty_bitmap = mem->dirty_bmap + BIT_WORD(bmap_start);
768 d.first_page = bmap_start;
769 /* It should never overflow. If it happens, say something */
770 assert(bmap_npages <= UINT32_MAX);
771 d.num_pages = bmap_npages;
772 d.slot = mem->slot | (as_id << 16);
774 if (kvm_vm_ioctl(s, KVM_CLEAR_DIRTY_LOG, &d) == -1) {
775 ret = -errno;
776 error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
777 "start=0x%"PRIx64", size=0x%"PRIx32", errno=%d",
778 __func__, d.slot, (uint64_t)d.first_page,
779 (uint32_t)d.num_pages, ret);
780 } else {
781 ret = 0;
782 trace_kvm_clear_dirty_log(d.slot, d.first_page, d.num_pages);
786 * After we have updated the remote dirty bitmap, we update the
787 * cached bitmap as well for the memslot, then if another user
788 * clears the same region we know we shouldn't clear it again on
789 * the remote otherwise it's data loss as well.
791 bitmap_clear(mem->dirty_bmap, bmap_start + start_delta,
792 size / psize);
793 /* This handles the NULL case well */
794 g_free(bmap_clear);
795 return ret;
800 * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
802 * NOTE: this will be a no-op if we haven't enabled manual dirty log
803 * protection in the host kernel because in that case this operation
804 * will be done within log_sync().
806 * @kml: the kvm memory listener
807 * @section: the memory range to clear dirty bitmap
809 static int kvm_physical_log_clear(KVMMemoryListener *kml,
810 MemoryRegionSection *section)
812 KVMState *s = kvm_state;
813 uint64_t start, size, offset, count;
814 KVMSlot *mem;
815 int ret = 0, i;
817 if (!s->manual_dirty_log_protect) {
818 /* No need to do explicit clear */
819 return ret;
822 start = section->offset_within_address_space;
823 size = int128_get64(section->size);
825 if (!size) {
826 /* Nothing more we can do... */
827 return ret;
830 kvm_slots_lock(kml);
832 for (i = 0; i < s->nr_slots; i++) {
833 mem = &kml->slots[i];
834 /* Discard slots that are empty or do not overlap the section */
835 if (!mem->memory_size ||
836 mem->start_addr > start + size - 1 ||
837 start > mem->start_addr + mem->memory_size - 1) {
838 continue;
841 if (start >= mem->start_addr) {
842 /* The slot starts before section or is aligned to it. */
843 offset = start - mem->start_addr;
844 count = MIN(mem->memory_size - offset, size);
845 } else {
846 /* The slot starts after section. */
847 offset = 0;
848 count = MIN(mem->memory_size, size - (mem->start_addr - start));
850 ret = kvm_log_clear_one_slot(mem, kml->as_id, offset, count);
851 if (ret < 0) {
852 break;
856 kvm_slots_unlock(kml);
858 return ret;
861 static void kvm_coalesce_mmio_region(MemoryListener *listener,
862 MemoryRegionSection *secion,
863 hwaddr start, hwaddr size)
865 KVMState *s = kvm_state;
867 if (s->coalesced_mmio) {
868 struct kvm_coalesced_mmio_zone zone;
870 zone.addr = start;
871 zone.size = size;
872 zone.pad = 0;
874 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
878 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
879 MemoryRegionSection *secion,
880 hwaddr start, hwaddr size)
882 KVMState *s = kvm_state;
884 if (s->coalesced_mmio) {
885 struct kvm_coalesced_mmio_zone zone;
887 zone.addr = start;
888 zone.size = size;
889 zone.pad = 0;
891 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
895 static void kvm_coalesce_pio_add(MemoryListener *listener,
896 MemoryRegionSection *section,
897 hwaddr start, hwaddr size)
899 KVMState *s = kvm_state;
901 if (s->coalesced_pio) {
902 struct kvm_coalesced_mmio_zone zone;
904 zone.addr = start;
905 zone.size = size;
906 zone.pio = 1;
908 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
912 static void kvm_coalesce_pio_del(MemoryListener *listener,
913 MemoryRegionSection *section,
914 hwaddr start, hwaddr size)
916 KVMState *s = kvm_state;
918 if (s->coalesced_pio) {
919 struct kvm_coalesced_mmio_zone zone;
921 zone.addr = start;
922 zone.size = size;
923 zone.pio = 1;
925 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
929 static MemoryListener kvm_coalesced_pio_listener = {
930 .coalesced_io_add = kvm_coalesce_pio_add,
931 .coalesced_io_del = kvm_coalesce_pio_del,
934 int kvm_check_extension(KVMState *s, unsigned int extension)
936 int ret;
938 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
939 if (ret < 0) {
940 ret = 0;
943 return ret;
946 int kvm_vm_check_extension(KVMState *s, unsigned int extension)
948 int ret;
950 ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
951 if (ret < 0) {
952 /* VM wide version not implemented, use global one instead */
953 ret = kvm_check_extension(s, extension);
956 return ret;
959 typedef struct HWPoisonPage {
960 ram_addr_t ram_addr;
961 QLIST_ENTRY(HWPoisonPage) list;
962 } HWPoisonPage;
964 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
965 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
967 static void kvm_unpoison_all(void *param)
969 HWPoisonPage *page, *next_page;
971 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
972 QLIST_REMOVE(page, list);
973 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
974 g_free(page);
978 void kvm_hwpoison_page_add(ram_addr_t ram_addr)
980 HWPoisonPage *page;
982 QLIST_FOREACH(page, &hwpoison_page_list, list) {
983 if (page->ram_addr == ram_addr) {
984 return;
987 page = g_new(HWPoisonPage, 1);
988 page->ram_addr = ram_addr;
989 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
992 static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
994 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
995 /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
996 * endianness, but the memory core hands them in target endianness.
997 * For example, PPC is always treated as big-endian even if running
998 * on KVM and on PPC64LE. Correct here.
1000 switch (size) {
1001 case 2:
1002 val = bswap16(val);
1003 break;
1004 case 4:
1005 val = bswap32(val);
1006 break;
1008 #endif
1009 return val;
1012 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
1013 bool assign, uint32_t size, bool datamatch)
1015 int ret;
1016 struct kvm_ioeventfd iofd = {
1017 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
1018 .addr = addr,
1019 .len = size,
1020 .flags = 0,
1021 .fd = fd,
1024 trace_kvm_set_ioeventfd_mmio(fd, (uint64_t)addr, val, assign, size,
1025 datamatch);
1026 if (!kvm_enabled()) {
1027 return -ENOSYS;
1030 if (datamatch) {
1031 iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
1033 if (!assign) {
1034 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1037 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
1039 if (ret < 0) {
1040 return -errno;
1043 return 0;
1046 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
1047 bool assign, uint32_t size, bool datamatch)
1049 struct kvm_ioeventfd kick = {
1050 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
1051 .addr = addr,
1052 .flags = KVM_IOEVENTFD_FLAG_PIO,
1053 .len = size,
1054 .fd = fd,
1056 int r;
1057 trace_kvm_set_ioeventfd_pio(fd, addr, val, assign, size, datamatch);
1058 if (!kvm_enabled()) {
1059 return -ENOSYS;
1061 if (datamatch) {
1062 kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
1064 if (!assign) {
1065 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1067 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
1068 if (r < 0) {
1069 return r;
1071 return 0;
1075 static int kvm_check_many_ioeventfds(void)
1077 /* Userspace can use ioeventfd for io notification. This requires a host
1078 * that supports eventfd(2) and an I/O thread; since eventfd does not
1079 * support SIGIO it cannot interrupt the vcpu.
1081 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
1082 * can avoid creating too many ioeventfds.
1084 #if defined(CONFIG_EVENTFD)
1085 int ioeventfds[7];
1086 int i, ret = 0;
1087 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
1088 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
1089 if (ioeventfds[i] < 0) {
1090 break;
1092 ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
1093 if (ret < 0) {
1094 close(ioeventfds[i]);
1095 break;
1099 /* Decide whether many devices are supported or not */
1100 ret = i == ARRAY_SIZE(ioeventfds);
1102 while (i-- > 0) {
1103 kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
1104 close(ioeventfds[i]);
1106 return ret;
1107 #else
1108 return 0;
1109 #endif
1112 static const KVMCapabilityInfo *
1113 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
1115 while (list->name) {
1116 if (!kvm_check_extension(s, list->value)) {
1117 return list;
1119 list++;
1121 return NULL;
1124 void kvm_set_max_memslot_size(hwaddr max_slot_size)
1126 g_assert(
1127 ROUND_UP(max_slot_size, qemu_real_host_page_size) == max_slot_size
1129 kvm_max_slot_size = max_slot_size;
1132 static void kvm_set_phys_mem(KVMMemoryListener *kml,
1133 MemoryRegionSection *section, bool add)
1135 KVMSlot *mem;
1136 int err;
1137 MemoryRegion *mr = section->mr;
1138 bool writeable = !mr->readonly && !mr->rom_device;
1139 hwaddr start_addr, size, slot_size;
1140 void *ram;
1142 if (!memory_region_is_ram(mr)) {
1143 if (writeable || !kvm_readonly_mem_allowed) {
1144 return;
1145 } else if (!mr->romd_mode) {
1146 /* If the memory device is not in romd_mode, then we actually want
1147 * to remove the kvm memory slot so all accesses will trap. */
1148 add = false;
1152 size = kvm_align_section(section, &start_addr);
1153 if (!size) {
1154 return;
1157 /* use aligned delta to align the ram address */
1158 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region +
1159 (start_addr - section->offset_within_address_space);
1161 kvm_slots_lock(kml);
1163 if (!add) {
1164 do {
1165 slot_size = MIN(kvm_max_slot_size, size);
1166 mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
1167 if (!mem) {
1168 goto out;
1170 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1171 kvm_physical_sync_dirty_bitmap(kml, section);
1174 /* unregister the slot */
1175 g_free(mem->dirty_bmap);
1176 mem->dirty_bmap = NULL;
1177 mem->memory_size = 0;
1178 mem->flags = 0;
1179 err = kvm_set_user_memory_region(kml, mem, false);
1180 if (err) {
1181 fprintf(stderr, "%s: error unregistering slot: %s\n",
1182 __func__, strerror(-err));
1183 abort();
1185 start_addr += slot_size;
1186 size -= slot_size;
1187 } while (size);
1188 goto out;
1191 /* register the new slot */
1192 do {
1193 slot_size = MIN(kvm_max_slot_size, size);
1194 mem = kvm_alloc_slot(kml);
1195 mem->memory_size = slot_size;
1196 mem->start_addr = start_addr;
1197 mem->ram = ram;
1198 mem->flags = kvm_mem_flags(mr);
1200 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1202 * Reallocate the bmap; it means it doesn't disappear in
1203 * middle of a migrate.
1205 kvm_memslot_init_dirty_bitmap(mem);
1207 err = kvm_set_user_memory_region(kml, mem, true);
1208 if (err) {
1209 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
1210 strerror(-err));
1211 abort();
1213 start_addr += slot_size;
1214 ram += slot_size;
1215 size -= slot_size;
1216 } while (size);
1218 out:
1219 kvm_slots_unlock(kml);
1222 static void kvm_region_add(MemoryListener *listener,
1223 MemoryRegionSection *section)
1225 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1227 memory_region_ref(section->mr);
1228 kvm_set_phys_mem(kml, section, true);
1231 static void kvm_region_del(MemoryListener *listener,
1232 MemoryRegionSection *section)
1234 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1236 kvm_set_phys_mem(kml, section, false);
1237 memory_region_unref(section->mr);
1240 static void kvm_log_sync(MemoryListener *listener,
1241 MemoryRegionSection *section)
1243 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1244 int r;
1246 kvm_slots_lock(kml);
1247 r = kvm_physical_sync_dirty_bitmap(kml, section);
1248 kvm_slots_unlock(kml);
1249 if (r < 0) {
1250 abort();
1254 static void kvm_log_clear(MemoryListener *listener,
1255 MemoryRegionSection *section)
1257 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1258 int r;
1260 r = kvm_physical_log_clear(kml, section);
1261 if (r < 0) {
1262 error_report_once("%s: kvm log clear failed: mr=%s "
1263 "offset=%"HWADDR_PRIx" size=%"PRIx64, __func__,
1264 section->mr->name, section->offset_within_region,
1265 int128_get64(section->size));
1266 abort();
1270 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
1271 MemoryRegionSection *section,
1272 bool match_data, uint64_t data,
1273 EventNotifier *e)
1275 int fd = event_notifier_get_fd(e);
1276 int r;
1278 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
1279 data, true, int128_get64(section->size),
1280 match_data);
1281 if (r < 0) {
1282 fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1283 __func__, strerror(-r), -r);
1284 abort();
1288 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
1289 MemoryRegionSection *section,
1290 bool match_data, uint64_t data,
1291 EventNotifier *e)
1293 int fd = event_notifier_get_fd(e);
1294 int r;
1296 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
1297 data, false, int128_get64(section->size),
1298 match_data);
1299 if (r < 0) {
1300 fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1301 __func__, strerror(-r), -r);
1302 abort();
1306 static void kvm_io_ioeventfd_add(MemoryListener *listener,
1307 MemoryRegionSection *section,
1308 bool match_data, uint64_t data,
1309 EventNotifier *e)
1311 int fd = event_notifier_get_fd(e);
1312 int r;
1314 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
1315 data, true, int128_get64(section->size),
1316 match_data);
1317 if (r < 0) {
1318 fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1319 __func__, strerror(-r), -r);
1320 abort();
1324 static void kvm_io_ioeventfd_del(MemoryListener *listener,
1325 MemoryRegionSection *section,
1326 bool match_data, uint64_t data,
1327 EventNotifier *e)
1330 int fd = event_notifier_get_fd(e);
1331 int r;
1333 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
1334 data, false, int128_get64(section->size),
1335 match_data);
1336 if (r < 0) {
1337 fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1338 __func__, strerror(-r), -r);
1339 abort();
1343 void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
1344 AddressSpace *as, int as_id)
1346 int i;
1348 qemu_mutex_init(&kml->slots_lock);
1349 kml->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
1350 kml->as_id = as_id;
1352 for (i = 0; i < s->nr_slots; i++) {
1353 kml->slots[i].slot = i;
1356 kml->listener.region_add = kvm_region_add;
1357 kml->listener.region_del = kvm_region_del;
1358 kml->listener.log_start = kvm_log_start;
1359 kml->listener.log_stop = kvm_log_stop;
1360 kml->listener.log_sync = kvm_log_sync;
1361 kml->listener.log_clear = kvm_log_clear;
1362 kml->listener.priority = 10;
1364 memory_listener_register(&kml->listener, as);
1366 for (i = 0; i < s->nr_as; ++i) {
1367 if (!s->as[i].as) {
1368 s->as[i].as = as;
1369 s->as[i].ml = kml;
1370 break;
1375 static MemoryListener kvm_io_listener = {
1376 .eventfd_add = kvm_io_ioeventfd_add,
1377 .eventfd_del = kvm_io_ioeventfd_del,
1378 .priority = 10,
1381 int kvm_set_irq(KVMState *s, int irq, int level)
1383 struct kvm_irq_level event;
1384 int ret;
1386 assert(kvm_async_interrupts_enabled());
1388 event.level = level;
1389 event.irq = irq;
1390 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
1391 if (ret < 0) {
1392 perror("kvm_set_irq");
1393 abort();
1396 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
1399 #ifdef KVM_CAP_IRQ_ROUTING
1400 typedef struct KVMMSIRoute {
1401 struct kvm_irq_routing_entry kroute;
1402 QTAILQ_ENTRY(KVMMSIRoute) entry;
1403 } KVMMSIRoute;
1405 static void set_gsi(KVMState *s, unsigned int gsi)
1407 set_bit(gsi, s->used_gsi_bitmap);
1410 static void clear_gsi(KVMState *s, unsigned int gsi)
1412 clear_bit(gsi, s->used_gsi_bitmap);
1415 void kvm_init_irq_routing(KVMState *s)
1417 int gsi_count, i;
1419 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
1420 if (gsi_count > 0) {
1421 /* Round up so we can search ints using ffs */
1422 s->used_gsi_bitmap = bitmap_new(gsi_count);
1423 s->gsi_count = gsi_count;
1426 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
1427 s->nr_allocated_irq_routes = 0;
1429 if (!kvm_direct_msi_allowed) {
1430 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
1431 QTAILQ_INIT(&s->msi_hashtab[i]);
1435 kvm_arch_init_irq_routing(s);
1438 void kvm_irqchip_commit_routes(KVMState *s)
1440 int ret;
1442 if (kvm_gsi_direct_mapping()) {
1443 return;
1446 if (!kvm_gsi_routing_enabled()) {
1447 return;
1450 s->irq_routes->flags = 0;
1451 trace_kvm_irqchip_commit_routes();
1452 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1453 assert(ret == 0);
1456 static void kvm_add_routing_entry(KVMState *s,
1457 struct kvm_irq_routing_entry *entry)
1459 struct kvm_irq_routing_entry *new;
1460 int n, size;
1462 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1463 n = s->nr_allocated_irq_routes * 2;
1464 if (n < 64) {
1465 n = 64;
1467 size = sizeof(struct kvm_irq_routing);
1468 size += n * sizeof(*new);
1469 s->irq_routes = g_realloc(s->irq_routes, size);
1470 s->nr_allocated_irq_routes = n;
1472 n = s->irq_routes->nr++;
1473 new = &s->irq_routes->entries[n];
1475 *new = *entry;
1477 set_gsi(s, entry->gsi);
1480 static int kvm_update_routing_entry(KVMState *s,
1481 struct kvm_irq_routing_entry *new_entry)
1483 struct kvm_irq_routing_entry *entry;
1484 int n;
1486 for (n = 0; n < s->irq_routes->nr; n++) {
1487 entry = &s->irq_routes->entries[n];
1488 if (entry->gsi != new_entry->gsi) {
1489 continue;
1492 if(!memcmp(entry, new_entry, sizeof *entry)) {
1493 return 0;
1496 *entry = *new_entry;
1498 return 0;
1501 return -ESRCH;
1504 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1506 struct kvm_irq_routing_entry e = {};
1508 assert(pin < s->gsi_count);
1510 e.gsi = irq;
1511 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1512 e.flags = 0;
1513 e.u.irqchip.irqchip = irqchip;
1514 e.u.irqchip.pin = pin;
1515 kvm_add_routing_entry(s, &e);
1518 void kvm_irqchip_release_virq(KVMState *s, int virq)
1520 struct kvm_irq_routing_entry *e;
1521 int i;
1523 if (kvm_gsi_direct_mapping()) {
1524 return;
1527 for (i = 0; i < s->irq_routes->nr; i++) {
1528 e = &s->irq_routes->entries[i];
1529 if (e->gsi == virq) {
1530 s->irq_routes->nr--;
1531 *e = s->irq_routes->entries[s->irq_routes->nr];
1534 clear_gsi(s, virq);
1535 kvm_arch_release_virq_post(virq);
1536 trace_kvm_irqchip_release_virq(virq);
1539 void kvm_irqchip_add_change_notifier(Notifier *n)
1541 notifier_list_add(&kvm_irqchip_change_notifiers, n);
1544 void kvm_irqchip_remove_change_notifier(Notifier *n)
1546 notifier_remove(n);
1549 void kvm_irqchip_change_notify(void)
1551 notifier_list_notify(&kvm_irqchip_change_notifiers, NULL);
1554 static unsigned int kvm_hash_msi(uint32_t data)
1556 /* This is optimized for IA32 MSI layout. However, no other arch shall
1557 * repeat the mistake of not providing a direct MSI injection API. */
1558 return data & 0xff;
1561 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1563 KVMMSIRoute *route, *next;
1564 unsigned int hash;
1566 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1567 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1568 kvm_irqchip_release_virq(s, route->kroute.gsi);
1569 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1570 g_free(route);
1575 static int kvm_irqchip_get_virq(KVMState *s)
1577 int next_virq;
1580 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1581 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1582 * number can succeed even though a new route entry cannot be added.
1583 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1585 if (!kvm_direct_msi_allowed && s->irq_routes->nr == s->gsi_count) {
1586 kvm_flush_dynamic_msi_routes(s);
1589 /* Return the lowest unused GSI in the bitmap */
1590 next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
1591 if (next_virq >= s->gsi_count) {
1592 return -ENOSPC;
1593 } else {
1594 return next_virq;
1598 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1600 unsigned int hash = kvm_hash_msi(msg.data);
1601 KVMMSIRoute *route;
1603 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1604 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1605 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1606 route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1607 return route;
1610 return NULL;
1613 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1615 struct kvm_msi msi;
1616 KVMMSIRoute *route;
1618 if (kvm_direct_msi_allowed) {
1619 msi.address_lo = (uint32_t)msg.address;
1620 msi.address_hi = msg.address >> 32;
1621 msi.data = le32_to_cpu(msg.data);
1622 msi.flags = 0;
1623 memset(msi.pad, 0, sizeof(msi.pad));
1625 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1628 route = kvm_lookup_msi_route(s, msg);
1629 if (!route) {
1630 int virq;
1632 virq = kvm_irqchip_get_virq(s);
1633 if (virq < 0) {
1634 return virq;
1637 route = g_malloc0(sizeof(KVMMSIRoute));
1638 route->kroute.gsi = virq;
1639 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1640 route->kroute.flags = 0;
1641 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1642 route->kroute.u.msi.address_hi = msg.address >> 32;
1643 route->kroute.u.msi.data = le32_to_cpu(msg.data);
1645 kvm_add_routing_entry(s, &route->kroute);
1646 kvm_irqchip_commit_routes(s);
1648 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1649 entry);
1652 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1654 return kvm_set_irq(s, route->kroute.gsi, 1);
1657 int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
1659 struct kvm_irq_routing_entry kroute = {};
1660 int virq;
1661 MSIMessage msg = {0, 0};
1663 if (pci_available && dev) {
1664 msg = pci_get_msi_message(dev, vector);
1667 if (kvm_gsi_direct_mapping()) {
1668 return kvm_arch_msi_data_to_gsi(msg.data);
1671 if (!kvm_gsi_routing_enabled()) {
1672 return -ENOSYS;
1675 virq = kvm_irqchip_get_virq(s);
1676 if (virq < 0) {
1677 return virq;
1680 kroute.gsi = virq;
1681 kroute.type = KVM_IRQ_ROUTING_MSI;
1682 kroute.flags = 0;
1683 kroute.u.msi.address_lo = (uint32_t)msg.address;
1684 kroute.u.msi.address_hi = msg.address >> 32;
1685 kroute.u.msi.data = le32_to_cpu(msg.data);
1686 if (pci_available && kvm_msi_devid_required()) {
1687 kroute.flags = KVM_MSI_VALID_DEVID;
1688 kroute.u.msi.devid = pci_requester_id(dev);
1690 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1691 kvm_irqchip_release_virq(s, virq);
1692 return -EINVAL;
1695 trace_kvm_irqchip_add_msi_route(dev ? dev->name : (char *)"N/A",
1696 vector, virq);
1698 kvm_add_routing_entry(s, &kroute);
1699 kvm_arch_add_msi_route_post(&kroute, vector, dev);
1700 kvm_irqchip_commit_routes(s);
1702 return virq;
1705 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
1706 PCIDevice *dev)
1708 struct kvm_irq_routing_entry kroute = {};
1710 if (kvm_gsi_direct_mapping()) {
1711 return 0;
1714 if (!kvm_irqchip_in_kernel()) {
1715 return -ENOSYS;
1718 kroute.gsi = virq;
1719 kroute.type = KVM_IRQ_ROUTING_MSI;
1720 kroute.flags = 0;
1721 kroute.u.msi.address_lo = (uint32_t)msg.address;
1722 kroute.u.msi.address_hi = msg.address >> 32;
1723 kroute.u.msi.data = le32_to_cpu(msg.data);
1724 if (pci_available && kvm_msi_devid_required()) {
1725 kroute.flags = KVM_MSI_VALID_DEVID;
1726 kroute.u.msi.devid = pci_requester_id(dev);
1728 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1729 return -EINVAL;
1732 trace_kvm_irqchip_update_msi_route(virq);
1734 return kvm_update_routing_entry(s, &kroute);
1737 static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
1738 EventNotifier *resample, int virq,
1739 bool assign)
1741 int fd = event_notifier_get_fd(event);
1742 int rfd = resample ? event_notifier_get_fd(resample) : -1;
1744 struct kvm_irqfd irqfd = {
1745 .fd = fd,
1746 .gsi = virq,
1747 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1750 if (rfd != -1) {
1751 assert(assign);
1752 if (kvm_irqchip_is_split()) {
1754 * When the slow irqchip (e.g. IOAPIC) is in the
1755 * userspace, KVM kernel resamplefd will not work because
1756 * the EOI of the interrupt will be delivered to userspace
1757 * instead, so the KVM kernel resamplefd kick will be
1758 * skipped. The userspace here mimics what the kernel
1759 * provides with resamplefd, remember the resamplefd and
1760 * kick it when we receive EOI of this IRQ.
1762 * This is hackery because IOAPIC is mostly bypassed
1763 * (except EOI broadcasts) when irqfd is used. However
1764 * this can bring much performance back for split irqchip
1765 * with INTx IRQs (for VFIO, this gives 93% perf of the
1766 * full fast path, which is 46% perf boost comparing to
1767 * the INTx slow path).
1769 kvm_resample_fd_insert(virq, resample);
1770 } else {
1771 irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1772 irqfd.resamplefd = rfd;
1774 } else if (!assign) {
1775 if (kvm_irqchip_is_split()) {
1776 kvm_resample_fd_remove(virq);
1780 if (!kvm_irqfds_enabled()) {
1781 return -ENOSYS;
1784 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1787 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1789 struct kvm_irq_routing_entry kroute = {};
1790 int virq;
1792 if (!kvm_gsi_routing_enabled()) {
1793 return -ENOSYS;
1796 virq = kvm_irqchip_get_virq(s);
1797 if (virq < 0) {
1798 return virq;
1801 kroute.gsi = virq;
1802 kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1803 kroute.flags = 0;
1804 kroute.u.adapter.summary_addr = adapter->summary_addr;
1805 kroute.u.adapter.ind_addr = adapter->ind_addr;
1806 kroute.u.adapter.summary_offset = adapter->summary_offset;
1807 kroute.u.adapter.ind_offset = adapter->ind_offset;
1808 kroute.u.adapter.adapter_id = adapter->adapter_id;
1810 kvm_add_routing_entry(s, &kroute);
1812 return virq;
1815 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1817 struct kvm_irq_routing_entry kroute = {};
1818 int virq;
1820 if (!kvm_gsi_routing_enabled()) {
1821 return -ENOSYS;
1823 if (!kvm_check_extension(s, KVM_CAP_HYPERV_SYNIC)) {
1824 return -ENOSYS;
1826 virq = kvm_irqchip_get_virq(s);
1827 if (virq < 0) {
1828 return virq;
1831 kroute.gsi = virq;
1832 kroute.type = KVM_IRQ_ROUTING_HV_SINT;
1833 kroute.flags = 0;
1834 kroute.u.hv_sint.vcpu = vcpu;
1835 kroute.u.hv_sint.sint = sint;
1837 kvm_add_routing_entry(s, &kroute);
1838 kvm_irqchip_commit_routes(s);
1840 return virq;
1843 #else /* !KVM_CAP_IRQ_ROUTING */
1845 void kvm_init_irq_routing(KVMState *s)
1849 void kvm_irqchip_release_virq(KVMState *s, int virq)
1853 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1855 abort();
1858 int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
1860 return -ENOSYS;
1863 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1865 return -ENOSYS;
1868 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1870 return -ENOSYS;
1873 static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
1874 EventNotifier *resample, int virq,
1875 bool assign)
1877 abort();
1880 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1882 return -ENOSYS;
1884 #endif /* !KVM_CAP_IRQ_ROUTING */
1886 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1887 EventNotifier *rn, int virq)
1889 return kvm_irqchip_assign_irqfd(s, n, rn, virq, true);
1892 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1893 int virq)
1895 return kvm_irqchip_assign_irqfd(s, n, NULL, virq, false);
1898 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1899 EventNotifier *rn, qemu_irq irq)
1901 gpointer key, gsi;
1902 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1904 if (!found) {
1905 return -ENXIO;
1907 return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
1910 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
1911 qemu_irq irq)
1913 gpointer key, gsi;
1914 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1916 if (!found) {
1917 return -ENXIO;
1919 return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
1922 void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
1924 g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
1927 static void kvm_irqchip_create(KVMState *s)
1929 int ret;
1931 assert(s->kernel_irqchip_split != ON_OFF_AUTO_AUTO);
1932 if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
1934 } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
1935 ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
1936 if (ret < 0) {
1937 fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
1938 exit(1);
1940 } else {
1941 return;
1944 /* First probe and see if there's a arch-specific hook to create the
1945 * in-kernel irqchip for us */
1946 ret = kvm_arch_irqchip_create(s);
1947 if (ret == 0) {
1948 if (s->kernel_irqchip_split == ON_OFF_AUTO_ON) {
1949 perror("Split IRQ chip mode not supported.");
1950 exit(1);
1951 } else {
1952 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1955 if (ret < 0) {
1956 fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
1957 exit(1);
1960 kvm_kernel_irqchip = true;
1961 /* If we have an in-kernel IRQ chip then we must have asynchronous
1962 * interrupt delivery (though the reverse is not necessarily true)
1964 kvm_async_interrupts_allowed = true;
1965 kvm_halt_in_kernel_allowed = true;
1967 kvm_init_irq_routing(s);
1969 s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
1972 /* Find number of supported CPUs using the recommended
1973 * procedure from the kernel API documentation to cope with
1974 * older kernels that may be missing capabilities.
1976 static int kvm_recommended_vcpus(KVMState *s)
1978 int ret = kvm_vm_check_extension(s, KVM_CAP_NR_VCPUS);
1979 return (ret) ? ret : 4;
1982 static int kvm_max_vcpus(KVMState *s)
1984 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1985 return (ret) ? ret : kvm_recommended_vcpus(s);
1988 static int kvm_max_vcpu_id(KVMState *s)
1990 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
1991 return (ret) ? ret : kvm_max_vcpus(s);
1994 bool kvm_vcpu_id_is_valid(int vcpu_id)
1996 KVMState *s = KVM_STATE(current_accel());
1997 return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
2000 static int kvm_init(MachineState *ms)
2002 MachineClass *mc = MACHINE_GET_CLASS(ms);
2003 static const char upgrade_note[] =
2004 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
2005 "(see http://sourceforge.net/projects/kvm).\n";
2006 struct {
2007 const char *name;
2008 int num;
2009 } num_cpus[] = {
2010 { "SMP", ms->smp.cpus },
2011 { "hotpluggable", ms->smp.max_cpus },
2012 { NULL, }
2013 }, *nc = num_cpus;
2014 int soft_vcpus_limit, hard_vcpus_limit;
2015 KVMState *s;
2016 const KVMCapabilityInfo *missing_cap;
2017 int ret;
2018 int type = 0;
2019 uint64_t dirty_log_manual_caps;
2021 s = KVM_STATE(ms->accelerator);
2024 * On systems where the kernel can support different base page
2025 * sizes, host page size may be different from TARGET_PAGE_SIZE,
2026 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
2027 * page size for the system though.
2029 assert(TARGET_PAGE_SIZE <= qemu_real_host_page_size);
2031 s->sigmask_len = 8;
2033 #ifdef KVM_CAP_SET_GUEST_DEBUG
2034 QTAILQ_INIT(&s->kvm_sw_breakpoints);
2035 #endif
2036 QLIST_INIT(&s->kvm_parked_vcpus);
2037 s->vmfd = -1;
2038 s->fd = qemu_open_old("/dev/kvm", O_RDWR);
2039 if (s->fd == -1) {
2040 fprintf(stderr, "Could not access KVM kernel module: %m\n");
2041 ret = -errno;
2042 goto err;
2045 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
2046 if (ret < KVM_API_VERSION) {
2047 if (ret >= 0) {
2048 ret = -EINVAL;
2050 fprintf(stderr, "kvm version too old\n");
2051 goto err;
2054 if (ret > KVM_API_VERSION) {
2055 ret = -EINVAL;
2056 fprintf(stderr, "kvm version not supported\n");
2057 goto err;
2060 kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
2061 s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
2063 /* If unspecified, use the default value */
2064 if (!s->nr_slots) {
2065 s->nr_slots = 32;
2068 s->nr_as = kvm_check_extension(s, KVM_CAP_MULTI_ADDRESS_SPACE);
2069 if (s->nr_as <= 1) {
2070 s->nr_as = 1;
2072 s->as = g_new0(struct KVMAs, s->nr_as);
2074 if (object_property_find(OBJECT(current_machine), "kvm-type")) {
2075 g_autofree char *kvm_type = object_property_get_str(OBJECT(current_machine),
2076 "kvm-type",
2077 &error_abort);
2078 type = mc->kvm_type(ms, kvm_type);
2081 do {
2082 ret = kvm_ioctl(s, KVM_CREATE_VM, type);
2083 } while (ret == -EINTR);
2085 if (ret < 0) {
2086 fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
2087 strerror(-ret));
2089 #ifdef TARGET_S390X
2090 if (ret == -EINVAL) {
2091 fprintf(stderr,
2092 "Host kernel setup problem detected. Please verify:\n");
2093 fprintf(stderr, "- for kernels supporting the switch_amode or"
2094 " user_mode parameters, whether\n");
2095 fprintf(stderr,
2096 " user space is running in primary address space\n");
2097 fprintf(stderr,
2098 "- for kernels supporting the vm.allocate_pgste sysctl, "
2099 "whether it is enabled\n");
2101 #endif
2102 goto err;
2105 s->vmfd = ret;
2107 /* check the vcpu limits */
2108 soft_vcpus_limit = kvm_recommended_vcpus(s);
2109 hard_vcpus_limit = kvm_max_vcpus(s);
2111 while (nc->name) {
2112 if (nc->num > soft_vcpus_limit) {
2113 warn_report("Number of %s cpus requested (%d) exceeds "
2114 "the recommended cpus supported by KVM (%d)",
2115 nc->name, nc->num, soft_vcpus_limit);
2117 if (nc->num > hard_vcpus_limit) {
2118 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
2119 "the maximum cpus supported by KVM (%d)\n",
2120 nc->name, nc->num, hard_vcpus_limit);
2121 exit(1);
2124 nc++;
2127 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
2128 if (!missing_cap) {
2129 missing_cap =
2130 kvm_check_extension_list(s, kvm_arch_required_capabilities);
2132 if (missing_cap) {
2133 ret = -EINVAL;
2134 fprintf(stderr, "kvm does not support %s\n%s",
2135 missing_cap->name, upgrade_note);
2136 goto err;
2139 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
2140 s->coalesced_pio = s->coalesced_mmio &&
2141 kvm_check_extension(s, KVM_CAP_COALESCED_PIO);
2143 dirty_log_manual_caps =
2144 kvm_check_extension(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
2145 dirty_log_manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
2146 KVM_DIRTY_LOG_INITIALLY_SET);
2147 s->manual_dirty_log_protect = dirty_log_manual_caps;
2148 if (dirty_log_manual_caps) {
2149 ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0,
2150 dirty_log_manual_caps);
2151 if (ret) {
2152 warn_report("Trying to enable capability %"PRIu64" of "
2153 "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
2154 "Falling back to the legacy mode. ",
2155 dirty_log_manual_caps);
2156 s->manual_dirty_log_protect = 0;
2160 #ifdef KVM_CAP_VCPU_EVENTS
2161 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
2162 #endif
2164 s->robust_singlestep =
2165 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
2167 #ifdef KVM_CAP_DEBUGREGS
2168 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
2169 #endif
2171 s->max_nested_state_len = kvm_check_extension(s, KVM_CAP_NESTED_STATE);
2173 #ifdef KVM_CAP_IRQ_ROUTING
2174 kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
2175 #endif
2177 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
2179 s->irq_set_ioctl = KVM_IRQ_LINE;
2180 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
2181 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
2184 kvm_readonly_mem_allowed =
2185 (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
2187 kvm_eventfds_allowed =
2188 (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
2190 kvm_irqfds_allowed =
2191 (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
2193 kvm_resamplefds_allowed =
2194 (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
2196 kvm_vm_attributes_allowed =
2197 (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
2199 kvm_ioeventfd_any_length_allowed =
2200 (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
2202 kvm_state = s;
2205 * if memory encryption object is specified then initialize the memory
2206 * encryption context.
2208 if (ms->memory_encryption) {
2209 kvm_state->memcrypt_handle = sev_guest_init(ms->memory_encryption);
2210 if (!kvm_state->memcrypt_handle) {
2211 ret = -1;
2212 goto err;
2215 kvm_state->memcrypt_encrypt_data = sev_encrypt_data;
2218 ret = kvm_arch_init(ms, s);
2219 if (ret < 0) {
2220 goto err;
2223 if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
2224 s->kernel_irqchip_split = mc->default_kernel_irqchip_split ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
2227 qemu_register_reset(kvm_unpoison_all, NULL);
2229 if (s->kernel_irqchip_allowed) {
2230 kvm_irqchip_create(s);
2233 if (kvm_eventfds_allowed) {
2234 s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
2235 s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
2237 s->memory_listener.listener.coalesced_io_add = kvm_coalesce_mmio_region;
2238 s->memory_listener.listener.coalesced_io_del = kvm_uncoalesce_mmio_region;
2240 kvm_memory_listener_register(s, &s->memory_listener,
2241 &address_space_memory, 0);
2242 if (kvm_eventfds_allowed) {
2243 memory_listener_register(&kvm_io_listener,
2244 &address_space_io);
2246 memory_listener_register(&kvm_coalesced_pio_listener,
2247 &address_space_io);
2249 s->many_ioeventfds = kvm_check_many_ioeventfds();
2251 s->sync_mmu = !!kvm_vm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2252 if (!s->sync_mmu) {
2253 ret = ram_block_discard_disable(true);
2254 assert(!ret);
2257 cpus_register_accel(&kvm_cpus);
2258 return 0;
2260 err:
2261 assert(ret < 0);
2262 if (s->vmfd >= 0) {
2263 close(s->vmfd);
2265 if (s->fd != -1) {
2266 close(s->fd);
2268 g_free(s->memory_listener.slots);
2270 return ret;
2273 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
2275 s->sigmask_len = sigmask_len;
2278 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
2279 int size, uint32_t count)
2281 int i;
2282 uint8_t *ptr = data;
2284 for (i = 0; i < count; i++) {
2285 address_space_rw(&address_space_io, port, attrs,
2286 ptr, size,
2287 direction == KVM_EXIT_IO_OUT);
2288 ptr += size;
2292 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
2294 fprintf(stderr, "KVM internal error. Suberror: %d\n",
2295 run->internal.suberror);
2297 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
2298 int i;
2300 for (i = 0; i < run->internal.ndata; ++i) {
2301 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
2302 i, (uint64_t)run->internal.data[i]);
2305 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
2306 fprintf(stderr, "emulation failure\n");
2307 if (!kvm_arch_stop_on_emulation_error(cpu)) {
2308 cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2309 return EXCP_INTERRUPT;
2312 /* FIXME: Should trigger a qmp message to let management know
2313 * something went wrong.
2315 return -1;
2318 void kvm_flush_coalesced_mmio_buffer(void)
2320 KVMState *s = kvm_state;
2322 if (s->coalesced_flush_in_progress) {
2323 return;
2326 s->coalesced_flush_in_progress = true;
2328 if (s->coalesced_mmio_ring) {
2329 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
2330 while (ring->first != ring->last) {
2331 struct kvm_coalesced_mmio *ent;
2333 ent = &ring->coalesced_mmio[ring->first];
2335 if (ent->pio == 1) {
2336 address_space_write(&address_space_io, ent->phys_addr,
2337 MEMTXATTRS_UNSPECIFIED, ent->data,
2338 ent->len);
2339 } else {
2340 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
2342 smp_wmb();
2343 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
2347 s->coalesced_flush_in_progress = false;
2350 static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
2352 if (!cpu->vcpu_dirty) {
2353 kvm_arch_get_registers(cpu);
2354 cpu->vcpu_dirty = true;
2358 void kvm_cpu_synchronize_state(CPUState *cpu)
2360 if (!cpu->vcpu_dirty) {
2361 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
2365 static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
2367 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
2368 cpu->vcpu_dirty = false;
2371 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
2373 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
2376 static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
2378 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
2379 cpu->vcpu_dirty = false;
2382 void kvm_cpu_synchronize_post_init(CPUState *cpu)
2384 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
2387 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
2389 cpu->vcpu_dirty = true;
2392 void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
2394 run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
2397 #ifdef KVM_HAVE_MCE_INJECTION
2398 static __thread void *pending_sigbus_addr;
2399 static __thread int pending_sigbus_code;
2400 static __thread bool have_sigbus_pending;
2401 #endif
2403 static void kvm_cpu_kick(CPUState *cpu)
2405 qatomic_set(&cpu->kvm_run->immediate_exit, 1);
2408 static void kvm_cpu_kick_self(void)
2410 if (kvm_immediate_exit) {
2411 kvm_cpu_kick(current_cpu);
2412 } else {
2413 qemu_cpu_kick_self();
2417 static void kvm_eat_signals(CPUState *cpu)
2419 struct timespec ts = { 0, 0 };
2420 siginfo_t siginfo;
2421 sigset_t waitset;
2422 sigset_t chkset;
2423 int r;
2425 if (kvm_immediate_exit) {
2426 qatomic_set(&cpu->kvm_run->immediate_exit, 0);
2427 /* Write kvm_run->immediate_exit before the cpu->exit_request
2428 * write in kvm_cpu_exec.
2430 smp_wmb();
2431 return;
2434 sigemptyset(&waitset);
2435 sigaddset(&waitset, SIG_IPI);
2437 do {
2438 r = sigtimedwait(&waitset, &siginfo, &ts);
2439 if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
2440 perror("sigtimedwait");
2441 exit(1);
2444 r = sigpending(&chkset);
2445 if (r == -1) {
2446 perror("sigpending");
2447 exit(1);
2449 } while (sigismember(&chkset, SIG_IPI));
2452 int kvm_cpu_exec(CPUState *cpu)
2454 struct kvm_run *run = cpu->kvm_run;
2455 int ret, run_ret;
2457 DPRINTF("kvm_cpu_exec()\n");
2459 if (kvm_arch_process_async_events(cpu)) {
2460 qatomic_set(&cpu->exit_request, 0);
2461 return EXCP_HLT;
2464 qemu_mutex_unlock_iothread();
2465 cpu_exec_start(cpu);
2467 do {
2468 MemTxAttrs attrs;
2470 if (cpu->vcpu_dirty) {
2471 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
2472 cpu->vcpu_dirty = false;
2475 kvm_arch_pre_run(cpu, run);
2476 if (qatomic_read(&cpu->exit_request)) {
2477 DPRINTF("interrupt exit requested\n");
2479 * KVM requires us to reenter the kernel after IO exits to complete
2480 * instruction emulation. This self-signal will ensure that we
2481 * leave ASAP again.
2483 kvm_cpu_kick_self();
2486 /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2487 * Matching barrier in kvm_eat_signals.
2489 smp_rmb();
2491 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
2493 attrs = kvm_arch_post_run(cpu, run);
2495 #ifdef KVM_HAVE_MCE_INJECTION
2496 if (unlikely(have_sigbus_pending)) {
2497 qemu_mutex_lock_iothread();
2498 kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
2499 pending_sigbus_addr);
2500 have_sigbus_pending = false;
2501 qemu_mutex_unlock_iothread();
2503 #endif
2505 if (run_ret < 0) {
2506 if (run_ret == -EINTR || run_ret == -EAGAIN) {
2507 DPRINTF("io window exit\n");
2508 kvm_eat_signals(cpu);
2509 ret = EXCP_INTERRUPT;
2510 break;
2512 fprintf(stderr, "error: kvm run failed %s\n",
2513 strerror(-run_ret));
2514 #ifdef TARGET_PPC
2515 if (run_ret == -EBUSY) {
2516 fprintf(stderr,
2517 "This is probably because your SMT is enabled.\n"
2518 "VCPU can only run on primary threads with all "
2519 "secondary threads offline.\n");
2521 #endif
2522 ret = -1;
2523 break;
2526 trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
2527 switch (run->exit_reason) {
2528 case KVM_EXIT_IO:
2529 DPRINTF("handle_io\n");
2530 /* Called outside BQL */
2531 kvm_handle_io(run->io.port, attrs,
2532 (uint8_t *)run + run->io.data_offset,
2533 run->io.direction,
2534 run->io.size,
2535 run->io.count);
2536 ret = 0;
2537 break;
2538 case KVM_EXIT_MMIO:
2539 DPRINTF("handle_mmio\n");
2540 /* Called outside BQL */
2541 address_space_rw(&address_space_memory,
2542 run->mmio.phys_addr, attrs,
2543 run->mmio.data,
2544 run->mmio.len,
2545 run->mmio.is_write);
2546 ret = 0;
2547 break;
2548 case KVM_EXIT_IRQ_WINDOW_OPEN:
2549 DPRINTF("irq_window_open\n");
2550 ret = EXCP_INTERRUPT;
2551 break;
2552 case KVM_EXIT_SHUTDOWN:
2553 DPRINTF("shutdown\n");
2554 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
2555 ret = EXCP_INTERRUPT;
2556 break;
2557 case KVM_EXIT_UNKNOWN:
2558 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
2559 (uint64_t)run->hw.hardware_exit_reason);
2560 ret = -1;
2561 break;
2562 case KVM_EXIT_INTERNAL_ERROR:
2563 ret = kvm_handle_internal_error(cpu, run);
2564 break;
2565 case KVM_EXIT_SYSTEM_EVENT:
2566 switch (run->system_event.type) {
2567 case KVM_SYSTEM_EVENT_SHUTDOWN:
2568 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
2569 ret = EXCP_INTERRUPT;
2570 break;
2571 case KVM_SYSTEM_EVENT_RESET:
2572 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
2573 ret = EXCP_INTERRUPT;
2574 break;
2575 case KVM_SYSTEM_EVENT_CRASH:
2576 kvm_cpu_synchronize_state(cpu);
2577 qemu_mutex_lock_iothread();
2578 qemu_system_guest_panicked(cpu_get_crash_info(cpu));
2579 qemu_mutex_unlock_iothread();
2580 ret = 0;
2581 break;
2582 default:
2583 DPRINTF("kvm_arch_handle_exit\n");
2584 ret = kvm_arch_handle_exit(cpu, run);
2585 break;
2587 break;
2588 default:
2589 DPRINTF("kvm_arch_handle_exit\n");
2590 ret = kvm_arch_handle_exit(cpu, run);
2591 break;
2593 } while (ret == 0);
2595 cpu_exec_end(cpu);
2596 qemu_mutex_lock_iothread();
2598 if (ret < 0) {
2599 cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2600 vm_stop(RUN_STATE_INTERNAL_ERROR);
2603 qatomic_set(&cpu->exit_request, 0);
2604 return ret;
2607 int kvm_ioctl(KVMState *s, int type, ...)
2609 int ret;
2610 void *arg;
2611 va_list ap;
2613 va_start(ap, type);
2614 arg = va_arg(ap, void *);
2615 va_end(ap);
2617 trace_kvm_ioctl(type, arg);
2618 ret = ioctl(s->fd, type, arg);
2619 if (ret == -1) {
2620 ret = -errno;
2622 return ret;
2625 int kvm_vm_ioctl(KVMState *s, int type, ...)
2627 int ret;
2628 void *arg;
2629 va_list ap;
2631 va_start(ap, type);
2632 arg = va_arg(ap, void *);
2633 va_end(ap);
2635 trace_kvm_vm_ioctl(type, arg);
2636 ret = ioctl(s->vmfd, type, arg);
2637 if (ret == -1) {
2638 ret = -errno;
2640 return ret;
2643 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
2645 int ret;
2646 void *arg;
2647 va_list ap;
2649 va_start(ap, type);
2650 arg = va_arg(ap, void *);
2651 va_end(ap);
2653 trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
2654 ret = ioctl(cpu->kvm_fd, type, arg);
2655 if (ret == -1) {
2656 ret = -errno;
2658 return ret;
2661 int kvm_device_ioctl(int fd, int type, ...)
2663 int ret;
2664 void *arg;
2665 va_list ap;
2667 va_start(ap, type);
2668 arg = va_arg(ap, void *);
2669 va_end(ap);
2671 trace_kvm_device_ioctl(fd, type, arg);
2672 ret = ioctl(fd, type, arg);
2673 if (ret == -1) {
2674 ret = -errno;
2676 return ret;
2679 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
2681 int ret;
2682 struct kvm_device_attr attribute = {
2683 .group = group,
2684 .attr = attr,
2687 if (!kvm_vm_attributes_allowed) {
2688 return 0;
2691 ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
2692 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2693 return ret ? 0 : 1;
2696 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
2698 struct kvm_device_attr attribute = {
2699 .group = group,
2700 .attr = attr,
2701 .flags = 0,
2704 return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
2707 int kvm_device_access(int fd, int group, uint64_t attr,
2708 void *val, bool write, Error **errp)
2710 struct kvm_device_attr kvmattr;
2711 int err;
2713 kvmattr.flags = 0;
2714 kvmattr.group = group;
2715 kvmattr.attr = attr;
2716 kvmattr.addr = (uintptr_t)val;
2718 err = kvm_device_ioctl(fd,
2719 write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
2720 &kvmattr);
2721 if (err < 0) {
2722 error_setg_errno(errp, -err,
2723 "KVM_%s_DEVICE_ATTR failed: Group %d "
2724 "attr 0x%016" PRIx64,
2725 write ? "SET" : "GET", group, attr);
2727 return err;
2730 bool kvm_has_sync_mmu(void)
2732 return kvm_state->sync_mmu;
2735 int kvm_has_vcpu_events(void)
2737 return kvm_state->vcpu_events;
2740 int kvm_has_robust_singlestep(void)
2742 return kvm_state->robust_singlestep;
2745 int kvm_has_debugregs(void)
2747 return kvm_state->debugregs;
2750 int kvm_max_nested_state_length(void)
2752 return kvm_state->max_nested_state_len;
2755 int kvm_has_many_ioeventfds(void)
2757 if (!kvm_enabled()) {
2758 return 0;
2760 return kvm_state->many_ioeventfds;
2763 int kvm_has_gsi_routing(void)
2765 #ifdef KVM_CAP_IRQ_ROUTING
2766 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
2767 #else
2768 return false;
2769 #endif
2772 int kvm_has_intx_set_mask(void)
2774 return kvm_state->intx_set_mask;
2777 bool kvm_arm_supports_user_irq(void)
2779 return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
2782 #ifdef KVM_CAP_SET_GUEST_DEBUG
2783 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
2784 target_ulong pc)
2786 struct kvm_sw_breakpoint *bp;
2788 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
2789 if (bp->pc == pc) {
2790 return bp;
2793 return NULL;
2796 int kvm_sw_breakpoints_active(CPUState *cpu)
2798 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
2801 struct kvm_set_guest_debug_data {
2802 struct kvm_guest_debug dbg;
2803 int err;
2806 static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
2808 struct kvm_set_guest_debug_data *dbg_data =
2809 (struct kvm_set_guest_debug_data *) data.host_ptr;
2811 dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
2812 &dbg_data->dbg);
2815 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2817 struct kvm_set_guest_debug_data data;
2819 data.dbg.control = reinject_trap;
2821 if (cpu->singlestep_enabled) {
2822 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2824 kvm_arch_update_guest_debug(cpu, &data.dbg);
2826 run_on_cpu(cpu, kvm_invoke_set_guest_debug,
2827 RUN_ON_CPU_HOST_PTR(&data));
2828 return data.err;
2831 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2832 target_ulong len, int type)
2834 struct kvm_sw_breakpoint *bp;
2835 int err;
2837 if (type == GDB_BREAKPOINT_SW) {
2838 bp = kvm_find_sw_breakpoint(cpu, addr);
2839 if (bp) {
2840 bp->use_count++;
2841 return 0;
2844 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2845 bp->pc = addr;
2846 bp->use_count = 1;
2847 err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2848 if (err) {
2849 g_free(bp);
2850 return err;
2853 QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2854 } else {
2855 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2856 if (err) {
2857 return err;
2861 CPU_FOREACH(cpu) {
2862 err = kvm_update_guest_debug(cpu, 0);
2863 if (err) {
2864 return err;
2867 return 0;
2870 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2871 target_ulong len, int type)
2873 struct kvm_sw_breakpoint *bp;
2874 int err;
2876 if (type == GDB_BREAKPOINT_SW) {
2877 bp = kvm_find_sw_breakpoint(cpu, addr);
2878 if (!bp) {
2879 return -ENOENT;
2882 if (bp->use_count > 1) {
2883 bp->use_count--;
2884 return 0;
2887 err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2888 if (err) {
2889 return err;
2892 QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2893 g_free(bp);
2894 } else {
2895 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2896 if (err) {
2897 return err;
2901 CPU_FOREACH(cpu) {
2902 err = kvm_update_guest_debug(cpu, 0);
2903 if (err) {
2904 return err;
2907 return 0;
2910 void kvm_remove_all_breakpoints(CPUState *cpu)
2912 struct kvm_sw_breakpoint *bp, *next;
2913 KVMState *s = cpu->kvm_state;
2914 CPUState *tmpcpu;
2916 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2917 if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2918 /* Try harder to find a CPU that currently sees the breakpoint. */
2919 CPU_FOREACH(tmpcpu) {
2920 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2921 break;
2925 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2926 g_free(bp);
2928 kvm_arch_remove_all_hw_breakpoints();
2930 CPU_FOREACH(cpu) {
2931 kvm_update_guest_debug(cpu, 0);
2935 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2937 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2939 return -EINVAL;
2942 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2943 target_ulong len, int type)
2945 return -EINVAL;
2948 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2949 target_ulong len, int type)
2951 return -EINVAL;
2954 void kvm_remove_all_breakpoints(CPUState *cpu)
2957 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2959 static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2961 KVMState *s = kvm_state;
2962 struct kvm_signal_mask *sigmask;
2963 int r;
2965 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2967 sigmask->len = s->sigmask_len;
2968 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2969 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2970 g_free(sigmask);
2972 return r;
2975 static void kvm_ipi_signal(int sig)
2977 if (current_cpu) {
2978 assert(kvm_immediate_exit);
2979 kvm_cpu_kick(current_cpu);
2983 void kvm_init_cpu_signals(CPUState *cpu)
2985 int r;
2986 sigset_t set;
2987 struct sigaction sigact;
2989 memset(&sigact, 0, sizeof(sigact));
2990 sigact.sa_handler = kvm_ipi_signal;
2991 sigaction(SIG_IPI, &sigact, NULL);
2993 pthread_sigmask(SIG_BLOCK, NULL, &set);
2994 #if defined KVM_HAVE_MCE_INJECTION
2995 sigdelset(&set, SIGBUS);
2996 pthread_sigmask(SIG_SETMASK, &set, NULL);
2997 #endif
2998 sigdelset(&set, SIG_IPI);
2999 if (kvm_immediate_exit) {
3000 r = pthread_sigmask(SIG_SETMASK, &set, NULL);
3001 } else {
3002 r = kvm_set_signal_mask(cpu, &set);
3004 if (r) {
3005 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
3006 exit(1);
3010 /* Called asynchronously in VCPU thread. */
3011 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
3013 #ifdef KVM_HAVE_MCE_INJECTION
3014 if (have_sigbus_pending) {
3015 return 1;
3017 have_sigbus_pending = true;
3018 pending_sigbus_addr = addr;
3019 pending_sigbus_code = code;
3020 qatomic_set(&cpu->exit_request, 1);
3021 return 0;
3022 #else
3023 return 1;
3024 #endif
3027 /* Called synchronously (via signalfd) in main thread. */
3028 int kvm_on_sigbus(int code, void *addr)
3030 #ifdef KVM_HAVE_MCE_INJECTION
3031 /* Action required MCE kills the process if SIGBUS is blocked. Because
3032 * that's what happens in the I/O thread, where we handle MCE via signalfd,
3033 * we can only get action optional here.
3035 assert(code != BUS_MCEERR_AR);
3036 kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
3037 return 0;
3038 #else
3039 return 1;
3040 #endif
3043 int kvm_create_device(KVMState *s, uint64_t type, bool test)
3045 int ret;
3046 struct kvm_create_device create_dev;
3048 create_dev.type = type;
3049 create_dev.fd = -1;
3050 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
3052 if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
3053 return -ENOTSUP;
3056 ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
3057 if (ret) {
3058 return ret;
3061 return test ? 0 : create_dev.fd;
3064 bool kvm_device_supported(int vmfd, uint64_t type)
3066 struct kvm_create_device create_dev = {
3067 .type = type,
3068 .fd = -1,
3069 .flags = KVM_CREATE_DEVICE_TEST,
3072 if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
3073 return false;
3076 return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
3079 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
3081 struct kvm_one_reg reg;
3082 int r;
3084 reg.id = id;
3085 reg.addr = (uintptr_t) source;
3086 r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
3087 if (r) {
3088 trace_kvm_failed_reg_set(id, strerror(-r));
3090 return r;
3093 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
3095 struct kvm_one_reg reg;
3096 int r;
3098 reg.id = id;
3099 reg.addr = (uintptr_t) target;
3100 r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
3101 if (r) {
3102 trace_kvm_failed_reg_get(id, strerror(-r));
3104 return r;
3107 static bool kvm_accel_has_memory(MachineState *ms, AddressSpace *as,
3108 hwaddr start_addr, hwaddr size)
3110 KVMState *kvm = KVM_STATE(ms->accelerator);
3111 int i;
3113 for (i = 0; i < kvm->nr_as; ++i) {
3114 if (kvm->as[i].as == as && kvm->as[i].ml) {
3115 size = MIN(kvm_max_slot_size, size);
3116 return NULL != kvm_lookup_matching_slot(kvm->as[i].ml,
3117 start_addr, size);
3121 return false;
3124 static void kvm_get_kvm_shadow_mem(Object *obj, Visitor *v,
3125 const char *name, void *opaque,
3126 Error **errp)
3128 KVMState *s = KVM_STATE(obj);
3129 int64_t value = s->kvm_shadow_mem;
3131 visit_type_int(v, name, &value, errp);
3134 static void kvm_set_kvm_shadow_mem(Object *obj, Visitor *v,
3135 const char *name, void *opaque,
3136 Error **errp)
3138 KVMState *s = KVM_STATE(obj);
3139 int64_t value;
3141 if (!visit_type_int(v, name, &value, errp)) {
3142 return;
3145 s->kvm_shadow_mem = value;
3148 static void kvm_set_kernel_irqchip(Object *obj, Visitor *v,
3149 const char *name, void *opaque,
3150 Error **errp)
3152 KVMState *s = KVM_STATE(obj);
3153 OnOffSplit mode;
3155 if (!visit_type_OnOffSplit(v, name, &mode, errp)) {
3156 return;
3158 switch (mode) {
3159 case ON_OFF_SPLIT_ON:
3160 s->kernel_irqchip_allowed = true;
3161 s->kernel_irqchip_required = true;
3162 s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3163 break;
3164 case ON_OFF_SPLIT_OFF:
3165 s->kernel_irqchip_allowed = false;
3166 s->kernel_irqchip_required = false;
3167 s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3168 break;
3169 case ON_OFF_SPLIT_SPLIT:
3170 s->kernel_irqchip_allowed = true;
3171 s->kernel_irqchip_required = true;
3172 s->kernel_irqchip_split = ON_OFF_AUTO_ON;
3173 break;
3174 default:
3175 /* The value was checked in visit_type_OnOffSplit() above. If
3176 * we get here, then something is wrong in QEMU.
3178 abort();
3182 bool kvm_kernel_irqchip_allowed(void)
3184 return kvm_state->kernel_irqchip_allowed;
3187 bool kvm_kernel_irqchip_required(void)
3189 return kvm_state->kernel_irqchip_required;
3192 bool kvm_kernel_irqchip_split(void)
3194 return kvm_state->kernel_irqchip_split == ON_OFF_AUTO_ON;
3197 static void kvm_accel_instance_init(Object *obj)
3199 KVMState *s = KVM_STATE(obj);
3201 s->kvm_shadow_mem = -1;
3202 s->kernel_irqchip_allowed = true;
3203 s->kernel_irqchip_split = ON_OFF_AUTO_AUTO;
3206 static void kvm_accel_class_init(ObjectClass *oc, void *data)
3208 AccelClass *ac = ACCEL_CLASS(oc);
3209 ac->name = "KVM";
3210 ac->init_machine = kvm_init;
3211 ac->has_memory = kvm_accel_has_memory;
3212 ac->allowed = &kvm_allowed;
3214 object_class_property_add(oc, "kernel-irqchip", "on|off|split",
3215 NULL, kvm_set_kernel_irqchip,
3216 NULL, NULL);
3217 object_class_property_set_description(oc, "kernel-irqchip",
3218 "Configure KVM in-kernel irqchip");
3220 object_class_property_add(oc, "kvm-shadow-mem", "int",
3221 kvm_get_kvm_shadow_mem, kvm_set_kvm_shadow_mem,
3222 NULL, NULL);
3223 object_class_property_set_description(oc, "kvm-shadow-mem",
3224 "KVM shadow MMU size");
3227 static const TypeInfo kvm_accel_type = {
3228 .name = TYPE_KVM_ACCEL,
3229 .parent = TYPE_ACCEL,
3230 .instance_init = kvm_accel_instance_init,
3231 .class_init = kvm_accel_class_init,
3232 .instance_size = sizeof(KVMState),
3235 static void kvm_type_init(void)
3237 type_register_static(&kvm_accel_type);
3240 type_init(kvm_type_init);