4 * Copyright IBM, Corp. 2008
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"
27 #include "hw/pci/msi.h"
28 #include "hw/s390x/adapter.h"
29 #include "exec/gdbstub.h"
30 #include "sysemu/kvm_int.h"
31 #include "qemu/bswap.h"
32 #include "exec/memory.h"
33 #include "exec/ram_addr.h"
34 #include "exec/address-spaces.h"
35 #include "qemu/event_notifier.h"
39 #include "hw/boards.h"
41 /* This check must be after config-host.h is included */
43 #include <sys/eventfd.h>
46 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
47 * need to use the real host PAGE_SIZE, as that's what KVM will use.
49 #define PAGE_SIZE getpagesize()
54 #define DPRINTF(fmt, ...) \
55 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
57 #define DPRINTF(fmt, ...) \
61 #define KVM_MSI_HASHTAB_SIZE 256
63 struct KVMParkedVcpu {
64 unsigned long vcpu_id;
66 QLIST_ENTRY(KVMParkedVcpu) node;
71 AccelState parent_obj;
77 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
78 bool coalesced_flush_in_progress;
79 int broken_set_mem_region;
81 int robust_singlestep;
83 #ifdef KVM_CAP_SET_GUEST_DEBUG
84 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
88 /* The man page (and posix) say ioctl numbers are signed int, but
89 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
90 * unsigned, and treating them as signed here can break things */
91 unsigned irq_set_ioctl;
92 unsigned int sigmask_len;
94 #ifdef KVM_CAP_IRQ_ROUTING
95 struct kvm_irq_routing *irq_routes;
96 int nr_allocated_irq_routes;
97 unsigned long *used_gsi_bitmap;
98 unsigned int gsi_count;
99 QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
101 KVMMemoryListener memory_listener;
102 QLIST_HEAD(, KVMParkedVcpu) kvm_parked_vcpus;
106 bool kvm_kernel_irqchip;
107 bool kvm_split_irqchip;
108 bool kvm_async_interrupts_allowed;
109 bool kvm_halt_in_kernel_allowed;
110 bool kvm_eventfds_allowed;
111 bool kvm_irqfds_allowed;
112 bool kvm_resamplefds_allowed;
113 bool kvm_msi_via_irqfd_allowed;
114 bool kvm_gsi_routing_allowed;
115 bool kvm_gsi_direct_mapping;
117 bool kvm_readonly_mem_allowed;
118 bool kvm_vm_attributes_allowed;
119 bool kvm_direct_msi_allowed;
120 bool kvm_ioeventfd_any_length_allowed;
122 static const KVMCapabilityInfo kvm_required_capabilites[] = {
123 KVM_CAP_INFO(USER_MEMORY),
124 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
128 int kvm_get_max_memslots(void)
130 KVMState *s = KVM_STATE(current_machine->accelerator);
135 static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
137 KVMState *s = kvm_state;
140 for (i = 0; i < s->nr_slots; i++) {
141 if (kml->slots[i].memory_size == 0) {
142 return &kml->slots[i];
149 bool kvm_has_free_slot(MachineState *ms)
151 KVMState *s = KVM_STATE(ms->accelerator);
153 return kvm_get_free_slot(&s->memory_listener);
156 static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
158 KVMSlot *slot = kvm_get_free_slot(kml);
164 fprintf(stderr, "%s: no free slot available\n", __func__);
168 static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
172 KVMState *s = kvm_state;
175 for (i = 0; i < s->nr_slots; i++) {
176 KVMSlot *mem = &kml->slots[i];
178 if (start_addr == mem->start_addr &&
179 end_addr == mem->start_addr + mem->memory_size) {
188 * Find overlapping slot with lowest start address
190 static KVMSlot *kvm_lookup_overlapping_slot(KVMMemoryListener *kml,
194 KVMState *s = kvm_state;
195 KVMSlot *found = NULL;
198 for (i = 0; i < s->nr_slots; i++) {
199 KVMSlot *mem = &kml->slots[i];
201 if (mem->memory_size == 0 ||
202 (found && found->start_addr < mem->start_addr)) {
206 if (end_addr > mem->start_addr &&
207 start_addr < mem->start_addr + mem->memory_size) {
215 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
218 KVMMemoryListener *kml = &s->memory_listener;
221 for (i = 0; i < s->nr_slots; i++) {
222 KVMSlot *mem = &kml->slots[i];
224 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
225 *phys_addr = mem->start_addr + (ram - mem->ram);
233 static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot)
235 KVMState *s = kvm_state;
236 struct kvm_userspace_memory_region mem;
238 mem.slot = slot->slot | (kml->as_id << 16);
239 mem.guest_phys_addr = slot->start_addr;
240 mem.userspace_addr = (unsigned long)slot->ram;
241 mem.flags = slot->flags;
243 if (slot->memory_size && mem.flags & KVM_MEM_READONLY) {
244 /* Set the slot size to 0 before setting the slot to the desired
245 * value. This is needed based on KVM commit 75d61fbc. */
247 kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
249 mem.memory_size = slot->memory_size;
250 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
253 int kvm_destroy_vcpu(CPUState *cpu)
255 KVMState *s = kvm_state;
257 struct KVMParkedVcpu *vcpu = NULL;
260 DPRINTF("kvm_destroy_vcpu\n");
262 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
265 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
269 ret = munmap(cpu->kvm_run, mmap_size);
274 vcpu = g_malloc0(sizeof(*vcpu));
275 vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
276 vcpu->kvm_fd = cpu->kvm_fd;
277 QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
282 static int kvm_get_vcpu(KVMState *s, unsigned long vcpu_id)
284 struct KVMParkedVcpu *cpu;
286 QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
287 if (cpu->vcpu_id == vcpu_id) {
290 QLIST_REMOVE(cpu, node);
291 kvm_fd = cpu->kvm_fd;
297 return kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)vcpu_id);
300 int kvm_init_vcpu(CPUState *cpu)
302 KVMState *s = kvm_state;
306 DPRINTF("kvm_init_vcpu\n");
308 ret = kvm_get_vcpu(s, kvm_arch_vcpu_id(cpu));
310 DPRINTF("kvm_create_vcpu failed\n");
316 cpu->kvm_vcpu_dirty = true;
318 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
321 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
325 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
327 if (cpu->kvm_run == MAP_FAILED) {
329 DPRINTF("mmap'ing vcpu state failed\n");
333 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
334 s->coalesced_mmio_ring =
335 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
338 ret = kvm_arch_init_vcpu(cpu);
344 * dirty pages logging control
347 static int kvm_mem_flags(MemoryRegion *mr)
349 bool readonly = mr->readonly || memory_region_is_romd(mr);
352 if (memory_region_get_dirty_log_mask(mr) != 0) {
353 flags |= KVM_MEM_LOG_DIRTY_PAGES;
355 if (readonly && kvm_readonly_mem_allowed) {
356 flags |= KVM_MEM_READONLY;
361 static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
366 old_flags = mem->flags;
367 mem->flags = kvm_mem_flags(mr);
369 /* If nothing changed effectively, no need to issue ioctl */
370 if (mem->flags == old_flags) {
374 return kvm_set_user_memory_region(kml, mem);
377 static int kvm_section_update_flags(KVMMemoryListener *kml,
378 MemoryRegionSection *section)
380 hwaddr phys_addr = section->offset_within_address_space;
381 ram_addr_t size = int128_get64(section->size);
382 KVMSlot *mem = kvm_lookup_matching_slot(kml, phys_addr, phys_addr + size);
387 return kvm_slot_update_flags(kml, mem, section->mr);
391 static void kvm_log_start(MemoryListener *listener,
392 MemoryRegionSection *section,
395 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
402 r = kvm_section_update_flags(kml, section);
408 static void kvm_log_stop(MemoryListener *listener,
409 MemoryRegionSection *section,
412 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
419 r = kvm_section_update_flags(kml, section);
425 /* get kvm's dirty pages bitmap and update qemu's */
426 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
427 unsigned long *bitmap)
429 ram_addr_t start = section->offset_within_region +
430 memory_region_get_ram_addr(section->mr);
431 ram_addr_t pages = int128_get64(section->size) / getpagesize();
433 cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
437 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
440 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
441 * This function updates qemu's dirty bitmap using
442 * memory_region_set_dirty(). This means all bits are set
445 * @start_add: start of logged region.
446 * @end_addr: end of logged region.
448 static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
449 MemoryRegionSection *section)
451 KVMState *s = kvm_state;
452 unsigned long size, allocated_size = 0;
453 struct kvm_dirty_log d = {};
456 hwaddr start_addr = section->offset_within_address_space;
457 hwaddr end_addr = start_addr + int128_get64(section->size);
459 d.dirty_bitmap = NULL;
460 while (start_addr < end_addr) {
461 mem = kvm_lookup_overlapping_slot(kml, start_addr, end_addr);
466 /* XXX bad kernel interface alert
467 * For dirty bitmap, kernel allocates array of size aligned to
468 * bits-per-long. But for case when the kernel is 64bits and
469 * the userspace is 32bits, userspace can't align to the same
470 * bits-per-long, since sizeof(long) is different between kernel
471 * and user space. This way, userspace will provide buffer which
472 * may be 4 bytes less than the kernel will use, resulting in
473 * userspace memory corruption (which is not detectable by valgrind
474 * too, in most cases).
475 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
476 * a hope that sizeof(long) won't become >8 any time soon.
478 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
479 /*HOST_LONG_BITS*/ 64) / 8;
480 if (!d.dirty_bitmap) {
481 d.dirty_bitmap = g_malloc(size);
482 } else if (size > allocated_size) {
483 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
485 allocated_size = size;
486 memset(d.dirty_bitmap, 0, allocated_size);
488 d.slot = mem->slot | (kml->as_id << 16);
489 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
490 DPRINTF("ioctl failed %d\n", errno);
495 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
496 start_addr = mem->start_addr + mem->memory_size;
498 g_free(d.dirty_bitmap);
503 static void kvm_coalesce_mmio_region(MemoryListener *listener,
504 MemoryRegionSection *secion,
505 hwaddr start, hwaddr size)
507 KVMState *s = kvm_state;
509 if (s->coalesced_mmio) {
510 struct kvm_coalesced_mmio_zone zone;
516 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
520 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
521 MemoryRegionSection *secion,
522 hwaddr start, hwaddr size)
524 KVMState *s = kvm_state;
526 if (s->coalesced_mmio) {
527 struct kvm_coalesced_mmio_zone zone;
533 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
537 int kvm_check_extension(KVMState *s, unsigned int extension)
541 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
549 int kvm_vm_check_extension(KVMState *s, unsigned int extension)
553 ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
555 /* VM wide version not implemented, use global one instead */
556 ret = kvm_check_extension(s, extension);
562 static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
564 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
565 /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
566 * endianness, but the memory core hands them in target endianness.
567 * For example, PPC is always treated as big-endian even if running
568 * on KVM and on PPC64LE. Correct here.
582 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
583 bool assign, uint32_t size, bool datamatch)
586 struct kvm_ioeventfd iofd = {
587 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
594 if (!kvm_enabled()) {
599 iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
602 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
605 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
614 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
615 bool assign, uint32_t size, bool datamatch)
617 struct kvm_ioeventfd kick = {
618 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
620 .flags = KVM_IOEVENTFD_FLAG_PIO,
625 if (!kvm_enabled()) {
629 kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
632 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
634 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
642 static int kvm_check_many_ioeventfds(void)
644 /* Userspace can use ioeventfd for io notification. This requires a host
645 * that supports eventfd(2) and an I/O thread; since eventfd does not
646 * support SIGIO it cannot interrupt the vcpu.
648 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
649 * can avoid creating too many ioeventfds.
651 #if defined(CONFIG_EVENTFD)
654 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
655 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
656 if (ioeventfds[i] < 0) {
659 ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
661 close(ioeventfds[i]);
666 /* Decide whether many devices are supported or not */
667 ret = i == ARRAY_SIZE(ioeventfds);
670 kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
671 close(ioeventfds[i]);
679 static const KVMCapabilityInfo *
680 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
683 if (!kvm_check_extension(s, list->value)) {
691 static void kvm_set_phys_mem(KVMMemoryListener *kml,
692 MemoryRegionSection *section, bool add)
694 KVMState *s = kvm_state;
697 MemoryRegion *mr = section->mr;
698 bool writeable = !mr->readonly && !mr->rom_device;
699 hwaddr start_addr = section->offset_within_address_space;
700 ram_addr_t size = int128_get64(section->size);
704 /* kvm works in page size chunks, but the function may be called
705 with sub-page size and unaligned start address. Pad the start
706 address to next and truncate size to previous page boundary. */
707 delta = qemu_real_host_page_size - (start_addr & ~qemu_real_host_page_mask);
708 delta &= ~qemu_real_host_page_mask;
714 size &= qemu_real_host_page_mask;
715 if (!size || (start_addr & ~qemu_real_host_page_mask)) {
719 if (!memory_region_is_ram(mr)) {
720 if (writeable || !kvm_readonly_mem_allowed) {
722 } else if (!mr->romd_mode) {
723 /* If the memory device is not in romd_mode, then we actually want
724 * to remove the kvm memory slot so all accesses will trap. */
729 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
732 mem = kvm_lookup_overlapping_slot(kml, start_addr, start_addr + size);
737 if (add && start_addr >= mem->start_addr &&
738 (start_addr + size <= mem->start_addr + mem->memory_size) &&
739 (ram - start_addr == mem->ram - mem->start_addr)) {
740 /* The new slot fits into the existing one and comes with
741 * identical parameters - update flags and done. */
742 kvm_slot_update_flags(kml, mem, mr);
748 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
749 kvm_physical_sync_dirty_bitmap(kml, section);
752 /* unregister the overlapping slot */
753 mem->memory_size = 0;
754 err = kvm_set_user_memory_region(kml, mem);
756 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
757 __func__, strerror(-err));
761 /* Workaround for older KVM versions: we can't join slots, even not by
762 * unregistering the previous ones and then registering the larger
763 * slot. We have to maintain the existing fragmentation. Sigh.
765 * This workaround assumes that the new slot starts at the same
766 * address as the first existing one. If not or if some overlapping
767 * slot comes around later, we will fail (not seen in practice so far)
768 * - and actually require a recent KVM version. */
769 if (s->broken_set_mem_region &&
770 old.start_addr == start_addr && old.memory_size < size && add) {
771 mem = kvm_alloc_slot(kml);
772 mem->memory_size = old.memory_size;
773 mem->start_addr = old.start_addr;
775 mem->flags = kvm_mem_flags(mr);
777 err = kvm_set_user_memory_region(kml, mem);
779 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
784 start_addr += old.memory_size;
785 ram += old.memory_size;
786 size -= old.memory_size;
790 /* register prefix slot */
791 if (old.start_addr < start_addr) {
792 mem = kvm_alloc_slot(kml);
793 mem->memory_size = start_addr - old.start_addr;
794 mem->start_addr = old.start_addr;
796 mem->flags = kvm_mem_flags(mr);
798 err = kvm_set_user_memory_region(kml, mem);
800 fprintf(stderr, "%s: error registering prefix slot: %s\n",
801 __func__, strerror(-err));
803 fprintf(stderr, "%s: This is probably because your kernel's " \
804 "PAGE_SIZE is too big. Please try to use 4k " \
805 "PAGE_SIZE!\n", __func__);
811 /* register suffix slot */
812 if (old.start_addr + old.memory_size > start_addr + size) {
813 ram_addr_t size_delta;
815 mem = kvm_alloc_slot(kml);
816 mem->start_addr = start_addr + size;
817 size_delta = mem->start_addr - old.start_addr;
818 mem->memory_size = old.memory_size - size_delta;
819 mem->ram = old.ram + size_delta;
820 mem->flags = kvm_mem_flags(mr);
822 err = kvm_set_user_memory_region(kml, mem);
824 fprintf(stderr, "%s: error registering suffix slot: %s\n",
825 __func__, strerror(-err));
831 /* in case the KVM bug workaround already "consumed" the new slot */
838 mem = kvm_alloc_slot(kml);
839 mem->memory_size = size;
840 mem->start_addr = start_addr;
842 mem->flags = kvm_mem_flags(mr);
844 err = kvm_set_user_memory_region(kml, mem);
846 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
852 static void kvm_region_add(MemoryListener *listener,
853 MemoryRegionSection *section)
855 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
857 memory_region_ref(section->mr);
858 kvm_set_phys_mem(kml, section, true);
861 static void kvm_region_del(MemoryListener *listener,
862 MemoryRegionSection *section)
864 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
866 kvm_set_phys_mem(kml, section, false);
867 memory_region_unref(section->mr);
870 static void kvm_log_sync(MemoryListener *listener,
871 MemoryRegionSection *section)
873 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
876 r = kvm_physical_sync_dirty_bitmap(kml, section);
882 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
883 MemoryRegionSection *section,
884 bool match_data, uint64_t data,
887 int fd = event_notifier_get_fd(e);
890 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
891 data, true, int128_get64(section->size),
894 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
895 __func__, strerror(-r));
900 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
901 MemoryRegionSection *section,
902 bool match_data, uint64_t data,
905 int fd = event_notifier_get_fd(e);
908 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
909 data, false, int128_get64(section->size),
916 static void kvm_io_ioeventfd_add(MemoryListener *listener,
917 MemoryRegionSection *section,
918 bool match_data, uint64_t data,
921 int fd = event_notifier_get_fd(e);
924 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
925 data, true, int128_get64(section->size),
928 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
929 __func__, strerror(-r));
934 static void kvm_io_ioeventfd_del(MemoryListener *listener,
935 MemoryRegionSection *section,
936 bool match_data, uint64_t data,
940 int fd = event_notifier_get_fd(e);
943 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
944 data, false, int128_get64(section->size),
951 void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
952 AddressSpace *as, int as_id)
956 kml->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
959 for (i = 0; i < s->nr_slots; i++) {
960 kml->slots[i].slot = i;
963 kml->listener.region_add = kvm_region_add;
964 kml->listener.region_del = kvm_region_del;
965 kml->listener.log_start = kvm_log_start;
966 kml->listener.log_stop = kvm_log_stop;
967 kml->listener.log_sync = kvm_log_sync;
968 kml->listener.priority = 10;
970 memory_listener_register(&kml->listener, as);
973 static MemoryListener kvm_io_listener = {
974 .eventfd_add = kvm_io_ioeventfd_add,
975 .eventfd_del = kvm_io_ioeventfd_del,
979 static void kvm_handle_interrupt(CPUState *cpu, int mask)
981 cpu->interrupt_request |= mask;
983 if (!qemu_cpu_is_self(cpu)) {
988 int kvm_set_irq(KVMState *s, int irq, int level)
990 struct kvm_irq_level event;
993 assert(kvm_async_interrupts_enabled());
997 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
999 perror("kvm_set_irq");
1003 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
1006 #ifdef KVM_CAP_IRQ_ROUTING
1007 typedef struct KVMMSIRoute {
1008 struct kvm_irq_routing_entry kroute;
1009 QTAILQ_ENTRY(KVMMSIRoute) entry;
1012 static void set_gsi(KVMState *s, unsigned int gsi)
1014 set_bit(gsi, s->used_gsi_bitmap);
1017 static void clear_gsi(KVMState *s, unsigned int gsi)
1019 clear_bit(gsi, s->used_gsi_bitmap);
1022 void kvm_init_irq_routing(KVMState *s)
1026 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
1027 if (gsi_count > 0) {
1028 /* Round up so we can search ints using ffs */
1029 s->used_gsi_bitmap = bitmap_new(gsi_count);
1030 s->gsi_count = gsi_count;
1033 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
1034 s->nr_allocated_irq_routes = 0;
1036 if (!kvm_direct_msi_allowed) {
1037 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
1038 QTAILQ_INIT(&s->msi_hashtab[i]);
1042 kvm_arch_init_irq_routing(s);
1045 void kvm_irqchip_commit_routes(KVMState *s)
1049 s->irq_routes->flags = 0;
1050 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1054 static void kvm_add_routing_entry(KVMState *s,
1055 struct kvm_irq_routing_entry *entry)
1057 struct kvm_irq_routing_entry *new;
1060 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1061 n = s->nr_allocated_irq_routes * 2;
1065 size = sizeof(struct kvm_irq_routing);
1066 size += n * sizeof(*new);
1067 s->irq_routes = g_realloc(s->irq_routes, size);
1068 s->nr_allocated_irq_routes = n;
1070 n = s->irq_routes->nr++;
1071 new = &s->irq_routes->entries[n];
1075 set_gsi(s, entry->gsi);
1078 static int kvm_update_routing_entry(KVMState *s,
1079 struct kvm_irq_routing_entry *new_entry)
1081 struct kvm_irq_routing_entry *entry;
1084 for (n = 0; n < s->irq_routes->nr; n++) {
1085 entry = &s->irq_routes->entries[n];
1086 if (entry->gsi != new_entry->gsi) {
1090 if(!memcmp(entry, new_entry, sizeof *entry)) {
1094 *entry = *new_entry;
1096 kvm_irqchip_commit_routes(s);
1104 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1106 struct kvm_irq_routing_entry e = {};
1108 assert(pin < s->gsi_count);
1111 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1113 e.u.irqchip.irqchip = irqchip;
1114 e.u.irqchip.pin = pin;
1115 kvm_add_routing_entry(s, &e);
1118 void kvm_irqchip_release_virq(KVMState *s, int virq)
1120 struct kvm_irq_routing_entry *e;
1123 if (kvm_gsi_direct_mapping()) {
1127 for (i = 0; i < s->irq_routes->nr; i++) {
1128 e = &s->irq_routes->entries[i];
1129 if (e->gsi == virq) {
1130 s->irq_routes->nr--;
1131 *e = s->irq_routes->entries[s->irq_routes->nr];
1137 static unsigned int kvm_hash_msi(uint32_t data)
1139 /* This is optimized for IA32 MSI layout. However, no other arch shall
1140 * repeat the mistake of not providing a direct MSI injection API. */
1144 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1146 KVMMSIRoute *route, *next;
1149 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1150 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1151 kvm_irqchip_release_virq(s, route->kroute.gsi);
1152 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1158 static int kvm_irqchip_get_virq(KVMState *s)
1163 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1164 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1165 * number can succeed even though a new route entry cannot be added.
1166 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1168 if (!kvm_direct_msi_allowed && s->irq_routes->nr == s->gsi_count) {
1169 kvm_flush_dynamic_msi_routes(s);
1172 /* Return the lowest unused GSI in the bitmap */
1173 next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
1174 if (next_virq >= s->gsi_count) {
1181 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1183 unsigned int hash = kvm_hash_msi(msg.data);
1186 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1187 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1188 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1189 route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1196 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1201 if (kvm_direct_msi_allowed) {
1202 msi.address_lo = (uint32_t)msg.address;
1203 msi.address_hi = msg.address >> 32;
1204 msi.data = le32_to_cpu(msg.data);
1206 memset(msi.pad, 0, sizeof(msi.pad));
1208 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1211 route = kvm_lookup_msi_route(s, msg);
1215 virq = kvm_irqchip_get_virq(s);
1220 route = g_malloc0(sizeof(KVMMSIRoute));
1221 route->kroute.gsi = virq;
1222 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1223 route->kroute.flags = 0;
1224 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1225 route->kroute.u.msi.address_hi = msg.address >> 32;
1226 route->kroute.u.msi.data = le32_to_cpu(msg.data);
1228 kvm_add_routing_entry(s, &route->kroute);
1229 kvm_irqchip_commit_routes(s);
1231 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1235 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1237 return kvm_set_irq(s, route->kroute.gsi, 1);
1240 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg, PCIDevice *dev)
1242 struct kvm_irq_routing_entry kroute = {};
1245 if (kvm_gsi_direct_mapping()) {
1246 return kvm_arch_msi_data_to_gsi(msg.data);
1249 if (!kvm_gsi_routing_enabled()) {
1253 virq = kvm_irqchip_get_virq(s);
1259 kroute.type = KVM_IRQ_ROUTING_MSI;
1261 kroute.u.msi.address_lo = (uint32_t)msg.address;
1262 kroute.u.msi.address_hi = msg.address >> 32;
1263 kroute.u.msi.data = le32_to_cpu(msg.data);
1264 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1265 kvm_irqchip_release_virq(s, virq);
1269 kvm_add_routing_entry(s, &kroute);
1270 kvm_irqchip_commit_routes(s);
1275 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
1278 struct kvm_irq_routing_entry kroute = {};
1280 if (kvm_gsi_direct_mapping()) {
1284 if (!kvm_irqchip_in_kernel()) {
1289 kroute.type = KVM_IRQ_ROUTING_MSI;
1291 kroute.u.msi.address_lo = (uint32_t)msg.address;
1292 kroute.u.msi.address_hi = msg.address >> 32;
1293 kroute.u.msi.data = le32_to_cpu(msg.data);
1294 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1298 return kvm_update_routing_entry(s, &kroute);
1301 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int rfd, int virq,
1304 struct kvm_irqfd irqfd = {
1307 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1311 irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1312 irqfd.resamplefd = rfd;
1315 if (!kvm_irqfds_enabled()) {
1319 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1322 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1324 struct kvm_irq_routing_entry kroute = {};
1327 if (!kvm_gsi_routing_enabled()) {
1331 virq = kvm_irqchip_get_virq(s);
1337 kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1339 kroute.u.adapter.summary_addr = adapter->summary_addr;
1340 kroute.u.adapter.ind_addr = adapter->ind_addr;
1341 kroute.u.adapter.summary_offset = adapter->summary_offset;
1342 kroute.u.adapter.ind_offset = adapter->ind_offset;
1343 kroute.u.adapter.adapter_id = adapter->adapter_id;
1345 kvm_add_routing_entry(s, &kroute);
1350 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1352 struct kvm_irq_routing_entry kroute = {};
1355 if (!kvm_gsi_routing_enabled()) {
1358 if (!kvm_check_extension(s, KVM_CAP_HYPERV_SYNIC)) {
1361 virq = kvm_irqchip_get_virq(s);
1367 kroute.type = KVM_IRQ_ROUTING_HV_SINT;
1369 kroute.u.hv_sint.vcpu = vcpu;
1370 kroute.u.hv_sint.sint = sint;
1372 kvm_add_routing_entry(s, &kroute);
1373 kvm_irqchip_commit_routes(s);
1378 #else /* !KVM_CAP_IRQ_ROUTING */
1380 void kvm_init_irq_routing(KVMState *s)
1384 void kvm_irqchip_release_virq(KVMState *s, int virq)
1388 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1393 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1398 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1403 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1408 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1413 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1417 #endif /* !KVM_CAP_IRQ_ROUTING */
1419 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1420 EventNotifier *rn, int virq)
1422 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n),
1423 rn ? event_notifier_get_fd(rn) : -1, virq, true);
1426 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1429 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), -1, virq,
1433 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1434 EventNotifier *rn, qemu_irq irq)
1437 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1442 return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
1445 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
1449 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1454 return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
1457 void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
1459 g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
1462 static void kvm_irqchip_create(MachineState *machine, KVMState *s)
1466 if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
1468 } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
1469 ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
1471 fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
1478 /* First probe and see if there's a arch-specific hook to create the
1479 * in-kernel irqchip for us */
1480 ret = kvm_arch_irqchip_create(machine, s);
1482 if (machine_kernel_irqchip_split(machine)) {
1483 perror("Split IRQ chip mode not supported.");
1486 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1490 fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
1494 kvm_kernel_irqchip = true;
1495 /* If we have an in-kernel IRQ chip then we must have asynchronous
1496 * interrupt delivery (though the reverse is not necessarily true)
1498 kvm_async_interrupts_allowed = true;
1499 kvm_halt_in_kernel_allowed = true;
1501 kvm_init_irq_routing(s);
1503 s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
1506 /* Find number of supported CPUs using the recommended
1507 * procedure from the kernel API documentation to cope with
1508 * older kernels that may be missing capabilities.
1510 static int kvm_recommended_vcpus(KVMState *s)
1512 int ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
1513 return (ret) ? ret : 4;
1516 static int kvm_max_vcpus(KVMState *s)
1518 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1519 return (ret) ? ret : kvm_recommended_vcpus(s);
1522 bool kvm_vcpu_id_is_valid(int vcpu_id)
1524 KVMState *s = KVM_STATE(current_machine->accelerator);
1525 return vcpu_id >= 0 && vcpu_id < kvm_max_vcpus(s);
1528 static int kvm_init(MachineState *ms)
1530 MachineClass *mc = MACHINE_GET_CLASS(ms);
1531 static const char upgrade_note[] =
1532 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1533 "(see http://sourceforge.net/projects/kvm).\n";
1538 { "SMP", smp_cpus },
1539 { "hotpluggable", max_cpus },
1542 int soft_vcpus_limit, hard_vcpus_limit;
1544 const KVMCapabilityInfo *missing_cap;
1547 const char *kvm_type;
1549 s = KVM_STATE(ms->accelerator);
1552 * On systems where the kernel can support different base page
1553 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1554 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1555 * page size for the system though.
1557 assert(TARGET_PAGE_SIZE <= getpagesize());
1561 #ifdef KVM_CAP_SET_GUEST_DEBUG
1562 QTAILQ_INIT(&s->kvm_sw_breakpoints);
1564 QLIST_INIT(&s->kvm_parked_vcpus);
1566 s->fd = qemu_open("/dev/kvm", O_RDWR);
1568 fprintf(stderr, "Could not access KVM kernel module: %m\n");
1573 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1574 if (ret < KVM_API_VERSION) {
1578 fprintf(stderr, "kvm version too old\n");
1582 if (ret > KVM_API_VERSION) {
1584 fprintf(stderr, "kvm version not supported\n");
1588 s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
1590 /* If unspecified, use the default value */
1595 /* check the vcpu limits */
1596 soft_vcpus_limit = kvm_recommended_vcpus(s);
1597 hard_vcpus_limit = kvm_max_vcpus(s);
1600 if (nc->num > soft_vcpus_limit) {
1602 "Warning: Number of %s cpus requested (%d) exceeds "
1603 "the recommended cpus supported by KVM (%d)\n",
1604 nc->name, nc->num, soft_vcpus_limit);
1606 if (nc->num > hard_vcpus_limit) {
1607 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
1608 "the maximum cpus supported by KVM (%d)\n",
1609 nc->name, nc->num, hard_vcpus_limit);
1616 kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1618 type = mc->kvm_type(kvm_type);
1619 } else if (kvm_type) {
1621 fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1626 ret = kvm_ioctl(s, KVM_CREATE_VM, type);
1627 } while (ret == -EINTR);
1630 fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
1634 if (ret == -EINVAL) {
1636 "Host kernel setup problem detected. Please verify:\n");
1637 fprintf(stderr, "- for kernels supporting the switch_amode or"
1638 " user_mode parameters, whether\n");
1640 " user space is running in primary address space\n");
1642 "- for kernels supporting the vm.allocate_pgste sysctl, "
1643 "whether it is enabled\n");
1650 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1653 kvm_check_extension_list(s, kvm_arch_required_capabilities);
1657 fprintf(stderr, "kvm does not support %s\n%s",
1658 missing_cap->name, upgrade_note);
1662 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1664 s->broken_set_mem_region = 1;
1665 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
1667 s->broken_set_mem_region = 0;
1670 #ifdef KVM_CAP_VCPU_EVENTS
1671 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1674 s->robust_singlestep =
1675 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1677 #ifdef KVM_CAP_DEBUGREGS
1678 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1681 #ifdef KVM_CAP_IRQ_ROUTING
1682 kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1685 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1687 s->irq_set_ioctl = KVM_IRQ_LINE;
1688 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1689 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1692 #ifdef KVM_CAP_READONLY_MEM
1693 kvm_readonly_mem_allowed =
1694 (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1697 kvm_eventfds_allowed =
1698 (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
1700 kvm_irqfds_allowed =
1701 (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
1703 kvm_resamplefds_allowed =
1704 (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
1706 kvm_vm_attributes_allowed =
1707 (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
1709 kvm_ioeventfd_any_length_allowed =
1710 (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
1712 ret = kvm_arch_init(ms, s);
1717 if (machine_kernel_irqchip_allowed(ms)) {
1718 kvm_irqchip_create(ms, s);
1723 if (kvm_eventfds_allowed) {
1724 s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
1725 s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
1727 s->memory_listener.listener.coalesced_mmio_add = kvm_coalesce_mmio_region;
1728 s->memory_listener.listener.coalesced_mmio_del = kvm_uncoalesce_mmio_region;
1730 kvm_memory_listener_register(s, &s->memory_listener,
1731 &address_space_memory, 0);
1732 memory_listener_register(&kvm_io_listener,
1735 s->many_ioeventfds = kvm_check_many_ioeventfds();
1737 cpu_interrupt_handler = kvm_handle_interrupt;
1749 g_free(s->memory_listener.slots);
1754 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
1756 s->sigmask_len = sigmask_len;
1759 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
1760 int size, uint32_t count)
1763 uint8_t *ptr = data;
1765 for (i = 0; i < count; i++) {
1766 address_space_rw(&address_space_io, port, attrs,
1768 direction == KVM_EXIT_IO_OUT);
1773 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
1775 fprintf(stderr, "KVM internal error. Suberror: %d\n",
1776 run->internal.suberror);
1778 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1781 for (i = 0; i < run->internal.ndata; ++i) {
1782 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1783 i, (uint64_t)run->internal.data[i]);
1786 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1787 fprintf(stderr, "emulation failure\n");
1788 if (!kvm_arch_stop_on_emulation_error(cpu)) {
1789 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1790 return EXCP_INTERRUPT;
1793 /* FIXME: Should trigger a qmp message to let management know
1794 * something went wrong.
1799 void kvm_flush_coalesced_mmio_buffer(void)
1801 KVMState *s = kvm_state;
1803 if (s->coalesced_flush_in_progress) {
1807 s->coalesced_flush_in_progress = true;
1809 if (s->coalesced_mmio_ring) {
1810 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1811 while (ring->first != ring->last) {
1812 struct kvm_coalesced_mmio *ent;
1814 ent = &ring->coalesced_mmio[ring->first];
1816 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1818 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1822 s->coalesced_flush_in_progress = false;
1825 static void do_kvm_cpu_synchronize_state(void *arg)
1827 CPUState *cpu = arg;
1829 if (!cpu->kvm_vcpu_dirty) {
1830 kvm_arch_get_registers(cpu);
1831 cpu->kvm_vcpu_dirty = true;
1835 void kvm_cpu_synchronize_state(CPUState *cpu)
1837 if (!cpu->kvm_vcpu_dirty) {
1838 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, cpu);
1842 static void do_kvm_cpu_synchronize_post_reset(void *arg)
1844 CPUState *cpu = arg;
1846 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1847 cpu->kvm_vcpu_dirty = false;
1850 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
1852 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, cpu);
1855 static void do_kvm_cpu_synchronize_post_init(void *arg)
1857 CPUState *cpu = arg;
1859 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1860 cpu->kvm_vcpu_dirty = false;
1863 void kvm_cpu_synchronize_post_init(CPUState *cpu)
1865 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, cpu);
1868 int kvm_cpu_exec(CPUState *cpu)
1870 struct kvm_run *run = cpu->kvm_run;
1873 DPRINTF("kvm_cpu_exec()\n");
1875 if (kvm_arch_process_async_events(cpu)) {
1876 cpu->exit_request = 0;
1880 qemu_mutex_unlock_iothread();
1885 if (cpu->kvm_vcpu_dirty) {
1886 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1887 cpu->kvm_vcpu_dirty = false;
1890 kvm_arch_pre_run(cpu, run);
1891 if (cpu->exit_request) {
1892 DPRINTF("interrupt exit requested\n");
1894 * KVM requires us to reenter the kernel after IO exits to complete
1895 * instruction emulation. This self-signal will ensure that we
1898 qemu_cpu_kick_self();
1901 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
1903 attrs = kvm_arch_post_run(cpu, run);
1906 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1907 DPRINTF("io window exit\n");
1908 ret = EXCP_INTERRUPT;
1911 fprintf(stderr, "error: kvm run failed %s\n",
1912 strerror(-run_ret));
1914 if (run_ret == -EBUSY) {
1916 "This is probably because your SMT is enabled.\n"
1917 "VCPU can only run on primary threads with all "
1918 "secondary threads offline.\n");
1925 trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
1926 switch (run->exit_reason) {
1928 DPRINTF("handle_io\n");
1929 /* Called outside BQL */
1930 kvm_handle_io(run->io.port, attrs,
1931 (uint8_t *)run + run->io.data_offset,
1938 DPRINTF("handle_mmio\n");
1939 /* Called outside BQL */
1940 address_space_rw(&address_space_memory,
1941 run->mmio.phys_addr, attrs,
1944 run->mmio.is_write);
1947 case KVM_EXIT_IRQ_WINDOW_OPEN:
1948 DPRINTF("irq_window_open\n");
1949 ret = EXCP_INTERRUPT;
1951 case KVM_EXIT_SHUTDOWN:
1952 DPRINTF("shutdown\n");
1953 qemu_system_reset_request();
1954 ret = EXCP_INTERRUPT;
1956 case KVM_EXIT_UNKNOWN:
1957 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1958 (uint64_t)run->hw.hardware_exit_reason);
1961 case KVM_EXIT_INTERNAL_ERROR:
1962 ret = kvm_handle_internal_error(cpu, run);
1964 case KVM_EXIT_SYSTEM_EVENT:
1965 switch (run->system_event.type) {
1966 case KVM_SYSTEM_EVENT_SHUTDOWN:
1967 qemu_system_shutdown_request();
1968 ret = EXCP_INTERRUPT;
1970 case KVM_SYSTEM_EVENT_RESET:
1971 qemu_system_reset_request();
1972 ret = EXCP_INTERRUPT;
1974 case KVM_SYSTEM_EVENT_CRASH:
1975 qemu_mutex_lock_iothread();
1976 qemu_system_guest_panicked();
1977 qemu_mutex_unlock_iothread();
1981 DPRINTF("kvm_arch_handle_exit\n");
1982 ret = kvm_arch_handle_exit(cpu, run);
1987 DPRINTF("kvm_arch_handle_exit\n");
1988 ret = kvm_arch_handle_exit(cpu, run);
1993 qemu_mutex_lock_iothread();
1996 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1997 vm_stop(RUN_STATE_INTERNAL_ERROR);
2000 cpu->exit_request = 0;
2004 int kvm_ioctl(KVMState *s, int type, ...)
2011 arg = va_arg(ap, void *);
2014 trace_kvm_ioctl(type, arg);
2015 ret = ioctl(s->fd, type, arg);
2022 int kvm_vm_ioctl(KVMState *s, int type, ...)
2029 arg = va_arg(ap, void *);
2032 trace_kvm_vm_ioctl(type, arg);
2033 ret = ioctl(s->vmfd, type, arg);
2040 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
2047 arg = va_arg(ap, void *);
2050 trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
2051 ret = ioctl(cpu->kvm_fd, type, arg);
2058 int kvm_device_ioctl(int fd, int type, ...)
2065 arg = va_arg(ap, void *);
2068 trace_kvm_device_ioctl(fd, type, arg);
2069 ret = ioctl(fd, type, arg);
2076 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
2079 struct kvm_device_attr attribute = {
2084 if (!kvm_vm_attributes_allowed) {
2088 ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
2089 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2093 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
2095 struct kvm_device_attr attribute = {
2101 return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
2104 void kvm_device_access(int fd, int group, uint64_t attr,
2105 void *val, bool write)
2107 struct kvm_device_attr kvmattr;
2111 kvmattr.group = group;
2112 kvmattr.attr = attr;
2113 kvmattr.addr = (uintptr_t)val;
2115 err = kvm_device_ioctl(fd,
2116 write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
2119 error_report("KVM_%s_DEVICE_ATTR failed: %s",
2120 write ? "SET" : "GET", strerror(-err));
2121 error_printf("Group %d attr 0x%016" PRIx64, group, attr);
2126 int kvm_has_sync_mmu(void)
2128 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2131 int kvm_has_vcpu_events(void)
2133 return kvm_state->vcpu_events;
2136 int kvm_has_robust_singlestep(void)
2138 return kvm_state->robust_singlestep;
2141 int kvm_has_debugregs(void)
2143 return kvm_state->debugregs;
2146 int kvm_has_many_ioeventfds(void)
2148 if (!kvm_enabled()) {
2151 return kvm_state->many_ioeventfds;
2154 int kvm_has_gsi_routing(void)
2156 #ifdef KVM_CAP_IRQ_ROUTING
2157 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
2163 int kvm_has_intx_set_mask(void)
2165 return kvm_state->intx_set_mask;
2168 void kvm_setup_guest_memory(void *start, size_t size)
2170 if (!kvm_has_sync_mmu()) {
2171 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
2174 perror("qemu_madvise");
2176 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
2182 #ifdef KVM_CAP_SET_GUEST_DEBUG
2183 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
2186 struct kvm_sw_breakpoint *bp;
2188 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
2196 int kvm_sw_breakpoints_active(CPUState *cpu)
2198 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
2201 struct kvm_set_guest_debug_data {
2202 struct kvm_guest_debug dbg;
2207 static void kvm_invoke_set_guest_debug(void *data)
2209 struct kvm_set_guest_debug_data *dbg_data = data;
2211 dbg_data->err = kvm_vcpu_ioctl(dbg_data->cpu, KVM_SET_GUEST_DEBUG,
2215 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2217 struct kvm_set_guest_debug_data data;
2219 data.dbg.control = reinject_trap;
2221 if (cpu->singlestep_enabled) {
2222 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2224 kvm_arch_update_guest_debug(cpu, &data.dbg);
2227 run_on_cpu(cpu, kvm_invoke_set_guest_debug, &data);
2231 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2232 target_ulong len, int type)
2234 struct kvm_sw_breakpoint *bp;
2237 if (type == GDB_BREAKPOINT_SW) {
2238 bp = kvm_find_sw_breakpoint(cpu, addr);
2244 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2247 err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2253 QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2255 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2262 err = kvm_update_guest_debug(cpu, 0);
2270 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2271 target_ulong len, int type)
2273 struct kvm_sw_breakpoint *bp;
2276 if (type == GDB_BREAKPOINT_SW) {
2277 bp = kvm_find_sw_breakpoint(cpu, addr);
2282 if (bp->use_count > 1) {
2287 err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2292 QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2295 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2302 err = kvm_update_guest_debug(cpu, 0);
2310 void kvm_remove_all_breakpoints(CPUState *cpu)
2312 struct kvm_sw_breakpoint *bp, *next;
2313 KVMState *s = cpu->kvm_state;
2316 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2317 if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2318 /* Try harder to find a CPU that currently sees the breakpoint. */
2319 CPU_FOREACH(tmpcpu) {
2320 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2325 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2328 kvm_arch_remove_all_hw_breakpoints();
2331 kvm_update_guest_debug(cpu, 0);
2335 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2337 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2342 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2343 target_ulong len, int type)
2348 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2349 target_ulong len, int type)
2354 void kvm_remove_all_breakpoints(CPUState *cpu)
2357 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2359 int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2361 KVMState *s = kvm_state;
2362 struct kvm_signal_mask *sigmask;
2366 return kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, NULL);
2369 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2371 sigmask->len = s->sigmask_len;
2372 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2373 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2378 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2380 return kvm_arch_on_sigbus_vcpu(cpu, code, addr);
2383 int kvm_on_sigbus(int code, void *addr)
2385 return kvm_arch_on_sigbus(code, addr);
2388 int kvm_create_device(KVMState *s, uint64_t type, bool test)
2391 struct kvm_create_device create_dev;
2393 create_dev.type = type;
2395 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2397 if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2401 ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2406 return test ? 0 : create_dev.fd;
2409 bool kvm_device_supported(int vmfd, uint64_t type)
2411 struct kvm_create_device create_dev = {
2414 .flags = KVM_CREATE_DEVICE_TEST,
2417 if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
2421 return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
2424 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2426 struct kvm_one_reg reg;
2430 reg.addr = (uintptr_t) source;
2431 r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, ®);
2433 trace_kvm_failed_reg_set(id, strerror(-r));
2438 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2440 struct kvm_one_reg reg;
2444 reg.addr = (uintptr_t) target;
2445 r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, ®);
2447 trace_kvm_failed_reg_get(id, strerror(-r));
2452 static void kvm_accel_class_init(ObjectClass *oc, void *data)
2454 AccelClass *ac = ACCEL_CLASS(oc);
2456 ac->init_machine = kvm_init;
2457 ac->allowed = &kvm_allowed;
2460 static const TypeInfo kvm_accel_type = {
2461 .name = TYPE_KVM_ACCEL,
2462 .parent = TYPE_ACCEL,
2463 .class_init = kvm_accel_class_init,
2464 .instance_size = sizeof(KVMState),
2467 static void kvm_type_init(void)
2469 type_register_static(&kvm_accel_type);
2472 type_init(kvm_type_init);