kvm: fix alignment of ram address
[qemu/ar7.git] / accel / kvm / kvm-all.c
blobfae1eca983c8fcf337d8f8e88d869ecf4201b054
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-common.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/hw.h"
28 #include "hw/pci/msi.h"
29 #include "hw/pci/msix.h"
30 #include "hw/s390x/adapter.h"
31 #include "exec/gdbstub.h"
32 #include "sysemu/kvm_int.h"
33 #include "sysemu/cpus.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 "trace.h"
40 #include "hw/irq.h"
42 #include "hw/boards.h"
44 /* This check must be after config-host.h is included */
45 #ifdef CONFIG_EVENTFD
46 #include <sys/eventfd.h>
47 #endif
49 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
50 * need to use the real host PAGE_SIZE, as that's what KVM will use.
52 #define PAGE_SIZE getpagesize()
54 //#define DEBUG_KVM
56 #ifdef DEBUG_KVM
57 #define DPRINTF(fmt, ...) \
58 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
59 #else
60 #define DPRINTF(fmt, ...) \
61 do { } while (0)
62 #endif
64 #define KVM_MSI_HASHTAB_SIZE 256
66 struct KVMParkedVcpu {
67 unsigned long vcpu_id;
68 int kvm_fd;
69 QLIST_ENTRY(KVMParkedVcpu) node;
72 struct KVMState
74 AccelState parent_obj;
76 int nr_slots;
77 int fd;
78 int vmfd;
79 int coalesced_mmio;
80 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
81 bool coalesced_flush_in_progress;
82 int vcpu_events;
83 int robust_singlestep;
84 int debugregs;
85 #ifdef KVM_CAP_SET_GUEST_DEBUG
86 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
87 #endif
88 int many_ioeventfds;
89 int intx_set_mask;
90 bool sync_mmu;
91 /* The man page (and posix) say ioctl numbers are signed int, but
92 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
93 * unsigned, and treating them as signed here can break things */
94 unsigned irq_set_ioctl;
95 unsigned int sigmask_len;
96 GHashTable *gsimap;
97 #ifdef KVM_CAP_IRQ_ROUTING
98 struct kvm_irq_routing *irq_routes;
99 int nr_allocated_irq_routes;
100 unsigned long *used_gsi_bitmap;
101 unsigned int gsi_count;
102 QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
103 #endif
104 KVMMemoryListener memory_listener;
105 QLIST_HEAD(, KVMParkedVcpu) kvm_parked_vcpus;
108 KVMState *kvm_state;
109 bool kvm_kernel_irqchip;
110 bool kvm_split_irqchip;
111 bool kvm_async_interrupts_allowed;
112 bool kvm_halt_in_kernel_allowed;
113 bool kvm_eventfds_allowed;
114 bool kvm_irqfds_allowed;
115 bool kvm_resamplefds_allowed;
116 bool kvm_msi_via_irqfd_allowed;
117 bool kvm_gsi_routing_allowed;
118 bool kvm_gsi_direct_mapping;
119 bool kvm_allowed;
120 bool kvm_readonly_mem_allowed;
121 bool kvm_vm_attributes_allowed;
122 bool kvm_direct_msi_allowed;
123 bool kvm_ioeventfd_any_length_allowed;
124 bool kvm_msi_use_devid;
125 static bool kvm_immediate_exit;
127 static const KVMCapabilityInfo kvm_required_capabilites[] = {
128 KVM_CAP_INFO(USER_MEMORY),
129 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
130 KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS),
131 KVM_CAP_LAST_INFO
134 int kvm_get_max_memslots(void)
136 KVMState *s = KVM_STATE(current_machine->accelerator);
138 return s->nr_slots;
141 static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
143 KVMState *s = kvm_state;
144 int i;
146 for (i = 0; i < s->nr_slots; i++) {
147 if (kml->slots[i].memory_size == 0) {
148 return &kml->slots[i];
152 return NULL;
155 bool kvm_has_free_slot(MachineState *ms)
157 KVMState *s = KVM_STATE(ms->accelerator);
159 return kvm_get_free_slot(&s->memory_listener);
162 static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
164 KVMSlot *slot = kvm_get_free_slot(kml);
166 if (slot) {
167 return slot;
170 fprintf(stderr, "%s: no free slot available\n", __func__);
171 abort();
174 static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
175 hwaddr start_addr,
176 hwaddr size)
178 KVMState *s = kvm_state;
179 int i;
181 for (i = 0; i < s->nr_slots; i++) {
182 KVMSlot *mem = &kml->slots[i];
184 if (start_addr == mem->start_addr && size == mem->memory_size) {
185 return mem;
189 return NULL;
193 * Calculate and align the start address and the size of the section.
194 * Return the size. If the size is 0, the aligned section is empty.
196 static hwaddr kvm_align_section(MemoryRegionSection *section,
197 hwaddr *start)
199 hwaddr size = int128_get64(section->size);
200 hwaddr delta;
202 *start = section->offset_within_address_space;
204 /* kvm works in page size chunks, but the function may be called
205 with sub-page size and unaligned start address. Pad the start
206 address to next and truncate size to previous page boundary. */
207 delta = qemu_real_host_page_size - (*start & ~qemu_real_host_page_mask);
208 delta &= ~qemu_real_host_page_mask;
209 *start += delta;
210 if (delta > size) {
211 return 0;
213 size -= delta;
214 size &= qemu_real_host_page_mask;
215 if (*start & ~qemu_real_host_page_mask) {
216 return 0;
219 return size;
222 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
223 hwaddr *phys_addr)
225 KVMMemoryListener *kml = &s->memory_listener;
226 int i;
228 for (i = 0; i < s->nr_slots; i++) {
229 KVMSlot *mem = &kml->slots[i];
231 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
232 *phys_addr = mem->start_addr + (ram - mem->ram);
233 return 1;
237 return 0;
240 static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot)
242 KVMState *s = kvm_state;
243 struct kvm_userspace_memory_region mem;
245 mem.slot = slot->slot | (kml->as_id << 16);
246 mem.guest_phys_addr = slot->start_addr;
247 mem.userspace_addr = (unsigned long)slot->ram;
248 mem.flags = slot->flags;
250 if (slot->memory_size && mem.flags & KVM_MEM_READONLY) {
251 /* Set the slot size to 0 before setting the slot to the desired
252 * value. This is needed based on KVM commit 75d61fbc. */
253 mem.memory_size = 0;
254 kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
256 mem.memory_size = slot->memory_size;
257 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
260 int kvm_destroy_vcpu(CPUState *cpu)
262 KVMState *s = kvm_state;
263 long mmap_size;
264 struct KVMParkedVcpu *vcpu = NULL;
265 int ret = 0;
267 DPRINTF("kvm_destroy_vcpu\n");
269 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
270 if (mmap_size < 0) {
271 ret = mmap_size;
272 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
273 goto err;
276 ret = munmap(cpu->kvm_run, mmap_size);
277 if (ret < 0) {
278 goto err;
281 vcpu = g_malloc0(sizeof(*vcpu));
282 vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
283 vcpu->kvm_fd = cpu->kvm_fd;
284 QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
285 err:
286 return ret;
289 static int kvm_get_vcpu(KVMState *s, unsigned long vcpu_id)
291 struct KVMParkedVcpu *cpu;
293 QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
294 if (cpu->vcpu_id == vcpu_id) {
295 int kvm_fd;
297 QLIST_REMOVE(cpu, node);
298 kvm_fd = cpu->kvm_fd;
299 g_free(cpu);
300 return kvm_fd;
304 return kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)vcpu_id);
307 int kvm_init_vcpu(CPUState *cpu)
309 KVMState *s = kvm_state;
310 long mmap_size;
311 int ret;
313 DPRINTF("kvm_init_vcpu\n");
315 ret = kvm_get_vcpu(s, kvm_arch_vcpu_id(cpu));
316 if (ret < 0) {
317 DPRINTF("kvm_create_vcpu failed\n");
318 goto err;
321 cpu->kvm_fd = ret;
322 cpu->kvm_state = s;
323 cpu->vcpu_dirty = true;
325 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
326 if (mmap_size < 0) {
327 ret = mmap_size;
328 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
329 goto err;
332 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
333 cpu->kvm_fd, 0);
334 if (cpu->kvm_run == MAP_FAILED) {
335 ret = -errno;
336 DPRINTF("mmap'ing vcpu state failed\n");
337 goto err;
340 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
341 s->coalesced_mmio_ring =
342 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
345 ret = kvm_arch_init_vcpu(cpu);
346 err:
347 return ret;
351 * dirty pages logging control
354 static int kvm_mem_flags(MemoryRegion *mr)
356 bool readonly = mr->readonly || memory_region_is_romd(mr);
357 int flags = 0;
359 if (memory_region_get_dirty_log_mask(mr) != 0) {
360 flags |= KVM_MEM_LOG_DIRTY_PAGES;
362 if (readonly && kvm_readonly_mem_allowed) {
363 flags |= KVM_MEM_READONLY;
365 return flags;
368 static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
369 MemoryRegion *mr)
371 int old_flags;
373 old_flags = mem->flags;
374 mem->flags = kvm_mem_flags(mr);
376 /* If nothing changed effectively, no need to issue ioctl */
377 if (mem->flags == old_flags) {
378 return 0;
381 return kvm_set_user_memory_region(kml, mem);
384 static int kvm_section_update_flags(KVMMemoryListener *kml,
385 MemoryRegionSection *section)
387 hwaddr start_addr, size;
388 KVMSlot *mem;
390 size = kvm_align_section(section, &start_addr);
391 if (!size) {
392 return 0;
395 mem = kvm_lookup_matching_slot(kml, start_addr, size);
396 if (!mem) {
397 fprintf(stderr, "%s: error finding slot\n", __func__);
398 abort();
401 return kvm_slot_update_flags(kml, mem, section->mr);
404 static void kvm_log_start(MemoryListener *listener,
405 MemoryRegionSection *section,
406 int old, int new)
408 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
409 int r;
411 if (old != 0) {
412 return;
415 r = kvm_section_update_flags(kml, section);
416 if (r < 0) {
417 abort();
421 static void kvm_log_stop(MemoryListener *listener,
422 MemoryRegionSection *section,
423 int old, int new)
425 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
426 int r;
428 if (new != 0) {
429 return;
432 r = kvm_section_update_flags(kml, section);
433 if (r < 0) {
434 abort();
438 /* get kvm's dirty pages bitmap and update qemu's */
439 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
440 unsigned long *bitmap)
442 ram_addr_t start = section->offset_within_region +
443 memory_region_get_ram_addr(section->mr);
444 ram_addr_t pages = int128_get64(section->size) / getpagesize();
446 cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
447 return 0;
450 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
453 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
454 * This function updates qemu's dirty bitmap using
455 * memory_region_set_dirty(). This means all bits are set
456 * to dirty.
458 * @start_add: start of logged region.
459 * @end_addr: end of logged region.
461 static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
462 MemoryRegionSection *section)
464 KVMState *s = kvm_state;
465 struct kvm_dirty_log d = {};
466 KVMSlot *mem;
467 hwaddr start_addr, size;
469 size = kvm_align_section(section, &start_addr);
470 if (size) {
471 mem = kvm_lookup_matching_slot(kml, start_addr, size);
472 if (!mem) {
473 fprintf(stderr, "%s: error finding slot\n", __func__);
474 abort();
477 /* XXX bad kernel interface alert
478 * For dirty bitmap, kernel allocates array of size aligned to
479 * bits-per-long. But for case when the kernel is 64bits and
480 * the userspace is 32bits, userspace can't align to the same
481 * bits-per-long, since sizeof(long) is different between kernel
482 * and user space. This way, userspace will provide buffer which
483 * may be 4 bytes less than the kernel will use, resulting in
484 * userspace memory corruption (which is not detectable by valgrind
485 * too, in most cases).
486 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
487 * a hope that sizeof(long) won't become >8 any time soon.
489 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
490 /*HOST_LONG_BITS*/ 64) / 8;
491 d.dirty_bitmap = g_malloc0(size);
493 d.slot = mem->slot | (kml->as_id << 16);
494 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
495 DPRINTF("ioctl failed %d\n", errno);
496 g_free(d.dirty_bitmap);
497 return -1;
500 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
501 g_free(d.dirty_bitmap);
504 return 0;
507 static void kvm_coalesce_mmio_region(MemoryListener *listener,
508 MemoryRegionSection *secion,
509 hwaddr start, hwaddr size)
511 KVMState *s = kvm_state;
513 if (s->coalesced_mmio) {
514 struct kvm_coalesced_mmio_zone zone;
516 zone.addr = start;
517 zone.size = size;
518 zone.pad = 0;
520 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
524 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
525 MemoryRegionSection *secion,
526 hwaddr start, hwaddr size)
528 KVMState *s = kvm_state;
530 if (s->coalesced_mmio) {
531 struct kvm_coalesced_mmio_zone zone;
533 zone.addr = start;
534 zone.size = size;
535 zone.pad = 0;
537 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
541 int kvm_check_extension(KVMState *s, unsigned int extension)
543 int ret;
545 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
546 if (ret < 0) {
547 ret = 0;
550 return ret;
553 int kvm_vm_check_extension(KVMState *s, unsigned int extension)
555 int ret;
557 ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
558 if (ret < 0) {
559 /* VM wide version not implemented, use global one instead */
560 ret = kvm_check_extension(s, extension);
563 return ret;
566 static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
568 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
569 /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
570 * endianness, but the memory core hands them in target endianness.
571 * For example, PPC is always treated as big-endian even if running
572 * on KVM and on PPC64LE. Correct here.
574 switch (size) {
575 case 2:
576 val = bswap16(val);
577 break;
578 case 4:
579 val = bswap32(val);
580 break;
582 #endif
583 return val;
586 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
587 bool assign, uint32_t size, bool datamatch)
589 int ret;
590 struct kvm_ioeventfd iofd = {
591 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
592 .addr = addr,
593 .len = size,
594 .flags = 0,
595 .fd = fd,
598 if (!kvm_enabled()) {
599 return -ENOSYS;
602 if (datamatch) {
603 iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
605 if (!assign) {
606 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
609 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
611 if (ret < 0) {
612 return -errno;
615 return 0;
618 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
619 bool assign, uint32_t size, bool datamatch)
621 struct kvm_ioeventfd kick = {
622 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
623 .addr = addr,
624 .flags = KVM_IOEVENTFD_FLAG_PIO,
625 .len = size,
626 .fd = fd,
628 int r;
629 if (!kvm_enabled()) {
630 return -ENOSYS;
632 if (datamatch) {
633 kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
635 if (!assign) {
636 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
638 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
639 if (r < 0) {
640 return r;
642 return 0;
646 static int kvm_check_many_ioeventfds(void)
648 /* Userspace can use ioeventfd for io notification. This requires a host
649 * that supports eventfd(2) and an I/O thread; since eventfd does not
650 * support SIGIO it cannot interrupt the vcpu.
652 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
653 * can avoid creating too many ioeventfds.
655 #if defined(CONFIG_EVENTFD)
656 int ioeventfds[7];
657 int i, ret = 0;
658 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
659 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
660 if (ioeventfds[i] < 0) {
661 break;
663 ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
664 if (ret < 0) {
665 close(ioeventfds[i]);
666 break;
670 /* Decide whether many devices are supported or not */
671 ret = i == ARRAY_SIZE(ioeventfds);
673 while (i-- > 0) {
674 kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
675 close(ioeventfds[i]);
677 return ret;
678 #else
679 return 0;
680 #endif
683 static const KVMCapabilityInfo *
684 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
686 while (list->name) {
687 if (!kvm_check_extension(s, list->value)) {
688 return list;
690 list++;
692 return NULL;
695 static void kvm_set_phys_mem(KVMMemoryListener *kml,
696 MemoryRegionSection *section, bool add)
698 KVMSlot *mem;
699 int err;
700 MemoryRegion *mr = section->mr;
701 bool writeable = !mr->readonly && !mr->rom_device;
702 hwaddr start_addr, size;
703 void *ram;
705 if (!memory_region_is_ram(mr)) {
706 if (writeable || !kvm_readonly_mem_allowed) {
707 return;
708 } else if (!mr->romd_mode) {
709 /* If the memory device is not in romd_mode, then we actually want
710 * to remove the kvm memory slot so all accesses will trap. */
711 add = false;
715 size = kvm_align_section(section, &start_addr);
716 if (!size) {
717 return;
720 /* use aligned delta to align the ram address */
721 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region +
722 (start_addr - section->offset_within_address_space);
724 mem = kvm_lookup_matching_slot(kml, start_addr, size);
725 if (!add) {
726 if (!mem) {
727 return;
729 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
730 kvm_physical_sync_dirty_bitmap(kml, section);
733 /* unregister the slot */
734 mem->memory_size = 0;
735 err = kvm_set_user_memory_region(kml, mem);
736 if (err) {
737 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
738 __func__, strerror(-err));
739 abort();
741 return;
744 if (mem) {
745 /* update the slot */
746 kvm_slot_update_flags(kml, mem, mr);
747 return;
750 /* register the new slot */
751 mem = kvm_alloc_slot(kml);
752 mem->memory_size = size;
753 mem->start_addr = start_addr;
754 mem->ram = ram;
755 mem->flags = kvm_mem_flags(mr);
757 err = kvm_set_user_memory_region(kml, mem);
758 if (err) {
759 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
760 strerror(-err));
761 abort();
765 static void kvm_region_add(MemoryListener *listener,
766 MemoryRegionSection *section)
768 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
770 memory_region_ref(section->mr);
771 kvm_set_phys_mem(kml, section, true);
774 static void kvm_region_del(MemoryListener *listener,
775 MemoryRegionSection *section)
777 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
779 kvm_set_phys_mem(kml, section, false);
780 memory_region_unref(section->mr);
783 static void kvm_log_sync(MemoryListener *listener,
784 MemoryRegionSection *section)
786 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
787 int r;
789 r = kvm_physical_sync_dirty_bitmap(kml, section);
790 if (r < 0) {
791 abort();
795 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
796 MemoryRegionSection *section,
797 bool match_data, uint64_t data,
798 EventNotifier *e)
800 int fd = event_notifier_get_fd(e);
801 int r;
803 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
804 data, true, int128_get64(section->size),
805 match_data);
806 if (r < 0) {
807 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
808 __func__, strerror(-r));
809 abort();
813 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
814 MemoryRegionSection *section,
815 bool match_data, uint64_t data,
816 EventNotifier *e)
818 int fd = event_notifier_get_fd(e);
819 int r;
821 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
822 data, false, int128_get64(section->size),
823 match_data);
824 if (r < 0) {
825 abort();
829 static void kvm_io_ioeventfd_add(MemoryListener *listener,
830 MemoryRegionSection *section,
831 bool match_data, uint64_t data,
832 EventNotifier *e)
834 int fd = event_notifier_get_fd(e);
835 int r;
837 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
838 data, true, int128_get64(section->size),
839 match_data);
840 if (r < 0) {
841 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
842 __func__, strerror(-r));
843 abort();
847 static void kvm_io_ioeventfd_del(MemoryListener *listener,
848 MemoryRegionSection *section,
849 bool match_data, uint64_t data,
850 EventNotifier *e)
853 int fd = event_notifier_get_fd(e);
854 int r;
856 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
857 data, false, int128_get64(section->size),
858 match_data);
859 if (r < 0) {
860 abort();
864 void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
865 AddressSpace *as, int as_id)
867 int i;
869 kml->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
870 kml->as_id = as_id;
872 for (i = 0; i < s->nr_slots; i++) {
873 kml->slots[i].slot = i;
876 kml->listener.region_add = kvm_region_add;
877 kml->listener.region_del = kvm_region_del;
878 kml->listener.log_start = kvm_log_start;
879 kml->listener.log_stop = kvm_log_stop;
880 kml->listener.log_sync = kvm_log_sync;
881 kml->listener.priority = 10;
883 memory_listener_register(&kml->listener, as);
886 static MemoryListener kvm_io_listener = {
887 .eventfd_add = kvm_io_ioeventfd_add,
888 .eventfd_del = kvm_io_ioeventfd_del,
889 .priority = 10,
892 int kvm_set_irq(KVMState *s, int irq, int level)
894 struct kvm_irq_level event;
895 int ret;
897 assert(kvm_async_interrupts_enabled());
899 event.level = level;
900 event.irq = irq;
901 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
902 if (ret < 0) {
903 perror("kvm_set_irq");
904 abort();
907 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
910 #ifdef KVM_CAP_IRQ_ROUTING
911 typedef struct KVMMSIRoute {
912 struct kvm_irq_routing_entry kroute;
913 QTAILQ_ENTRY(KVMMSIRoute) entry;
914 } KVMMSIRoute;
916 static void set_gsi(KVMState *s, unsigned int gsi)
918 set_bit(gsi, s->used_gsi_bitmap);
921 static void clear_gsi(KVMState *s, unsigned int gsi)
923 clear_bit(gsi, s->used_gsi_bitmap);
926 void kvm_init_irq_routing(KVMState *s)
928 int gsi_count, i;
930 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
931 if (gsi_count > 0) {
932 /* Round up so we can search ints using ffs */
933 s->used_gsi_bitmap = bitmap_new(gsi_count);
934 s->gsi_count = gsi_count;
937 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
938 s->nr_allocated_irq_routes = 0;
940 if (!kvm_direct_msi_allowed) {
941 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
942 QTAILQ_INIT(&s->msi_hashtab[i]);
946 kvm_arch_init_irq_routing(s);
949 void kvm_irqchip_commit_routes(KVMState *s)
951 int ret;
953 if (kvm_gsi_direct_mapping()) {
954 return;
957 if (!kvm_gsi_routing_enabled()) {
958 return;
961 s->irq_routes->flags = 0;
962 trace_kvm_irqchip_commit_routes();
963 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
964 assert(ret == 0);
967 static void kvm_add_routing_entry(KVMState *s,
968 struct kvm_irq_routing_entry *entry)
970 struct kvm_irq_routing_entry *new;
971 int n, size;
973 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
974 n = s->nr_allocated_irq_routes * 2;
975 if (n < 64) {
976 n = 64;
978 size = sizeof(struct kvm_irq_routing);
979 size += n * sizeof(*new);
980 s->irq_routes = g_realloc(s->irq_routes, size);
981 s->nr_allocated_irq_routes = n;
983 n = s->irq_routes->nr++;
984 new = &s->irq_routes->entries[n];
986 *new = *entry;
988 set_gsi(s, entry->gsi);
991 static int kvm_update_routing_entry(KVMState *s,
992 struct kvm_irq_routing_entry *new_entry)
994 struct kvm_irq_routing_entry *entry;
995 int n;
997 for (n = 0; n < s->irq_routes->nr; n++) {
998 entry = &s->irq_routes->entries[n];
999 if (entry->gsi != new_entry->gsi) {
1000 continue;
1003 if(!memcmp(entry, new_entry, sizeof *entry)) {
1004 return 0;
1007 *entry = *new_entry;
1009 return 0;
1012 return -ESRCH;
1015 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1017 struct kvm_irq_routing_entry e = {};
1019 assert(pin < s->gsi_count);
1021 e.gsi = irq;
1022 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1023 e.flags = 0;
1024 e.u.irqchip.irqchip = irqchip;
1025 e.u.irqchip.pin = pin;
1026 kvm_add_routing_entry(s, &e);
1029 void kvm_irqchip_release_virq(KVMState *s, int virq)
1031 struct kvm_irq_routing_entry *e;
1032 int i;
1034 if (kvm_gsi_direct_mapping()) {
1035 return;
1038 for (i = 0; i < s->irq_routes->nr; i++) {
1039 e = &s->irq_routes->entries[i];
1040 if (e->gsi == virq) {
1041 s->irq_routes->nr--;
1042 *e = s->irq_routes->entries[s->irq_routes->nr];
1045 clear_gsi(s, virq);
1046 kvm_arch_release_virq_post(virq);
1047 trace_kvm_irqchip_release_virq(virq);
1050 static unsigned int kvm_hash_msi(uint32_t data)
1052 /* This is optimized for IA32 MSI layout. However, no other arch shall
1053 * repeat the mistake of not providing a direct MSI injection API. */
1054 return data & 0xff;
1057 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1059 KVMMSIRoute *route, *next;
1060 unsigned int hash;
1062 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1063 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1064 kvm_irqchip_release_virq(s, route->kroute.gsi);
1065 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1066 g_free(route);
1071 static int kvm_irqchip_get_virq(KVMState *s)
1073 int next_virq;
1076 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1077 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1078 * number can succeed even though a new route entry cannot be added.
1079 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1081 if (!kvm_direct_msi_allowed && s->irq_routes->nr == s->gsi_count) {
1082 kvm_flush_dynamic_msi_routes(s);
1085 /* Return the lowest unused GSI in the bitmap */
1086 next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
1087 if (next_virq >= s->gsi_count) {
1088 return -ENOSPC;
1089 } else {
1090 return next_virq;
1094 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1096 unsigned int hash = kvm_hash_msi(msg.data);
1097 KVMMSIRoute *route;
1099 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1100 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1101 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1102 route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1103 return route;
1106 return NULL;
1109 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1111 struct kvm_msi msi;
1112 KVMMSIRoute *route;
1114 if (kvm_direct_msi_allowed) {
1115 msi.address_lo = (uint32_t)msg.address;
1116 msi.address_hi = msg.address >> 32;
1117 msi.data = le32_to_cpu(msg.data);
1118 msi.flags = 0;
1119 memset(msi.pad, 0, sizeof(msi.pad));
1121 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1124 route = kvm_lookup_msi_route(s, msg);
1125 if (!route) {
1126 int virq;
1128 virq = kvm_irqchip_get_virq(s);
1129 if (virq < 0) {
1130 return virq;
1133 route = g_malloc0(sizeof(KVMMSIRoute));
1134 route->kroute.gsi = virq;
1135 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1136 route->kroute.flags = 0;
1137 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1138 route->kroute.u.msi.address_hi = msg.address >> 32;
1139 route->kroute.u.msi.data = le32_to_cpu(msg.data);
1141 kvm_add_routing_entry(s, &route->kroute);
1142 kvm_irqchip_commit_routes(s);
1144 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1145 entry);
1148 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1150 return kvm_set_irq(s, route->kroute.gsi, 1);
1153 int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
1155 struct kvm_irq_routing_entry kroute = {};
1156 int virq;
1157 MSIMessage msg = {0, 0};
1159 if (pci_available && dev) {
1160 msg = pci_get_msi_message(dev, vector);
1163 if (kvm_gsi_direct_mapping()) {
1164 return kvm_arch_msi_data_to_gsi(msg.data);
1167 if (!kvm_gsi_routing_enabled()) {
1168 return -ENOSYS;
1171 virq = kvm_irqchip_get_virq(s);
1172 if (virq < 0) {
1173 return virq;
1176 kroute.gsi = virq;
1177 kroute.type = KVM_IRQ_ROUTING_MSI;
1178 kroute.flags = 0;
1179 kroute.u.msi.address_lo = (uint32_t)msg.address;
1180 kroute.u.msi.address_hi = msg.address >> 32;
1181 kroute.u.msi.data = le32_to_cpu(msg.data);
1182 if (pci_available && kvm_msi_devid_required()) {
1183 kroute.flags = KVM_MSI_VALID_DEVID;
1184 kroute.u.msi.devid = pci_requester_id(dev);
1186 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1187 kvm_irqchip_release_virq(s, virq);
1188 return -EINVAL;
1191 trace_kvm_irqchip_add_msi_route(dev ? dev->name : (char *)"N/A",
1192 vector, virq);
1194 kvm_add_routing_entry(s, &kroute);
1195 kvm_arch_add_msi_route_post(&kroute, vector, dev);
1196 kvm_irqchip_commit_routes(s);
1198 return virq;
1201 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
1202 PCIDevice *dev)
1204 struct kvm_irq_routing_entry kroute = {};
1206 if (kvm_gsi_direct_mapping()) {
1207 return 0;
1210 if (!kvm_irqchip_in_kernel()) {
1211 return -ENOSYS;
1214 kroute.gsi = virq;
1215 kroute.type = KVM_IRQ_ROUTING_MSI;
1216 kroute.flags = 0;
1217 kroute.u.msi.address_lo = (uint32_t)msg.address;
1218 kroute.u.msi.address_hi = msg.address >> 32;
1219 kroute.u.msi.data = le32_to_cpu(msg.data);
1220 if (pci_available && kvm_msi_devid_required()) {
1221 kroute.flags = KVM_MSI_VALID_DEVID;
1222 kroute.u.msi.devid = pci_requester_id(dev);
1224 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1225 return -EINVAL;
1228 trace_kvm_irqchip_update_msi_route(virq);
1230 return kvm_update_routing_entry(s, &kroute);
1233 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int rfd, int virq,
1234 bool assign)
1236 struct kvm_irqfd irqfd = {
1237 .fd = fd,
1238 .gsi = virq,
1239 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1242 if (rfd != -1) {
1243 irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1244 irqfd.resamplefd = rfd;
1247 if (!kvm_irqfds_enabled()) {
1248 return -ENOSYS;
1251 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1254 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1256 struct kvm_irq_routing_entry kroute = {};
1257 int virq;
1259 if (!kvm_gsi_routing_enabled()) {
1260 return -ENOSYS;
1263 virq = kvm_irqchip_get_virq(s);
1264 if (virq < 0) {
1265 return virq;
1268 kroute.gsi = virq;
1269 kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1270 kroute.flags = 0;
1271 kroute.u.adapter.summary_addr = adapter->summary_addr;
1272 kroute.u.adapter.ind_addr = adapter->ind_addr;
1273 kroute.u.adapter.summary_offset = adapter->summary_offset;
1274 kroute.u.adapter.ind_offset = adapter->ind_offset;
1275 kroute.u.adapter.adapter_id = adapter->adapter_id;
1277 kvm_add_routing_entry(s, &kroute);
1279 return virq;
1282 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1284 struct kvm_irq_routing_entry kroute = {};
1285 int virq;
1287 if (!kvm_gsi_routing_enabled()) {
1288 return -ENOSYS;
1290 if (!kvm_check_extension(s, KVM_CAP_HYPERV_SYNIC)) {
1291 return -ENOSYS;
1293 virq = kvm_irqchip_get_virq(s);
1294 if (virq < 0) {
1295 return virq;
1298 kroute.gsi = virq;
1299 kroute.type = KVM_IRQ_ROUTING_HV_SINT;
1300 kroute.flags = 0;
1301 kroute.u.hv_sint.vcpu = vcpu;
1302 kroute.u.hv_sint.sint = sint;
1304 kvm_add_routing_entry(s, &kroute);
1305 kvm_irqchip_commit_routes(s);
1307 return virq;
1310 #else /* !KVM_CAP_IRQ_ROUTING */
1312 void kvm_init_irq_routing(KVMState *s)
1316 void kvm_irqchip_release_virq(KVMState *s, int virq)
1320 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1322 abort();
1325 int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
1327 return -ENOSYS;
1330 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1332 return -ENOSYS;
1335 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1337 return -ENOSYS;
1340 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1342 abort();
1345 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1347 return -ENOSYS;
1349 #endif /* !KVM_CAP_IRQ_ROUTING */
1351 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1352 EventNotifier *rn, int virq)
1354 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n),
1355 rn ? event_notifier_get_fd(rn) : -1, virq, true);
1358 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1359 int virq)
1361 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), -1, virq,
1362 false);
1365 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1366 EventNotifier *rn, qemu_irq irq)
1368 gpointer key, gsi;
1369 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1371 if (!found) {
1372 return -ENXIO;
1374 return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
1377 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
1378 qemu_irq irq)
1380 gpointer key, gsi;
1381 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1383 if (!found) {
1384 return -ENXIO;
1386 return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
1389 void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
1391 g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
1394 static void kvm_irqchip_create(MachineState *machine, KVMState *s)
1396 int ret;
1398 if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
1400 } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
1401 ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
1402 if (ret < 0) {
1403 fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
1404 exit(1);
1406 } else {
1407 return;
1410 /* First probe and see if there's a arch-specific hook to create the
1411 * in-kernel irqchip for us */
1412 ret = kvm_arch_irqchip_create(machine, s);
1413 if (ret == 0) {
1414 if (machine_kernel_irqchip_split(machine)) {
1415 perror("Split IRQ chip mode not supported.");
1416 exit(1);
1417 } else {
1418 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1421 if (ret < 0) {
1422 fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
1423 exit(1);
1426 kvm_kernel_irqchip = true;
1427 /* If we have an in-kernel IRQ chip then we must have asynchronous
1428 * interrupt delivery (though the reverse is not necessarily true)
1430 kvm_async_interrupts_allowed = true;
1431 kvm_halt_in_kernel_allowed = true;
1433 kvm_init_irq_routing(s);
1435 s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
1438 /* Find number of supported CPUs using the recommended
1439 * procedure from the kernel API documentation to cope with
1440 * older kernels that may be missing capabilities.
1442 static int kvm_recommended_vcpus(KVMState *s)
1444 int ret = kvm_vm_check_extension(s, KVM_CAP_NR_VCPUS);
1445 return (ret) ? ret : 4;
1448 static int kvm_max_vcpus(KVMState *s)
1450 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1451 return (ret) ? ret : kvm_recommended_vcpus(s);
1454 static int kvm_max_vcpu_id(KVMState *s)
1456 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
1457 return (ret) ? ret : kvm_max_vcpus(s);
1460 bool kvm_vcpu_id_is_valid(int vcpu_id)
1462 KVMState *s = KVM_STATE(current_machine->accelerator);
1463 return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
1466 static int kvm_init(MachineState *ms)
1468 MachineClass *mc = MACHINE_GET_CLASS(ms);
1469 static const char upgrade_note[] =
1470 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1471 "(see http://sourceforge.net/projects/kvm).\n";
1472 struct {
1473 const char *name;
1474 int num;
1475 } num_cpus[] = {
1476 { "SMP", smp_cpus },
1477 { "hotpluggable", max_cpus },
1478 { NULL, }
1479 }, *nc = num_cpus;
1480 int soft_vcpus_limit, hard_vcpus_limit;
1481 KVMState *s;
1482 const KVMCapabilityInfo *missing_cap;
1483 int ret;
1484 int type = 0;
1485 const char *kvm_type;
1487 s = KVM_STATE(ms->accelerator);
1490 * On systems where the kernel can support different base page
1491 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1492 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1493 * page size for the system though.
1495 assert(TARGET_PAGE_SIZE <= getpagesize());
1497 s->sigmask_len = 8;
1499 #ifdef KVM_CAP_SET_GUEST_DEBUG
1500 QTAILQ_INIT(&s->kvm_sw_breakpoints);
1501 #endif
1502 QLIST_INIT(&s->kvm_parked_vcpus);
1503 s->vmfd = -1;
1504 s->fd = qemu_open("/dev/kvm", O_RDWR);
1505 if (s->fd == -1) {
1506 fprintf(stderr, "Could not access KVM kernel module: %m\n");
1507 ret = -errno;
1508 goto err;
1511 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1512 if (ret < KVM_API_VERSION) {
1513 if (ret >= 0) {
1514 ret = -EINVAL;
1516 fprintf(stderr, "kvm version too old\n");
1517 goto err;
1520 if (ret > KVM_API_VERSION) {
1521 ret = -EINVAL;
1522 fprintf(stderr, "kvm version not supported\n");
1523 goto err;
1526 kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
1527 s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
1529 /* If unspecified, use the default value */
1530 if (!s->nr_slots) {
1531 s->nr_slots = 32;
1534 kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1535 if (mc->kvm_type) {
1536 type = mc->kvm_type(kvm_type);
1537 } else if (kvm_type) {
1538 ret = -EINVAL;
1539 fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1540 goto err;
1543 do {
1544 ret = kvm_ioctl(s, KVM_CREATE_VM, type);
1545 } while (ret == -EINTR);
1547 if (ret < 0) {
1548 fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
1549 strerror(-ret));
1551 #ifdef TARGET_S390X
1552 if (ret == -EINVAL) {
1553 fprintf(stderr,
1554 "Host kernel setup problem detected. Please verify:\n");
1555 fprintf(stderr, "- for kernels supporting the switch_amode or"
1556 " user_mode parameters, whether\n");
1557 fprintf(stderr,
1558 " user space is running in primary address space\n");
1559 fprintf(stderr,
1560 "- for kernels supporting the vm.allocate_pgste sysctl, "
1561 "whether it is enabled\n");
1563 #endif
1564 goto err;
1567 s->vmfd = ret;
1569 /* check the vcpu limits */
1570 soft_vcpus_limit = kvm_recommended_vcpus(s);
1571 hard_vcpus_limit = kvm_max_vcpus(s);
1573 while (nc->name) {
1574 if (nc->num > soft_vcpus_limit) {
1575 warn_report("Number of %s cpus requested (%d) exceeds "
1576 "the recommended cpus supported by KVM (%d)",
1577 nc->name, nc->num, soft_vcpus_limit);
1579 if (nc->num > hard_vcpus_limit) {
1580 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
1581 "the maximum cpus supported by KVM (%d)\n",
1582 nc->name, nc->num, hard_vcpus_limit);
1583 exit(1);
1586 nc++;
1589 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1590 if (!missing_cap) {
1591 missing_cap =
1592 kvm_check_extension_list(s, kvm_arch_required_capabilities);
1594 if (missing_cap) {
1595 ret = -EINVAL;
1596 fprintf(stderr, "kvm does not support %s\n%s",
1597 missing_cap->name, upgrade_note);
1598 goto err;
1601 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1603 #ifdef KVM_CAP_VCPU_EVENTS
1604 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1605 #endif
1607 s->robust_singlestep =
1608 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1610 #ifdef KVM_CAP_DEBUGREGS
1611 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1612 #endif
1614 #ifdef KVM_CAP_IRQ_ROUTING
1615 kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1616 #endif
1618 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1620 s->irq_set_ioctl = KVM_IRQ_LINE;
1621 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1622 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1625 #ifdef KVM_CAP_READONLY_MEM
1626 kvm_readonly_mem_allowed =
1627 (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1628 #endif
1630 kvm_eventfds_allowed =
1631 (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
1633 kvm_irqfds_allowed =
1634 (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
1636 kvm_resamplefds_allowed =
1637 (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
1639 kvm_vm_attributes_allowed =
1640 (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
1642 kvm_ioeventfd_any_length_allowed =
1643 (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
1645 kvm_state = s;
1647 ret = kvm_arch_init(ms, s);
1648 if (ret < 0) {
1649 goto err;
1652 if (machine_kernel_irqchip_allowed(ms)) {
1653 kvm_irqchip_create(ms, s);
1656 if (kvm_eventfds_allowed) {
1657 s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
1658 s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
1660 s->memory_listener.listener.coalesced_mmio_add = kvm_coalesce_mmio_region;
1661 s->memory_listener.listener.coalesced_mmio_del = kvm_uncoalesce_mmio_region;
1663 kvm_memory_listener_register(s, &s->memory_listener,
1664 &address_space_memory, 0);
1665 memory_listener_register(&kvm_io_listener,
1666 &address_space_io);
1668 s->many_ioeventfds = kvm_check_many_ioeventfds();
1670 s->sync_mmu = !!kvm_vm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1672 return 0;
1674 err:
1675 assert(ret < 0);
1676 if (s->vmfd >= 0) {
1677 close(s->vmfd);
1679 if (s->fd != -1) {
1680 close(s->fd);
1682 g_free(s->memory_listener.slots);
1684 return ret;
1687 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
1689 s->sigmask_len = sigmask_len;
1692 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
1693 int size, uint32_t count)
1695 int i;
1696 uint8_t *ptr = data;
1698 for (i = 0; i < count; i++) {
1699 address_space_rw(&address_space_io, port, attrs,
1700 ptr, size,
1701 direction == KVM_EXIT_IO_OUT);
1702 ptr += size;
1706 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
1708 fprintf(stderr, "KVM internal error. Suberror: %d\n",
1709 run->internal.suberror);
1711 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1712 int i;
1714 for (i = 0; i < run->internal.ndata; ++i) {
1715 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1716 i, (uint64_t)run->internal.data[i]);
1719 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1720 fprintf(stderr, "emulation failure\n");
1721 if (!kvm_arch_stop_on_emulation_error(cpu)) {
1722 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1723 return EXCP_INTERRUPT;
1726 /* FIXME: Should trigger a qmp message to let management know
1727 * something went wrong.
1729 return -1;
1732 void kvm_flush_coalesced_mmio_buffer(void)
1734 KVMState *s = kvm_state;
1736 if (s->coalesced_flush_in_progress) {
1737 return;
1740 s->coalesced_flush_in_progress = true;
1742 if (s->coalesced_mmio_ring) {
1743 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1744 while (ring->first != ring->last) {
1745 struct kvm_coalesced_mmio *ent;
1747 ent = &ring->coalesced_mmio[ring->first];
1749 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1750 smp_wmb();
1751 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1755 s->coalesced_flush_in_progress = false;
1758 static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
1760 if (!cpu->vcpu_dirty) {
1761 kvm_arch_get_registers(cpu);
1762 cpu->vcpu_dirty = true;
1766 void kvm_cpu_synchronize_state(CPUState *cpu)
1768 if (!cpu->vcpu_dirty) {
1769 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
1773 static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
1775 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1776 cpu->vcpu_dirty = false;
1779 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
1781 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
1784 static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
1786 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1787 cpu->vcpu_dirty = false;
1790 void kvm_cpu_synchronize_post_init(CPUState *cpu)
1792 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
1795 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
1797 cpu->vcpu_dirty = true;
1800 void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
1802 run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
1805 #ifdef KVM_HAVE_MCE_INJECTION
1806 static __thread void *pending_sigbus_addr;
1807 static __thread int pending_sigbus_code;
1808 static __thread bool have_sigbus_pending;
1809 #endif
1811 static void kvm_cpu_kick(CPUState *cpu)
1813 atomic_set(&cpu->kvm_run->immediate_exit, 1);
1816 static void kvm_cpu_kick_self(void)
1818 if (kvm_immediate_exit) {
1819 kvm_cpu_kick(current_cpu);
1820 } else {
1821 qemu_cpu_kick_self();
1825 static void kvm_eat_signals(CPUState *cpu)
1827 struct timespec ts = { 0, 0 };
1828 siginfo_t siginfo;
1829 sigset_t waitset;
1830 sigset_t chkset;
1831 int r;
1833 if (kvm_immediate_exit) {
1834 atomic_set(&cpu->kvm_run->immediate_exit, 0);
1835 /* Write kvm_run->immediate_exit before the cpu->exit_request
1836 * write in kvm_cpu_exec.
1838 smp_wmb();
1839 return;
1842 sigemptyset(&waitset);
1843 sigaddset(&waitset, SIG_IPI);
1845 do {
1846 r = sigtimedwait(&waitset, &siginfo, &ts);
1847 if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
1848 perror("sigtimedwait");
1849 exit(1);
1852 r = sigpending(&chkset);
1853 if (r == -1) {
1854 perror("sigpending");
1855 exit(1);
1857 } while (sigismember(&chkset, SIG_IPI));
1860 int kvm_cpu_exec(CPUState *cpu)
1862 struct kvm_run *run = cpu->kvm_run;
1863 int ret, run_ret;
1865 DPRINTF("kvm_cpu_exec()\n");
1867 if (kvm_arch_process_async_events(cpu)) {
1868 atomic_set(&cpu->exit_request, 0);
1869 return EXCP_HLT;
1872 qemu_mutex_unlock_iothread();
1873 cpu_exec_start(cpu);
1875 do {
1876 MemTxAttrs attrs;
1878 if (cpu->vcpu_dirty) {
1879 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1880 cpu->vcpu_dirty = false;
1883 kvm_arch_pre_run(cpu, run);
1884 if (atomic_read(&cpu->exit_request)) {
1885 DPRINTF("interrupt exit requested\n");
1887 * KVM requires us to reenter the kernel after IO exits to complete
1888 * instruction emulation. This self-signal will ensure that we
1889 * leave ASAP again.
1891 kvm_cpu_kick_self();
1894 /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
1895 * Matching barrier in kvm_eat_signals.
1897 smp_rmb();
1899 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
1901 attrs = kvm_arch_post_run(cpu, run);
1903 #ifdef KVM_HAVE_MCE_INJECTION
1904 if (unlikely(have_sigbus_pending)) {
1905 qemu_mutex_lock_iothread();
1906 kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
1907 pending_sigbus_addr);
1908 have_sigbus_pending = false;
1909 qemu_mutex_unlock_iothread();
1911 #endif
1913 if (run_ret < 0) {
1914 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1915 DPRINTF("io window exit\n");
1916 kvm_eat_signals(cpu);
1917 ret = EXCP_INTERRUPT;
1918 break;
1920 fprintf(stderr, "error: kvm run failed %s\n",
1921 strerror(-run_ret));
1922 #ifdef TARGET_PPC
1923 if (run_ret == -EBUSY) {
1924 fprintf(stderr,
1925 "This is probably because your SMT is enabled.\n"
1926 "VCPU can only run on primary threads with all "
1927 "secondary threads offline.\n");
1929 #endif
1930 ret = -1;
1931 break;
1934 trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
1935 switch (run->exit_reason) {
1936 case KVM_EXIT_IO:
1937 DPRINTF("handle_io\n");
1938 /* Called outside BQL */
1939 kvm_handle_io(run->io.port, attrs,
1940 (uint8_t *)run + run->io.data_offset,
1941 run->io.direction,
1942 run->io.size,
1943 run->io.count);
1944 ret = 0;
1945 break;
1946 case KVM_EXIT_MMIO:
1947 DPRINTF("handle_mmio\n");
1948 /* Called outside BQL */
1949 address_space_rw(&address_space_memory,
1950 run->mmio.phys_addr, attrs,
1951 run->mmio.data,
1952 run->mmio.len,
1953 run->mmio.is_write);
1954 ret = 0;
1955 break;
1956 case KVM_EXIT_IRQ_WINDOW_OPEN:
1957 DPRINTF("irq_window_open\n");
1958 ret = EXCP_INTERRUPT;
1959 break;
1960 case KVM_EXIT_SHUTDOWN:
1961 DPRINTF("shutdown\n");
1962 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
1963 ret = EXCP_INTERRUPT;
1964 break;
1965 case KVM_EXIT_UNKNOWN:
1966 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1967 (uint64_t)run->hw.hardware_exit_reason);
1968 ret = -1;
1969 break;
1970 case KVM_EXIT_INTERNAL_ERROR:
1971 ret = kvm_handle_internal_error(cpu, run);
1972 break;
1973 case KVM_EXIT_SYSTEM_EVENT:
1974 switch (run->system_event.type) {
1975 case KVM_SYSTEM_EVENT_SHUTDOWN:
1976 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
1977 ret = EXCP_INTERRUPT;
1978 break;
1979 case KVM_SYSTEM_EVENT_RESET:
1980 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
1981 ret = EXCP_INTERRUPT;
1982 break;
1983 case KVM_SYSTEM_EVENT_CRASH:
1984 kvm_cpu_synchronize_state(cpu);
1985 qemu_mutex_lock_iothread();
1986 qemu_system_guest_panicked(cpu_get_crash_info(cpu));
1987 qemu_mutex_unlock_iothread();
1988 ret = 0;
1989 break;
1990 default:
1991 DPRINTF("kvm_arch_handle_exit\n");
1992 ret = kvm_arch_handle_exit(cpu, run);
1993 break;
1995 break;
1996 default:
1997 DPRINTF("kvm_arch_handle_exit\n");
1998 ret = kvm_arch_handle_exit(cpu, run);
1999 break;
2001 } while (ret == 0);
2003 cpu_exec_end(cpu);
2004 qemu_mutex_lock_iothread();
2006 if (ret < 0) {
2007 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
2008 vm_stop(RUN_STATE_INTERNAL_ERROR);
2011 atomic_set(&cpu->exit_request, 0);
2012 return ret;
2015 int kvm_ioctl(KVMState *s, int type, ...)
2017 int ret;
2018 void *arg;
2019 va_list ap;
2021 va_start(ap, type);
2022 arg = va_arg(ap, void *);
2023 va_end(ap);
2025 trace_kvm_ioctl(type, arg);
2026 ret = ioctl(s->fd, type, arg);
2027 if (ret == -1) {
2028 ret = -errno;
2030 return ret;
2033 int kvm_vm_ioctl(KVMState *s, int type, ...)
2035 int ret;
2036 void *arg;
2037 va_list ap;
2039 va_start(ap, type);
2040 arg = va_arg(ap, void *);
2041 va_end(ap);
2043 trace_kvm_vm_ioctl(type, arg);
2044 ret = ioctl(s->vmfd, type, arg);
2045 if (ret == -1) {
2046 ret = -errno;
2048 return ret;
2051 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
2053 int ret;
2054 void *arg;
2055 va_list ap;
2057 va_start(ap, type);
2058 arg = va_arg(ap, void *);
2059 va_end(ap);
2061 trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
2062 ret = ioctl(cpu->kvm_fd, type, arg);
2063 if (ret == -1) {
2064 ret = -errno;
2066 return ret;
2069 int kvm_device_ioctl(int fd, int type, ...)
2071 int ret;
2072 void *arg;
2073 va_list ap;
2075 va_start(ap, type);
2076 arg = va_arg(ap, void *);
2077 va_end(ap);
2079 trace_kvm_device_ioctl(fd, type, arg);
2080 ret = ioctl(fd, type, arg);
2081 if (ret == -1) {
2082 ret = -errno;
2084 return ret;
2087 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
2089 int ret;
2090 struct kvm_device_attr attribute = {
2091 .group = group,
2092 .attr = attr,
2095 if (!kvm_vm_attributes_allowed) {
2096 return 0;
2099 ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
2100 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2101 return ret ? 0 : 1;
2104 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
2106 struct kvm_device_attr attribute = {
2107 .group = group,
2108 .attr = attr,
2109 .flags = 0,
2112 return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
2115 int kvm_device_access(int fd, int group, uint64_t attr,
2116 void *val, bool write, Error **errp)
2118 struct kvm_device_attr kvmattr;
2119 int err;
2121 kvmattr.flags = 0;
2122 kvmattr.group = group;
2123 kvmattr.attr = attr;
2124 kvmattr.addr = (uintptr_t)val;
2126 err = kvm_device_ioctl(fd,
2127 write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
2128 &kvmattr);
2129 if (err < 0) {
2130 error_setg_errno(errp, -err,
2131 "KVM_%s_DEVICE_ATTR failed: Group %d "
2132 "attr 0x%016" PRIx64,
2133 write ? "SET" : "GET", group, attr);
2135 return err;
2138 bool kvm_has_sync_mmu(void)
2140 return kvm_state->sync_mmu;
2143 int kvm_has_vcpu_events(void)
2145 return kvm_state->vcpu_events;
2148 int kvm_has_robust_singlestep(void)
2150 return kvm_state->robust_singlestep;
2153 int kvm_has_debugregs(void)
2155 return kvm_state->debugregs;
2158 int kvm_has_many_ioeventfds(void)
2160 if (!kvm_enabled()) {
2161 return 0;
2163 return kvm_state->many_ioeventfds;
2166 int kvm_has_gsi_routing(void)
2168 #ifdef KVM_CAP_IRQ_ROUTING
2169 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
2170 #else
2171 return false;
2172 #endif
2175 int kvm_has_intx_set_mask(void)
2177 return kvm_state->intx_set_mask;
2180 bool kvm_arm_supports_user_irq(void)
2182 return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
2185 #ifdef KVM_CAP_SET_GUEST_DEBUG
2186 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
2187 target_ulong pc)
2189 struct kvm_sw_breakpoint *bp;
2191 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
2192 if (bp->pc == pc) {
2193 return bp;
2196 return NULL;
2199 int kvm_sw_breakpoints_active(CPUState *cpu)
2201 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
2204 struct kvm_set_guest_debug_data {
2205 struct kvm_guest_debug dbg;
2206 int err;
2209 static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
2211 struct kvm_set_guest_debug_data *dbg_data =
2212 (struct kvm_set_guest_debug_data *) data.host_ptr;
2214 dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
2215 &dbg_data->dbg);
2218 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2220 struct kvm_set_guest_debug_data data;
2222 data.dbg.control = reinject_trap;
2224 if (cpu->singlestep_enabled) {
2225 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2227 kvm_arch_update_guest_debug(cpu, &data.dbg);
2229 run_on_cpu(cpu, kvm_invoke_set_guest_debug,
2230 RUN_ON_CPU_HOST_PTR(&data));
2231 return data.err;
2234 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2235 target_ulong len, int type)
2237 struct kvm_sw_breakpoint *bp;
2238 int err;
2240 if (type == GDB_BREAKPOINT_SW) {
2241 bp = kvm_find_sw_breakpoint(cpu, addr);
2242 if (bp) {
2243 bp->use_count++;
2244 return 0;
2247 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2248 bp->pc = addr;
2249 bp->use_count = 1;
2250 err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2251 if (err) {
2252 g_free(bp);
2253 return err;
2256 QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2257 } else {
2258 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2259 if (err) {
2260 return err;
2264 CPU_FOREACH(cpu) {
2265 err = kvm_update_guest_debug(cpu, 0);
2266 if (err) {
2267 return err;
2270 return 0;
2273 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2274 target_ulong len, int type)
2276 struct kvm_sw_breakpoint *bp;
2277 int err;
2279 if (type == GDB_BREAKPOINT_SW) {
2280 bp = kvm_find_sw_breakpoint(cpu, addr);
2281 if (!bp) {
2282 return -ENOENT;
2285 if (bp->use_count > 1) {
2286 bp->use_count--;
2287 return 0;
2290 err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2291 if (err) {
2292 return err;
2295 QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2296 g_free(bp);
2297 } else {
2298 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2299 if (err) {
2300 return err;
2304 CPU_FOREACH(cpu) {
2305 err = kvm_update_guest_debug(cpu, 0);
2306 if (err) {
2307 return err;
2310 return 0;
2313 void kvm_remove_all_breakpoints(CPUState *cpu)
2315 struct kvm_sw_breakpoint *bp, *next;
2316 KVMState *s = cpu->kvm_state;
2317 CPUState *tmpcpu;
2319 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2320 if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2321 /* Try harder to find a CPU that currently sees the breakpoint. */
2322 CPU_FOREACH(tmpcpu) {
2323 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2324 break;
2328 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2329 g_free(bp);
2331 kvm_arch_remove_all_hw_breakpoints();
2333 CPU_FOREACH(cpu) {
2334 kvm_update_guest_debug(cpu, 0);
2338 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2340 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2342 return -EINVAL;
2345 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2346 target_ulong len, int type)
2348 return -EINVAL;
2351 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2352 target_ulong len, int type)
2354 return -EINVAL;
2357 void kvm_remove_all_breakpoints(CPUState *cpu)
2360 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2362 static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2364 KVMState *s = kvm_state;
2365 struct kvm_signal_mask *sigmask;
2366 int r;
2368 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2370 sigmask->len = s->sigmask_len;
2371 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2372 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2373 g_free(sigmask);
2375 return r;
2378 static void kvm_ipi_signal(int sig)
2380 if (current_cpu) {
2381 assert(kvm_immediate_exit);
2382 kvm_cpu_kick(current_cpu);
2386 void kvm_init_cpu_signals(CPUState *cpu)
2388 int r;
2389 sigset_t set;
2390 struct sigaction sigact;
2392 memset(&sigact, 0, sizeof(sigact));
2393 sigact.sa_handler = kvm_ipi_signal;
2394 sigaction(SIG_IPI, &sigact, NULL);
2396 pthread_sigmask(SIG_BLOCK, NULL, &set);
2397 #if defined KVM_HAVE_MCE_INJECTION
2398 sigdelset(&set, SIGBUS);
2399 pthread_sigmask(SIG_SETMASK, &set, NULL);
2400 #endif
2401 sigdelset(&set, SIG_IPI);
2402 if (kvm_immediate_exit) {
2403 r = pthread_sigmask(SIG_SETMASK, &set, NULL);
2404 } else {
2405 r = kvm_set_signal_mask(cpu, &set);
2407 if (r) {
2408 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
2409 exit(1);
2413 /* Called asynchronously in VCPU thread. */
2414 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2416 #ifdef KVM_HAVE_MCE_INJECTION
2417 if (have_sigbus_pending) {
2418 return 1;
2420 have_sigbus_pending = true;
2421 pending_sigbus_addr = addr;
2422 pending_sigbus_code = code;
2423 atomic_set(&cpu->exit_request, 1);
2424 return 0;
2425 #else
2426 return 1;
2427 #endif
2430 /* Called synchronously (via signalfd) in main thread. */
2431 int kvm_on_sigbus(int code, void *addr)
2433 #ifdef KVM_HAVE_MCE_INJECTION
2434 /* Action required MCE kills the process if SIGBUS is blocked. Because
2435 * that's what happens in the I/O thread, where we handle MCE via signalfd,
2436 * we can only get action optional here.
2438 assert(code != BUS_MCEERR_AR);
2439 kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
2440 return 0;
2441 #else
2442 return 1;
2443 #endif
2446 int kvm_create_device(KVMState *s, uint64_t type, bool test)
2448 int ret;
2449 struct kvm_create_device create_dev;
2451 create_dev.type = type;
2452 create_dev.fd = -1;
2453 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2455 if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2456 return -ENOTSUP;
2459 ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2460 if (ret) {
2461 return ret;
2464 return test ? 0 : create_dev.fd;
2467 bool kvm_device_supported(int vmfd, uint64_t type)
2469 struct kvm_create_device create_dev = {
2470 .type = type,
2471 .fd = -1,
2472 .flags = KVM_CREATE_DEVICE_TEST,
2475 if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
2476 return false;
2479 return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
2482 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2484 struct kvm_one_reg reg;
2485 int r;
2487 reg.id = id;
2488 reg.addr = (uintptr_t) source;
2489 r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
2490 if (r) {
2491 trace_kvm_failed_reg_set(id, strerror(-r));
2493 return r;
2496 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2498 struct kvm_one_reg reg;
2499 int r;
2501 reg.id = id;
2502 reg.addr = (uintptr_t) target;
2503 r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
2504 if (r) {
2505 trace_kvm_failed_reg_get(id, strerror(-r));
2507 return r;
2510 static void kvm_accel_class_init(ObjectClass *oc, void *data)
2512 AccelClass *ac = ACCEL_CLASS(oc);
2513 ac->name = "KVM";
2514 ac->init_machine = kvm_init;
2515 ac->allowed = &kvm_allowed;
2518 static const TypeInfo kvm_accel_type = {
2519 .name = TYPE_KVM_ACCEL,
2520 .parent = TYPE_ACCEL,
2521 .class_init = kvm_accel_class_init,
2522 .instance_size = sizeof(KVMState),
2525 static void kvm_type_init(void)
2527 type_register_static(&kvm_accel_type);
2530 type_init(kvm_type_init);