4 * Copyright IBM, Corp. 2008
8 * Anthony Liguori <aliguori@us.ibm.com>
9 * Glauber Costa <gcosta@redhat.com>
11 * This work is licensed under the terms of the GNU GPL, version 2 or later.
12 * See the COPYING file in the top-level directory.
16 #include "qemu/osdep.h"
17 #include <sys/ioctl.h>
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"
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"
42 #include "hw/boards.h"
44 /* This check must be after config-host.h is included */
46 #include <sys/eventfd.h>
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()
57 #define DPRINTF(fmt, ...) \
58 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
60 #define DPRINTF(fmt, ...) \
64 #define KVM_MSI_HASHTAB_SIZE 256
66 struct KVMParkedVcpu
{
67 unsigned long vcpu_id
;
69 QLIST_ENTRY(KVMParkedVcpu
) node
;
74 AccelState parent_obj
;
80 struct kvm_coalesced_mmio_ring
*coalesced_mmio_ring
;
81 bool coalesced_flush_in_progress
;
83 int robust_singlestep
;
85 #ifdef KVM_CAP_SET_GUEST_DEBUG
86 struct kvm_sw_breakpoint_head kvm_sw_breakpoints
;
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
;
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
];
104 KVMMemoryListener memory_listener
;
105 QLIST_HEAD(, KVMParkedVcpu
) kvm_parked_vcpus
;
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
;
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
),
134 int kvm_get_max_memslots(void)
136 KVMState
*s
= KVM_STATE(current_machine
->accelerator
);
141 static KVMSlot
*kvm_get_free_slot(KVMMemoryListener
*kml
)
143 KVMState
*s
= kvm_state
;
146 for (i
= 0; i
< s
->nr_slots
; i
++) {
147 if (kml
->slots
[i
].memory_size
== 0) {
148 return &kml
->slots
[i
];
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
);
170 fprintf(stderr
, "%s: no free slot available\n", __func__
);
174 static KVMSlot
*kvm_lookup_matching_slot(KVMMemoryListener
*kml
,
178 KVMState
*s
= kvm_state
;
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
) {
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
,
199 hwaddr size
= int128_get64(section
->size
);
200 hwaddr delta
, aligned
;
202 /* kvm works in page size chunks, but the function may be called
203 with sub-page size and unaligned start address. Pad the start
204 address to next and truncate size to previous page boundary. */
205 aligned
= ROUND_UP(section
->offset_within_address_space
,
206 qemu_real_host_page_size
);
207 delta
= aligned
- section
->offset_within_address_space
;
213 return (size
- delta
) & qemu_real_host_page_mask
;
216 int kvm_physical_memory_addr_from_host(KVMState
*s
, void *ram
,
219 KVMMemoryListener
*kml
= &s
->memory_listener
;
222 for (i
= 0; i
< s
->nr_slots
; i
++) {
223 KVMSlot
*mem
= &kml
->slots
[i
];
225 if (ram
>= mem
->ram
&& ram
< mem
->ram
+ mem
->memory_size
) {
226 *phys_addr
= mem
->start_addr
+ (ram
- mem
->ram
);
234 static int kvm_set_user_memory_region(KVMMemoryListener
*kml
, KVMSlot
*slot
)
236 KVMState
*s
= kvm_state
;
237 struct kvm_userspace_memory_region mem
;
240 mem
.slot
= slot
->slot
| (kml
->as_id
<< 16);
241 mem
.guest_phys_addr
= slot
->start_addr
;
242 mem
.userspace_addr
= (unsigned long)slot
->ram
;
243 mem
.flags
= slot
->flags
;
245 if (slot
->memory_size
&& mem
.flags
& KVM_MEM_READONLY
) {
246 /* Set the slot size to 0 before setting the slot to the desired
247 * value. This is needed based on KVM commit 75d61fbc. */
249 kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
251 mem
.memory_size
= slot
->memory_size
;
252 ret
= kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
253 trace_kvm_set_user_memory(mem
.slot
, mem
.flags
, mem
.guest_phys_addr
,
254 mem
.memory_size
, mem
.userspace_addr
, ret
);
258 int kvm_destroy_vcpu(CPUState
*cpu
)
260 KVMState
*s
= kvm_state
;
262 struct KVMParkedVcpu
*vcpu
= NULL
;
265 DPRINTF("kvm_destroy_vcpu\n");
267 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
270 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
274 ret
= munmap(cpu
->kvm_run
, mmap_size
);
279 vcpu
= g_malloc0(sizeof(*vcpu
));
280 vcpu
->vcpu_id
= kvm_arch_vcpu_id(cpu
);
281 vcpu
->kvm_fd
= cpu
->kvm_fd
;
282 QLIST_INSERT_HEAD(&kvm_state
->kvm_parked_vcpus
, vcpu
, node
);
287 static int kvm_get_vcpu(KVMState
*s
, unsigned long vcpu_id
)
289 struct KVMParkedVcpu
*cpu
;
291 QLIST_FOREACH(cpu
, &s
->kvm_parked_vcpus
, node
) {
292 if (cpu
->vcpu_id
== vcpu_id
) {
295 QLIST_REMOVE(cpu
, node
);
296 kvm_fd
= cpu
->kvm_fd
;
302 return kvm_vm_ioctl(s
, KVM_CREATE_VCPU
, (void *)vcpu_id
);
305 int kvm_init_vcpu(CPUState
*cpu
)
307 KVMState
*s
= kvm_state
;
311 DPRINTF("kvm_init_vcpu\n");
313 ret
= kvm_get_vcpu(s
, kvm_arch_vcpu_id(cpu
));
315 DPRINTF("kvm_create_vcpu failed\n");
321 cpu
->vcpu_dirty
= true;
323 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
326 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
330 cpu
->kvm_run
= mmap(NULL
, mmap_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
332 if (cpu
->kvm_run
== MAP_FAILED
) {
334 DPRINTF("mmap'ing vcpu state failed\n");
338 if (s
->coalesced_mmio
&& !s
->coalesced_mmio_ring
) {
339 s
->coalesced_mmio_ring
=
340 (void *)cpu
->kvm_run
+ s
->coalesced_mmio
* PAGE_SIZE
;
343 ret
= kvm_arch_init_vcpu(cpu
);
349 * dirty pages logging control
352 static int kvm_mem_flags(MemoryRegion
*mr
)
354 bool readonly
= mr
->readonly
|| memory_region_is_romd(mr
);
357 if (memory_region_get_dirty_log_mask(mr
) != 0) {
358 flags
|= KVM_MEM_LOG_DIRTY_PAGES
;
360 if (readonly
&& kvm_readonly_mem_allowed
) {
361 flags
|= KVM_MEM_READONLY
;
366 static int kvm_slot_update_flags(KVMMemoryListener
*kml
, KVMSlot
*mem
,
371 old_flags
= mem
->flags
;
372 mem
->flags
= kvm_mem_flags(mr
);
374 /* If nothing changed effectively, no need to issue ioctl */
375 if (mem
->flags
== old_flags
) {
379 return kvm_set_user_memory_region(kml
, mem
);
382 static int kvm_section_update_flags(KVMMemoryListener
*kml
,
383 MemoryRegionSection
*section
)
385 hwaddr start_addr
, size
;
388 size
= kvm_align_section(section
, &start_addr
);
393 mem
= kvm_lookup_matching_slot(kml
, start_addr
, size
);
395 /* We don't have a slot if we want to trap every access. */
399 return kvm_slot_update_flags(kml
, mem
, section
->mr
);
402 static void kvm_log_start(MemoryListener
*listener
,
403 MemoryRegionSection
*section
,
406 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
413 r
= kvm_section_update_flags(kml
, section
);
419 static void kvm_log_stop(MemoryListener
*listener
,
420 MemoryRegionSection
*section
,
423 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
430 r
= kvm_section_update_flags(kml
, section
);
436 /* get kvm's dirty pages bitmap and update qemu's */
437 static int kvm_get_dirty_pages_log_range(MemoryRegionSection
*section
,
438 unsigned long *bitmap
)
440 ram_addr_t start
= section
->offset_within_region
+
441 memory_region_get_ram_addr(section
->mr
);
442 ram_addr_t pages
= int128_get64(section
->size
) / getpagesize();
444 cpu_physical_memory_set_dirty_lebitmap(bitmap
, start
, pages
);
448 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
451 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
452 * This function updates qemu's dirty bitmap using
453 * memory_region_set_dirty(). This means all bits are set
456 * @start_add: start of logged region.
457 * @end_addr: end of logged region.
459 static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener
*kml
,
460 MemoryRegionSection
*section
)
462 KVMState
*s
= kvm_state
;
463 struct kvm_dirty_log d
= {};
465 hwaddr start_addr
, size
;
467 size
= kvm_align_section(section
, &start_addr
);
469 mem
= kvm_lookup_matching_slot(kml
, start_addr
, size
);
471 /* We don't have a slot if we want to trap every access. */
475 /* XXX bad kernel interface alert
476 * For dirty bitmap, kernel allocates array of size aligned to
477 * bits-per-long. But for case when the kernel is 64bits and
478 * the userspace is 32bits, userspace can't align to the same
479 * bits-per-long, since sizeof(long) is different between kernel
480 * and user space. This way, userspace will provide buffer which
481 * may be 4 bytes less than the kernel will use, resulting in
482 * userspace memory corruption (which is not detectable by valgrind
483 * too, in most cases).
484 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
485 * a hope that sizeof(long) won't become >8 any time soon.
487 size
= ALIGN(((mem
->memory_size
) >> TARGET_PAGE_BITS
),
488 /*HOST_LONG_BITS*/ 64) / 8;
489 d
.dirty_bitmap
= g_malloc0(size
);
491 d
.slot
= mem
->slot
| (kml
->as_id
<< 16);
492 if (kvm_vm_ioctl(s
, KVM_GET_DIRTY_LOG
, &d
) == -1) {
493 DPRINTF("ioctl failed %d\n", errno
);
494 g_free(d
.dirty_bitmap
);
498 kvm_get_dirty_pages_log_range(section
, d
.dirty_bitmap
);
499 g_free(d
.dirty_bitmap
);
505 static void kvm_coalesce_mmio_region(MemoryListener
*listener
,
506 MemoryRegionSection
*secion
,
507 hwaddr start
, hwaddr size
)
509 KVMState
*s
= kvm_state
;
511 if (s
->coalesced_mmio
) {
512 struct kvm_coalesced_mmio_zone zone
;
518 (void)kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
522 static void kvm_uncoalesce_mmio_region(MemoryListener
*listener
,
523 MemoryRegionSection
*secion
,
524 hwaddr start
, hwaddr size
)
526 KVMState
*s
= kvm_state
;
528 if (s
->coalesced_mmio
) {
529 struct kvm_coalesced_mmio_zone zone
;
535 (void)kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
539 int kvm_check_extension(KVMState
*s
, unsigned int extension
)
543 ret
= kvm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
551 int kvm_vm_check_extension(KVMState
*s
, unsigned int extension
)
555 ret
= kvm_vm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
557 /* VM wide version not implemented, use global one instead */
558 ret
= kvm_check_extension(s
, extension
);
564 static uint32_t adjust_ioeventfd_endianness(uint32_t val
, uint32_t size
)
566 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
567 /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
568 * endianness, but the memory core hands them in target endianness.
569 * For example, PPC is always treated as big-endian even if running
570 * on KVM and on PPC64LE. Correct here.
584 static int kvm_set_ioeventfd_mmio(int fd
, hwaddr addr
, uint32_t val
,
585 bool assign
, uint32_t size
, bool datamatch
)
588 struct kvm_ioeventfd iofd
= {
589 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
596 if (!kvm_enabled()) {
601 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
604 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
607 ret
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &iofd
);
616 static int kvm_set_ioeventfd_pio(int fd
, uint16_t addr
, uint16_t val
,
617 bool assign
, uint32_t size
, bool datamatch
)
619 struct kvm_ioeventfd kick
= {
620 .datamatch
= datamatch
? adjust_ioeventfd_endianness(val
, size
) : 0,
622 .flags
= KVM_IOEVENTFD_FLAG_PIO
,
627 if (!kvm_enabled()) {
631 kick
.flags
|= KVM_IOEVENTFD_FLAG_DATAMATCH
;
634 kick
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
636 r
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &kick
);
644 static int kvm_check_many_ioeventfds(void)
646 /* Userspace can use ioeventfd for io notification. This requires a host
647 * that supports eventfd(2) and an I/O thread; since eventfd does not
648 * support SIGIO it cannot interrupt the vcpu.
650 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
651 * can avoid creating too many ioeventfds.
653 #if defined(CONFIG_EVENTFD)
656 for (i
= 0; i
< ARRAY_SIZE(ioeventfds
); i
++) {
657 ioeventfds
[i
] = eventfd(0, EFD_CLOEXEC
);
658 if (ioeventfds
[i
] < 0) {
661 ret
= kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, true, 2, true);
663 close(ioeventfds
[i
]);
668 /* Decide whether many devices are supported or not */
669 ret
= i
== ARRAY_SIZE(ioeventfds
);
672 kvm_set_ioeventfd_pio(ioeventfds
[i
], 0, i
, false, 2, true);
673 close(ioeventfds
[i
]);
681 static const KVMCapabilityInfo
*
682 kvm_check_extension_list(KVMState
*s
, const KVMCapabilityInfo
*list
)
685 if (!kvm_check_extension(s
, list
->value
)) {
693 static void kvm_set_phys_mem(KVMMemoryListener
*kml
,
694 MemoryRegionSection
*section
, bool add
)
698 MemoryRegion
*mr
= section
->mr
;
699 bool writeable
= !mr
->readonly
&& !mr
->rom_device
;
700 hwaddr start_addr
, size
;
703 if (!memory_region_is_ram(mr
)) {
704 if (writeable
|| !kvm_readonly_mem_allowed
) {
706 } else if (!mr
->romd_mode
) {
707 /* If the memory device is not in romd_mode, then we actually want
708 * to remove the kvm memory slot so all accesses will trap. */
713 size
= kvm_align_section(section
, &start_addr
);
718 /* use aligned delta to align the ram address */
719 ram
= memory_region_get_ram_ptr(mr
) + section
->offset_within_region
+
720 (start_addr
- section
->offset_within_address_space
);
723 mem
= kvm_lookup_matching_slot(kml
, start_addr
, size
);
727 if (mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
728 kvm_physical_sync_dirty_bitmap(kml
, section
);
731 /* unregister the slot */
732 mem
->memory_size
= 0;
733 err
= kvm_set_user_memory_region(kml
, mem
);
735 fprintf(stderr
, "%s: error unregistering slot: %s\n",
736 __func__
, strerror(-err
));
742 /* register the new slot */
743 mem
= kvm_alloc_slot(kml
);
744 mem
->memory_size
= size
;
745 mem
->start_addr
= start_addr
;
747 mem
->flags
= kvm_mem_flags(mr
);
749 err
= kvm_set_user_memory_region(kml
, mem
);
751 fprintf(stderr
, "%s: error registering slot: %s\n", __func__
,
757 static void kvm_region_add(MemoryListener
*listener
,
758 MemoryRegionSection
*section
)
760 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
762 memory_region_ref(section
->mr
);
763 kvm_set_phys_mem(kml
, section
, true);
766 static void kvm_region_del(MemoryListener
*listener
,
767 MemoryRegionSection
*section
)
769 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
771 kvm_set_phys_mem(kml
, section
, false);
772 memory_region_unref(section
->mr
);
775 static void kvm_log_sync(MemoryListener
*listener
,
776 MemoryRegionSection
*section
)
778 KVMMemoryListener
*kml
= container_of(listener
, KVMMemoryListener
, listener
);
781 r
= kvm_physical_sync_dirty_bitmap(kml
, section
);
787 static void kvm_mem_ioeventfd_add(MemoryListener
*listener
,
788 MemoryRegionSection
*section
,
789 bool match_data
, uint64_t data
,
792 int fd
= event_notifier_get_fd(e
);
795 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
796 data
, true, int128_get64(section
->size
),
799 fprintf(stderr
, "%s: error adding ioeventfd: %s\n",
800 __func__
, strerror(-r
));
805 static void kvm_mem_ioeventfd_del(MemoryListener
*listener
,
806 MemoryRegionSection
*section
,
807 bool match_data
, uint64_t data
,
810 int fd
= event_notifier_get_fd(e
);
813 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
814 data
, false, int128_get64(section
->size
),
821 static void kvm_io_ioeventfd_add(MemoryListener
*listener
,
822 MemoryRegionSection
*section
,
823 bool match_data
, uint64_t data
,
826 int fd
= event_notifier_get_fd(e
);
829 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
830 data
, true, int128_get64(section
->size
),
833 fprintf(stderr
, "%s: error adding ioeventfd: %s\n",
834 __func__
, strerror(-r
));
839 static void kvm_io_ioeventfd_del(MemoryListener
*listener
,
840 MemoryRegionSection
*section
,
841 bool match_data
, uint64_t data
,
845 int fd
= event_notifier_get_fd(e
);
848 r
= kvm_set_ioeventfd_pio(fd
, section
->offset_within_address_space
,
849 data
, false, int128_get64(section
->size
),
856 void kvm_memory_listener_register(KVMState
*s
, KVMMemoryListener
*kml
,
857 AddressSpace
*as
, int as_id
)
861 kml
->slots
= g_malloc0(s
->nr_slots
* sizeof(KVMSlot
));
864 for (i
= 0; i
< s
->nr_slots
; i
++) {
865 kml
->slots
[i
].slot
= i
;
868 kml
->listener
.region_add
= kvm_region_add
;
869 kml
->listener
.region_del
= kvm_region_del
;
870 kml
->listener
.log_start
= kvm_log_start
;
871 kml
->listener
.log_stop
= kvm_log_stop
;
872 kml
->listener
.log_sync
= kvm_log_sync
;
873 kml
->listener
.priority
= 10;
875 memory_listener_register(&kml
->listener
, as
);
878 static MemoryListener kvm_io_listener
= {
879 .eventfd_add
= kvm_io_ioeventfd_add
,
880 .eventfd_del
= kvm_io_ioeventfd_del
,
884 int kvm_set_irq(KVMState
*s
, int irq
, int level
)
886 struct kvm_irq_level event
;
889 assert(kvm_async_interrupts_enabled());
893 ret
= kvm_vm_ioctl(s
, s
->irq_set_ioctl
, &event
);
895 perror("kvm_set_irq");
899 return (s
->irq_set_ioctl
== KVM_IRQ_LINE
) ? 1 : event
.status
;
902 #ifdef KVM_CAP_IRQ_ROUTING
903 typedef struct KVMMSIRoute
{
904 struct kvm_irq_routing_entry kroute
;
905 QTAILQ_ENTRY(KVMMSIRoute
) entry
;
908 static void set_gsi(KVMState
*s
, unsigned int gsi
)
910 set_bit(gsi
, s
->used_gsi_bitmap
);
913 static void clear_gsi(KVMState
*s
, unsigned int gsi
)
915 clear_bit(gsi
, s
->used_gsi_bitmap
);
918 void kvm_init_irq_routing(KVMState
*s
)
922 gsi_count
= kvm_check_extension(s
, KVM_CAP_IRQ_ROUTING
) - 1;
924 /* Round up so we can search ints using ffs */
925 s
->used_gsi_bitmap
= bitmap_new(gsi_count
);
926 s
->gsi_count
= gsi_count
;
929 s
->irq_routes
= g_malloc0(sizeof(*s
->irq_routes
));
930 s
->nr_allocated_irq_routes
= 0;
932 if (!kvm_direct_msi_allowed
) {
933 for (i
= 0; i
< KVM_MSI_HASHTAB_SIZE
; i
++) {
934 QTAILQ_INIT(&s
->msi_hashtab
[i
]);
938 kvm_arch_init_irq_routing(s
);
941 void kvm_irqchip_commit_routes(KVMState
*s
)
945 if (kvm_gsi_direct_mapping()) {
949 if (!kvm_gsi_routing_enabled()) {
953 s
->irq_routes
->flags
= 0;
954 trace_kvm_irqchip_commit_routes();
955 ret
= kvm_vm_ioctl(s
, KVM_SET_GSI_ROUTING
, s
->irq_routes
);
959 static void kvm_add_routing_entry(KVMState
*s
,
960 struct kvm_irq_routing_entry
*entry
)
962 struct kvm_irq_routing_entry
*new;
965 if (s
->irq_routes
->nr
== s
->nr_allocated_irq_routes
) {
966 n
= s
->nr_allocated_irq_routes
* 2;
970 size
= sizeof(struct kvm_irq_routing
);
971 size
+= n
* sizeof(*new);
972 s
->irq_routes
= g_realloc(s
->irq_routes
, size
);
973 s
->nr_allocated_irq_routes
= n
;
975 n
= s
->irq_routes
->nr
++;
976 new = &s
->irq_routes
->entries
[n
];
980 set_gsi(s
, entry
->gsi
);
983 static int kvm_update_routing_entry(KVMState
*s
,
984 struct kvm_irq_routing_entry
*new_entry
)
986 struct kvm_irq_routing_entry
*entry
;
989 for (n
= 0; n
< s
->irq_routes
->nr
; n
++) {
990 entry
= &s
->irq_routes
->entries
[n
];
991 if (entry
->gsi
!= new_entry
->gsi
) {
995 if(!memcmp(entry
, new_entry
, sizeof *entry
)) {
1007 void kvm_irqchip_add_irq_route(KVMState
*s
, int irq
, int irqchip
, int pin
)
1009 struct kvm_irq_routing_entry e
= {};
1011 assert(pin
< s
->gsi_count
);
1014 e
.type
= KVM_IRQ_ROUTING_IRQCHIP
;
1016 e
.u
.irqchip
.irqchip
= irqchip
;
1017 e
.u
.irqchip
.pin
= pin
;
1018 kvm_add_routing_entry(s
, &e
);
1021 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
1023 struct kvm_irq_routing_entry
*e
;
1026 if (kvm_gsi_direct_mapping()) {
1030 for (i
= 0; i
< s
->irq_routes
->nr
; i
++) {
1031 e
= &s
->irq_routes
->entries
[i
];
1032 if (e
->gsi
== virq
) {
1033 s
->irq_routes
->nr
--;
1034 *e
= s
->irq_routes
->entries
[s
->irq_routes
->nr
];
1038 kvm_arch_release_virq_post(virq
);
1039 trace_kvm_irqchip_release_virq(virq
);
1042 static unsigned int kvm_hash_msi(uint32_t data
)
1044 /* This is optimized for IA32 MSI layout. However, no other arch shall
1045 * repeat the mistake of not providing a direct MSI injection API. */
1049 static void kvm_flush_dynamic_msi_routes(KVMState
*s
)
1051 KVMMSIRoute
*route
, *next
;
1054 for (hash
= 0; hash
< KVM_MSI_HASHTAB_SIZE
; hash
++) {
1055 QTAILQ_FOREACH_SAFE(route
, &s
->msi_hashtab
[hash
], entry
, next
) {
1056 kvm_irqchip_release_virq(s
, route
->kroute
.gsi
);
1057 QTAILQ_REMOVE(&s
->msi_hashtab
[hash
], route
, entry
);
1063 static int kvm_irqchip_get_virq(KVMState
*s
)
1068 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1069 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1070 * number can succeed even though a new route entry cannot be added.
1071 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1073 if (!kvm_direct_msi_allowed
&& s
->irq_routes
->nr
== s
->gsi_count
) {
1074 kvm_flush_dynamic_msi_routes(s
);
1077 /* Return the lowest unused GSI in the bitmap */
1078 next_virq
= find_first_zero_bit(s
->used_gsi_bitmap
, s
->gsi_count
);
1079 if (next_virq
>= s
->gsi_count
) {
1086 static KVMMSIRoute
*kvm_lookup_msi_route(KVMState
*s
, MSIMessage msg
)
1088 unsigned int hash
= kvm_hash_msi(msg
.data
);
1091 QTAILQ_FOREACH(route
, &s
->msi_hashtab
[hash
], entry
) {
1092 if (route
->kroute
.u
.msi
.address_lo
== (uint32_t)msg
.address
&&
1093 route
->kroute
.u
.msi
.address_hi
== (msg
.address
>> 32) &&
1094 route
->kroute
.u
.msi
.data
== le32_to_cpu(msg
.data
)) {
1101 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1106 if (kvm_direct_msi_allowed
) {
1107 msi
.address_lo
= (uint32_t)msg
.address
;
1108 msi
.address_hi
= msg
.address
>> 32;
1109 msi
.data
= le32_to_cpu(msg
.data
);
1111 memset(msi
.pad
, 0, sizeof(msi
.pad
));
1113 return kvm_vm_ioctl(s
, KVM_SIGNAL_MSI
, &msi
);
1116 route
= kvm_lookup_msi_route(s
, msg
);
1120 virq
= kvm_irqchip_get_virq(s
);
1125 route
= g_malloc0(sizeof(KVMMSIRoute
));
1126 route
->kroute
.gsi
= virq
;
1127 route
->kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1128 route
->kroute
.flags
= 0;
1129 route
->kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1130 route
->kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1131 route
->kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1133 kvm_add_routing_entry(s
, &route
->kroute
);
1134 kvm_irqchip_commit_routes(s
);
1136 QTAILQ_INSERT_TAIL(&s
->msi_hashtab
[kvm_hash_msi(msg
.data
)], route
,
1140 assert(route
->kroute
.type
== KVM_IRQ_ROUTING_MSI
);
1142 return kvm_set_irq(s
, route
->kroute
.gsi
, 1);
1145 int kvm_irqchip_add_msi_route(KVMState
*s
, int vector
, PCIDevice
*dev
)
1147 struct kvm_irq_routing_entry kroute
= {};
1149 MSIMessage msg
= {0, 0};
1151 if (pci_available
&& dev
) {
1152 msg
= pci_get_msi_message(dev
, vector
);
1155 if (kvm_gsi_direct_mapping()) {
1156 return kvm_arch_msi_data_to_gsi(msg
.data
);
1159 if (!kvm_gsi_routing_enabled()) {
1163 virq
= kvm_irqchip_get_virq(s
);
1169 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1171 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1172 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1173 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1174 if (pci_available
&& kvm_msi_devid_required()) {
1175 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1176 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1178 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1179 kvm_irqchip_release_virq(s
, virq
);
1183 trace_kvm_irqchip_add_msi_route(dev
? dev
->name
: (char *)"N/A",
1186 kvm_add_routing_entry(s
, &kroute
);
1187 kvm_arch_add_msi_route_post(&kroute
, vector
, dev
);
1188 kvm_irqchip_commit_routes(s
);
1193 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
,
1196 struct kvm_irq_routing_entry kroute
= {};
1198 if (kvm_gsi_direct_mapping()) {
1202 if (!kvm_irqchip_in_kernel()) {
1207 kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1209 kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1210 kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1211 kroute
.u
.msi
.data
= le32_to_cpu(msg
.data
);
1212 if (pci_available
&& kvm_msi_devid_required()) {
1213 kroute
.flags
= KVM_MSI_VALID_DEVID
;
1214 kroute
.u
.msi
.devid
= pci_requester_id(dev
);
1216 if (kvm_arch_fixup_msi_route(&kroute
, msg
.address
, msg
.data
, dev
)) {
1220 trace_kvm_irqchip_update_msi_route(virq
);
1222 return kvm_update_routing_entry(s
, &kroute
);
1225 static int kvm_irqchip_assign_irqfd(KVMState
*s
, int fd
, int rfd
, int virq
,
1228 struct kvm_irqfd irqfd
= {
1231 .flags
= assign
? 0 : KVM_IRQFD_FLAG_DEASSIGN
,
1235 irqfd
.flags
|= KVM_IRQFD_FLAG_RESAMPLE
;
1236 irqfd
.resamplefd
= rfd
;
1239 if (!kvm_irqfds_enabled()) {
1243 return kvm_vm_ioctl(s
, KVM_IRQFD
, &irqfd
);
1246 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
1248 struct kvm_irq_routing_entry kroute
= {};
1251 if (!kvm_gsi_routing_enabled()) {
1255 virq
= kvm_irqchip_get_virq(s
);
1261 kroute
.type
= KVM_IRQ_ROUTING_S390_ADAPTER
;
1263 kroute
.u
.adapter
.summary_addr
= adapter
->summary_addr
;
1264 kroute
.u
.adapter
.ind_addr
= adapter
->ind_addr
;
1265 kroute
.u
.adapter
.summary_offset
= adapter
->summary_offset
;
1266 kroute
.u
.adapter
.ind_offset
= adapter
->ind_offset
;
1267 kroute
.u
.adapter
.adapter_id
= adapter
->adapter_id
;
1269 kvm_add_routing_entry(s
, &kroute
);
1274 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
1276 struct kvm_irq_routing_entry kroute
= {};
1279 if (!kvm_gsi_routing_enabled()) {
1282 if (!kvm_check_extension(s
, KVM_CAP_HYPERV_SYNIC
)) {
1285 virq
= kvm_irqchip_get_virq(s
);
1291 kroute
.type
= KVM_IRQ_ROUTING_HV_SINT
;
1293 kroute
.u
.hv_sint
.vcpu
= vcpu
;
1294 kroute
.u
.hv_sint
.sint
= sint
;
1296 kvm_add_routing_entry(s
, &kroute
);
1297 kvm_irqchip_commit_routes(s
);
1302 #else /* !KVM_CAP_IRQ_ROUTING */
1304 void kvm_init_irq_routing(KVMState
*s
)
1308 void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
1312 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1317 int kvm_irqchip_add_msi_route(KVMState
*s
, int vector
, PCIDevice
*dev
)
1322 int kvm_irqchip_add_adapter_route(KVMState
*s
, AdapterInfo
*adapter
)
1327 int kvm_irqchip_add_hv_sint_route(KVMState
*s
, uint32_t vcpu
, uint32_t sint
)
1332 static int kvm_irqchip_assign_irqfd(KVMState
*s
, int fd
, int virq
, bool assign
)
1337 int kvm_irqchip_update_msi_route(KVMState
*s
, int virq
, MSIMessage msg
)
1341 #endif /* !KVM_CAP_IRQ_ROUTING */
1343 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
1344 EventNotifier
*rn
, int virq
)
1346 return kvm_irqchip_assign_irqfd(s
, event_notifier_get_fd(n
),
1347 rn
? event_notifier_get_fd(rn
) : -1, virq
, true);
1350 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState
*s
, EventNotifier
*n
,
1353 return kvm_irqchip_assign_irqfd(s
, event_notifier_get_fd(n
), -1, virq
,
1357 int kvm_irqchip_add_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
1358 EventNotifier
*rn
, qemu_irq irq
)
1361 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
1366 return kvm_irqchip_add_irqfd_notifier_gsi(s
, n
, rn
, GPOINTER_TO_INT(gsi
));
1369 int kvm_irqchip_remove_irqfd_notifier(KVMState
*s
, EventNotifier
*n
,
1373 gboolean found
= g_hash_table_lookup_extended(s
->gsimap
, irq
, &key
, &gsi
);
1378 return kvm_irqchip_remove_irqfd_notifier_gsi(s
, n
, GPOINTER_TO_INT(gsi
));
1381 void kvm_irqchip_set_qemuirq_gsi(KVMState
*s
, qemu_irq irq
, int gsi
)
1383 g_hash_table_insert(s
->gsimap
, irq
, GINT_TO_POINTER(gsi
));
1386 static void kvm_irqchip_create(MachineState
*machine
, KVMState
*s
)
1390 if (kvm_check_extension(s
, KVM_CAP_IRQCHIP
)) {
1392 } else if (kvm_check_extension(s
, KVM_CAP_S390_IRQCHIP
)) {
1393 ret
= kvm_vm_enable_cap(s
, KVM_CAP_S390_IRQCHIP
, 0);
1395 fprintf(stderr
, "Enable kernel irqchip failed: %s\n", strerror(-ret
));
1402 /* First probe and see if there's a arch-specific hook to create the
1403 * in-kernel irqchip for us */
1404 ret
= kvm_arch_irqchip_create(machine
, s
);
1406 if (machine_kernel_irqchip_split(machine
)) {
1407 perror("Split IRQ chip mode not supported.");
1410 ret
= kvm_vm_ioctl(s
, KVM_CREATE_IRQCHIP
);
1414 fprintf(stderr
, "Create kernel irqchip failed: %s\n", strerror(-ret
));
1418 kvm_kernel_irqchip
= true;
1419 /* If we have an in-kernel IRQ chip then we must have asynchronous
1420 * interrupt delivery (though the reverse is not necessarily true)
1422 kvm_async_interrupts_allowed
= true;
1423 kvm_halt_in_kernel_allowed
= true;
1425 kvm_init_irq_routing(s
);
1427 s
->gsimap
= g_hash_table_new(g_direct_hash
, g_direct_equal
);
1430 /* Find number of supported CPUs using the recommended
1431 * procedure from the kernel API documentation to cope with
1432 * older kernels that may be missing capabilities.
1434 static int kvm_recommended_vcpus(KVMState
*s
)
1436 int ret
= kvm_vm_check_extension(s
, KVM_CAP_NR_VCPUS
);
1437 return (ret
) ? ret
: 4;
1440 static int kvm_max_vcpus(KVMState
*s
)
1442 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPUS
);
1443 return (ret
) ? ret
: kvm_recommended_vcpus(s
);
1446 static int kvm_max_vcpu_id(KVMState
*s
)
1448 int ret
= kvm_check_extension(s
, KVM_CAP_MAX_VCPU_ID
);
1449 return (ret
) ? ret
: kvm_max_vcpus(s
);
1452 bool kvm_vcpu_id_is_valid(int vcpu_id
)
1454 KVMState
*s
= KVM_STATE(current_machine
->accelerator
);
1455 return vcpu_id
>= 0 && vcpu_id
< kvm_max_vcpu_id(s
);
1458 static int kvm_init(MachineState
*ms
)
1460 MachineClass
*mc
= MACHINE_GET_CLASS(ms
);
1461 static const char upgrade_note
[] =
1462 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1463 "(see http://sourceforge.net/projects/kvm).\n";
1468 { "SMP", smp_cpus
},
1469 { "hotpluggable", max_cpus
},
1472 int soft_vcpus_limit
, hard_vcpus_limit
;
1474 const KVMCapabilityInfo
*missing_cap
;
1477 const char *kvm_type
;
1479 s
= KVM_STATE(ms
->accelerator
);
1482 * On systems where the kernel can support different base page
1483 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1484 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1485 * page size for the system though.
1487 assert(TARGET_PAGE_SIZE
<= getpagesize());
1491 #ifdef KVM_CAP_SET_GUEST_DEBUG
1492 QTAILQ_INIT(&s
->kvm_sw_breakpoints
);
1494 QLIST_INIT(&s
->kvm_parked_vcpus
);
1496 s
->fd
= qemu_open("/dev/kvm", O_RDWR
);
1498 fprintf(stderr
, "Could not access KVM kernel module: %m\n");
1503 ret
= kvm_ioctl(s
, KVM_GET_API_VERSION
, 0);
1504 if (ret
< KVM_API_VERSION
) {
1508 fprintf(stderr
, "kvm version too old\n");
1512 if (ret
> KVM_API_VERSION
) {
1514 fprintf(stderr
, "kvm version not supported\n");
1518 kvm_immediate_exit
= kvm_check_extension(s
, KVM_CAP_IMMEDIATE_EXIT
);
1519 s
->nr_slots
= kvm_check_extension(s
, KVM_CAP_NR_MEMSLOTS
);
1521 /* If unspecified, use the default value */
1526 kvm_type
= qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1528 type
= mc
->kvm_type(kvm_type
);
1529 } else if (kvm_type
) {
1531 fprintf(stderr
, "Invalid argument kvm-type=%s\n", kvm_type
);
1536 ret
= kvm_ioctl(s
, KVM_CREATE_VM
, type
);
1537 } while (ret
== -EINTR
);
1540 fprintf(stderr
, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret
,
1544 if (ret
== -EINVAL
) {
1546 "Host kernel setup problem detected. Please verify:\n");
1547 fprintf(stderr
, "- for kernels supporting the switch_amode or"
1548 " user_mode parameters, whether\n");
1550 " user space is running in primary address space\n");
1552 "- for kernels supporting the vm.allocate_pgste sysctl, "
1553 "whether it is enabled\n");
1561 /* check the vcpu limits */
1562 soft_vcpus_limit
= kvm_recommended_vcpus(s
);
1563 hard_vcpus_limit
= kvm_max_vcpus(s
);
1566 if (nc
->num
> soft_vcpus_limit
) {
1567 warn_report("Number of %s cpus requested (%d) exceeds "
1568 "the recommended cpus supported by KVM (%d)",
1569 nc
->name
, nc
->num
, soft_vcpus_limit
);
1571 if (nc
->num
> hard_vcpus_limit
) {
1572 fprintf(stderr
, "Number of %s cpus requested (%d) exceeds "
1573 "the maximum cpus supported by KVM (%d)\n",
1574 nc
->name
, nc
->num
, hard_vcpus_limit
);
1581 missing_cap
= kvm_check_extension_list(s
, kvm_required_capabilites
);
1584 kvm_check_extension_list(s
, kvm_arch_required_capabilities
);
1588 fprintf(stderr
, "kvm does not support %s\n%s",
1589 missing_cap
->name
, upgrade_note
);
1593 s
->coalesced_mmio
= kvm_check_extension(s
, KVM_CAP_COALESCED_MMIO
);
1595 #ifdef KVM_CAP_VCPU_EVENTS
1596 s
->vcpu_events
= kvm_check_extension(s
, KVM_CAP_VCPU_EVENTS
);
1599 s
->robust_singlestep
=
1600 kvm_check_extension(s
, KVM_CAP_X86_ROBUST_SINGLESTEP
);
1602 #ifdef KVM_CAP_DEBUGREGS
1603 s
->debugregs
= kvm_check_extension(s
, KVM_CAP_DEBUGREGS
);
1606 #ifdef KVM_CAP_IRQ_ROUTING
1607 kvm_direct_msi_allowed
= (kvm_check_extension(s
, KVM_CAP_SIGNAL_MSI
) > 0);
1610 s
->intx_set_mask
= kvm_check_extension(s
, KVM_CAP_PCI_2_3
);
1612 s
->irq_set_ioctl
= KVM_IRQ_LINE
;
1613 if (kvm_check_extension(s
, KVM_CAP_IRQ_INJECT_STATUS
)) {
1614 s
->irq_set_ioctl
= KVM_IRQ_LINE_STATUS
;
1617 #ifdef KVM_CAP_READONLY_MEM
1618 kvm_readonly_mem_allowed
=
1619 (kvm_check_extension(s
, KVM_CAP_READONLY_MEM
) > 0);
1622 kvm_eventfds_allowed
=
1623 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD
) > 0);
1625 kvm_irqfds_allowed
=
1626 (kvm_check_extension(s
, KVM_CAP_IRQFD
) > 0);
1628 kvm_resamplefds_allowed
=
1629 (kvm_check_extension(s
, KVM_CAP_IRQFD_RESAMPLE
) > 0);
1631 kvm_vm_attributes_allowed
=
1632 (kvm_check_extension(s
, KVM_CAP_VM_ATTRIBUTES
) > 0);
1634 kvm_ioeventfd_any_length_allowed
=
1635 (kvm_check_extension(s
, KVM_CAP_IOEVENTFD_ANY_LENGTH
) > 0);
1639 ret
= kvm_arch_init(ms
, s
);
1644 if (machine_kernel_irqchip_allowed(ms
)) {
1645 kvm_irqchip_create(ms
, s
);
1648 if (kvm_eventfds_allowed
) {
1649 s
->memory_listener
.listener
.eventfd_add
= kvm_mem_ioeventfd_add
;
1650 s
->memory_listener
.listener
.eventfd_del
= kvm_mem_ioeventfd_del
;
1652 s
->memory_listener
.listener
.coalesced_mmio_add
= kvm_coalesce_mmio_region
;
1653 s
->memory_listener
.listener
.coalesced_mmio_del
= kvm_uncoalesce_mmio_region
;
1655 kvm_memory_listener_register(s
, &s
->memory_listener
,
1656 &address_space_memory
, 0);
1657 memory_listener_register(&kvm_io_listener
,
1660 s
->many_ioeventfds
= kvm_check_many_ioeventfds();
1662 s
->sync_mmu
= !!kvm_vm_check_extension(kvm_state
, KVM_CAP_SYNC_MMU
);
1674 g_free(s
->memory_listener
.slots
);
1679 void kvm_set_sigmask_len(KVMState
*s
, unsigned int sigmask_len
)
1681 s
->sigmask_len
= sigmask_len
;
1684 static void kvm_handle_io(uint16_t port
, MemTxAttrs attrs
, void *data
, int direction
,
1685 int size
, uint32_t count
)
1688 uint8_t *ptr
= data
;
1690 for (i
= 0; i
< count
; i
++) {
1691 address_space_rw(&address_space_io
, port
, attrs
,
1693 direction
== KVM_EXIT_IO_OUT
);
1698 static int kvm_handle_internal_error(CPUState
*cpu
, struct kvm_run
*run
)
1700 fprintf(stderr
, "KVM internal error. Suberror: %d\n",
1701 run
->internal
.suberror
);
1703 if (kvm_check_extension(kvm_state
, KVM_CAP_INTERNAL_ERROR_DATA
)) {
1706 for (i
= 0; i
< run
->internal
.ndata
; ++i
) {
1707 fprintf(stderr
, "extra data[%d]: %"PRIx64
"\n",
1708 i
, (uint64_t)run
->internal
.data
[i
]);
1711 if (run
->internal
.suberror
== KVM_INTERNAL_ERROR_EMULATION
) {
1712 fprintf(stderr
, "emulation failure\n");
1713 if (!kvm_arch_stop_on_emulation_error(cpu
)) {
1714 cpu_dump_state(cpu
, stderr
, fprintf
, CPU_DUMP_CODE
);
1715 return EXCP_INTERRUPT
;
1718 /* FIXME: Should trigger a qmp message to let management know
1719 * something went wrong.
1724 void kvm_flush_coalesced_mmio_buffer(void)
1726 KVMState
*s
= kvm_state
;
1728 if (s
->coalesced_flush_in_progress
) {
1732 s
->coalesced_flush_in_progress
= true;
1734 if (s
->coalesced_mmio_ring
) {
1735 struct kvm_coalesced_mmio_ring
*ring
= s
->coalesced_mmio_ring
;
1736 while (ring
->first
!= ring
->last
) {
1737 struct kvm_coalesced_mmio
*ent
;
1739 ent
= &ring
->coalesced_mmio
[ring
->first
];
1741 cpu_physical_memory_write(ent
->phys_addr
, ent
->data
, ent
->len
);
1743 ring
->first
= (ring
->first
+ 1) % KVM_COALESCED_MMIO_MAX
;
1747 s
->coalesced_flush_in_progress
= false;
1750 static void do_kvm_cpu_synchronize_state(CPUState
*cpu
, run_on_cpu_data arg
)
1752 if (!cpu
->vcpu_dirty
) {
1753 kvm_arch_get_registers(cpu
);
1754 cpu
->vcpu_dirty
= true;
1758 void kvm_cpu_synchronize_state(CPUState
*cpu
)
1760 if (!cpu
->vcpu_dirty
) {
1761 run_on_cpu(cpu
, do_kvm_cpu_synchronize_state
, RUN_ON_CPU_NULL
);
1765 static void do_kvm_cpu_synchronize_post_reset(CPUState
*cpu
, run_on_cpu_data arg
)
1767 kvm_arch_put_registers(cpu
, KVM_PUT_RESET_STATE
);
1768 cpu
->vcpu_dirty
= false;
1771 void kvm_cpu_synchronize_post_reset(CPUState
*cpu
)
1773 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_reset
, RUN_ON_CPU_NULL
);
1776 static void do_kvm_cpu_synchronize_post_init(CPUState
*cpu
, run_on_cpu_data arg
)
1778 kvm_arch_put_registers(cpu
, KVM_PUT_FULL_STATE
);
1779 cpu
->vcpu_dirty
= false;
1782 void kvm_cpu_synchronize_post_init(CPUState
*cpu
)
1784 run_on_cpu(cpu
, do_kvm_cpu_synchronize_post_init
, RUN_ON_CPU_NULL
);
1787 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
, run_on_cpu_data arg
)
1789 cpu
->vcpu_dirty
= true;
1792 void kvm_cpu_synchronize_pre_loadvm(CPUState
*cpu
)
1794 run_on_cpu(cpu
, do_kvm_cpu_synchronize_pre_loadvm
, RUN_ON_CPU_NULL
);
1797 #ifdef KVM_HAVE_MCE_INJECTION
1798 static __thread
void *pending_sigbus_addr
;
1799 static __thread
int pending_sigbus_code
;
1800 static __thread
bool have_sigbus_pending
;
1803 static void kvm_cpu_kick(CPUState
*cpu
)
1805 atomic_set(&cpu
->kvm_run
->immediate_exit
, 1);
1808 static void kvm_cpu_kick_self(void)
1810 if (kvm_immediate_exit
) {
1811 kvm_cpu_kick(current_cpu
);
1813 qemu_cpu_kick_self();
1817 static void kvm_eat_signals(CPUState
*cpu
)
1819 struct timespec ts
= { 0, 0 };
1825 if (kvm_immediate_exit
) {
1826 atomic_set(&cpu
->kvm_run
->immediate_exit
, 0);
1827 /* Write kvm_run->immediate_exit before the cpu->exit_request
1828 * write in kvm_cpu_exec.
1834 sigemptyset(&waitset
);
1835 sigaddset(&waitset
, SIG_IPI
);
1838 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
1839 if (r
== -1 && !(errno
== EAGAIN
|| errno
== EINTR
)) {
1840 perror("sigtimedwait");
1844 r
= sigpending(&chkset
);
1846 perror("sigpending");
1849 } while (sigismember(&chkset
, SIG_IPI
));
1852 int kvm_cpu_exec(CPUState
*cpu
)
1854 struct kvm_run
*run
= cpu
->kvm_run
;
1857 DPRINTF("kvm_cpu_exec()\n");
1859 if (kvm_arch_process_async_events(cpu
)) {
1860 atomic_set(&cpu
->exit_request
, 0);
1864 qemu_mutex_unlock_iothread();
1865 cpu_exec_start(cpu
);
1870 if (cpu
->vcpu_dirty
) {
1871 kvm_arch_put_registers(cpu
, KVM_PUT_RUNTIME_STATE
);
1872 cpu
->vcpu_dirty
= false;
1875 kvm_arch_pre_run(cpu
, run
);
1876 if (atomic_read(&cpu
->exit_request
)) {
1877 DPRINTF("interrupt exit requested\n");
1879 * KVM requires us to reenter the kernel after IO exits to complete
1880 * instruction emulation. This self-signal will ensure that we
1883 kvm_cpu_kick_self();
1886 /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
1887 * Matching barrier in kvm_eat_signals.
1891 run_ret
= kvm_vcpu_ioctl(cpu
, KVM_RUN
, 0);
1893 attrs
= kvm_arch_post_run(cpu
, run
);
1895 #ifdef KVM_HAVE_MCE_INJECTION
1896 if (unlikely(have_sigbus_pending
)) {
1897 qemu_mutex_lock_iothread();
1898 kvm_arch_on_sigbus_vcpu(cpu
, pending_sigbus_code
,
1899 pending_sigbus_addr
);
1900 have_sigbus_pending
= false;
1901 qemu_mutex_unlock_iothread();
1906 if (run_ret
== -EINTR
|| run_ret
== -EAGAIN
) {
1907 DPRINTF("io window exit\n");
1908 kvm_eat_signals(cpu
);
1909 ret
= EXCP_INTERRUPT
;
1912 fprintf(stderr
, "error: kvm run failed %s\n",
1913 strerror(-run_ret
));
1915 if (run_ret
== -EBUSY
) {
1917 "This is probably because your SMT is enabled.\n"
1918 "VCPU can only run on primary threads with all "
1919 "secondary threads offline.\n");
1926 trace_kvm_run_exit(cpu
->cpu_index
, run
->exit_reason
);
1927 switch (run
->exit_reason
) {
1929 DPRINTF("handle_io\n");
1930 /* Called outside BQL */
1931 kvm_handle_io(run
->io
.port
, attrs
,
1932 (uint8_t *)run
+ run
->io
.data_offset
,
1939 DPRINTF("handle_mmio\n");
1940 /* Called outside BQL */
1941 address_space_rw(&address_space_memory
,
1942 run
->mmio
.phys_addr
, attrs
,
1945 run
->mmio
.is_write
);
1948 case KVM_EXIT_IRQ_WINDOW_OPEN
:
1949 DPRINTF("irq_window_open\n");
1950 ret
= EXCP_INTERRUPT
;
1952 case KVM_EXIT_SHUTDOWN
:
1953 DPRINTF("shutdown\n");
1954 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
1955 ret
= EXCP_INTERRUPT
;
1957 case KVM_EXIT_UNKNOWN
:
1958 fprintf(stderr
, "KVM: unknown exit, hardware reason %" PRIx64
"\n",
1959 (uint64_t)run
->hw
.hardware_exit_reason
);
1962 case KVM_EXIT_INTERNAL_ERROR
:
1963 ret
= kvm_handle_internal_error(cpu
, run
);
1965 case KVM_EXIT_SYSTEM_EVENT
:
1966 switch (run
->system_event
.type
) {
1967 case KVM_SYSTEM_EVENT_SHUTDOWN
:
1968 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN
);
1969 ret
= EXCP_INTERRUPT
;
1971 case KVM_SYSTEM_EVENT_RESET
:
1972 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET
);
1973 ret
= EXCP_INTERRUPT
;
1975 case KVM_SYSTEM_EVENT_CRASH
:
1976 kvm_cpu_synchronize_state(cpu
);
1977 qemu_mutex_lock_iothread();
1978 qemu_system_guest_panicked(cpu_get_crash_info(cpu
));
1979 qemu_mutex_unlock_iothread();
1983 DPRINTF("kvm_arch_handle_exit\n");
1984 ret
= kvm_arch_handle_exit(cpu
, run
);
1989 DPRINTF("kvm_arch_handle_exit\n");
1990 ret
= kvm_arch_handle_exit(cpu
, run
);
1996 qemu_mutex_lock_iothread();
1999 cpu_dump_state(cpu
, stderr
, fprintf
, CPU_DUMP_CODE
);
2000 vm_stop(RUN_STATE_INTERNAL_ERROR
);
2003 atomic_set(&cpu
->exit_request
, 0);
2007 int kvm_ioctl(KVMState
*s
, int type
, ...)
2014 arg
= va_arg(ap
, void *);
2017 trace_kvm_ioctl(type
, arg
);
2018 ret
= ioctl(s
->fd
, type
, arg
);
2025 int kvm_vm_ioctl(KVMState
*s
, int type
, ...)
2032 arg
= va_arg(ap
, void *);
2035 trace_kvm_vm_ioctl(type
, arg
);
2036 ret
= ioctl(s
->vmfd
, type
, arg
);
2043 int kvm_vcpu_ioctl(CPUState
*cpu
, int type
, ...)
2050 arg
= va_arg(ap
, void *);
2053 trace_kvm_vcpu_ioctl(cpu
->cpu_index
, type
, arg
);
2054 ret
= ioctl(cpu
->kvm_fd
, type
, arg
);
2061 int kvm_device_ioctl(int fd
, int type
, ...)
2068 arg
= va_arg(ap
, void *);
2071 trace_kvm_device_ioctl(fd
, type
, arg
);
2072 ret
= ioctl(fd
, type
, arg
);
2079 int kvm_vm_check_attr(KVMState
*s
, uint32_t group
, uint64_t attr
)
2082 struct kvm_device_attr attribute
= {
2087 if (!kvm_vm_attributes_allowed
) {
2091 ret
= kvm_vm_ioctl(s
, KVM_HAS_DEVICE_ATTR
, &attribute
);
2092 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2096 int kvm_device_check_attr(int dev_fd
, uint32_t group
, uint64_t attr
)
2098 struct kvm_device_attr attribute
= {
2104 return kvm_device_ioctl(dev_fd
, KVM_HAS_DEVICE_ATTR
, &attribute
) ? 0 : 1;
2107 int kvm_device_access(int fd
, int group
, uint64_t attr
,
2108 void *val
, bool write
, Error
**errp
)
2110 struct kvm_device_attr kvmattr
;
2114 kvmattr
.group
= group
;
2115 kvmattr
.attr
= attr
;
2116 kvmattr
.addr
= (uintptr_t)val
;
2118 err
= kvm_device_ioctl(fd
,
2119 write
? KVM_SET_DEVICE_ATTR
: KVM_GET_DEVICE_ATTR
,
2122 error_setg_errno(errp
, -err
,
2123 "KVM_%s_DEVICE_ATTR failed: Group %d "
2124 "attr 0x%016" PRIx64
,
2125 write
? "SET" : "GET", group
, attr
);
2130 bool kvm_has_sync_mmu(void)
2132 return kvm_state
->sync_mmu
;
2135 int kvm_has_vcpu_events(void)
2137 return kvm_state
->vcpu_events
;
2140 int kvm_has_robust_singlestep(void)
2142 return kvm_state
->robust_singlestep
;
2145 int kvm_has_debugregs(void)
2147 return kvm_state
->debugregs
;
2150 int kvm_has_many_ioeventfds(void)
2152 if (!kvm_enabled()) {
2155 return kvm_state
->many_ioeventfds
;
2158 int kvm_has_gsi_routing(void)
2160 #ifdef KVM_CAP_IRQ_ROUTING
2161 return kvm_check_extension(kvm_state
, KVM_CAP_IRQ_ROUTING
);
2167 int kvm_has_intx_set_mask(void)
2169 return kvm_state
->intx_set_mask
;
2172 bool kvm_arm_supports_user_irq(void)
2174 return kvm_check_extension(kvm_state
, KVM_CAP_ARM_USER_IRQ
);
2177 #ifdef KVM_CAP_SET_GUEST_DEBUG
2178 struct kvm_sw_breakpoint
*kvm_find_sw_breakpoint(CPUState
*cpu
,
2181 struct kvm_sw_breakpoint
*bp
;
2183 QTAILQ_FOREACH(bp
, &cpu
->kvm_state
->kvm_sw_breakpoints
, entry
) {
2191 int kvm_sw_breakpoints_active(CPUState
*cpu
)
2193 return !QTAILQ_EMPTY(&cpu
->kvm_state
->kvm_sw_breakpoints
);
2196 struct kvm_set_guest_debug_data
{
2197 struct kvm_guest_debug dbg
;
2201 static void kvm_invoke_set_guest_debug(CPUState
*cpu
, run_on_cpu_data data
)
2203 struct kvm_set_guest_debug_data
*dbg_data
=
2204 (struct kvm_set_guest_debug_data
*) data
.host_ptr
;
2206 dbg_data
->err
= kvm_vcpu_ioctl(cpu
, KVM_SET_GUEST_DEBUG
,
2210 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
2212 struct kvm_set_guest_debug_data data
;
2214 data
.dbg
.control
= reinject_trap
;
2216 if (cpu
->singlestep_enabled
) {
2217 data
.dbg
.control
|= KVM_GUESTDBG_ENABLE
| KVM_GUESTDBG_SINGLESTEP
;
2219 kvm_arch_update_guest_debug(cpu
, &data
.dbg
);
2221 run_on_cpu(cpu
, kvm_invoke_set_guest_debug
,
2222 RUN_ON_CPU_HOST_PTR(&data
));
2226 int kvm_insert_breakpoint(CPUState
*cpu
, target_ulong addr
,
2227 target_ulong len
, int type
)
2229 struct kvm_sw_breakpoint
*bp
;
2232 if (type
== GDB_BREAKPOINT_SW
) {
2233 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
2239 bp
= g_malloc(sizeof(struct kvm_sw_breakpoint
));
2242 err
= kvm_arch_insert_sw_breakpoint(cpu
, bp
);
2248 QTAILQ_INSERT_HEAD(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
2250 err
= kvm_arch_insert_hw_breakpoint(addr
, len
, type
);
2257 err
= kvm_update_guest_debug(cpu
, 0);
2265 int kvm_remove_breakpoint(CPUState
*cpu
, target_ulong addr
,
2266 target_ulong len
, int type
)
2268 struct kvm_sw_breakpoint
*bp
;
2271 if (type
== GDB_BREAKPOINT_SW
) {
2272 bp
= kvm_find_sw_breakpoint(cpu
, addr
);
2277 if (bp
->use_count
> 1) {
2282 err
= kvm_arch_remove_sw_breakpoint(cpu
, bp
);
2287 QTAILQ_REMOVE(&cpu
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
2290 err
= kvm_arch_remove_hw_breakpoint(addr
, len
, type
);
2297 err
= kvm_update_guest_debug(cpu
, 0);
2305 void kvm_remove_all_breakpoints(CPUState
*cpu
)
2307 struct kvm_sw_breakpoint
*bp
, *next
;
2308 KVMState
*s
= cpu
->kvm_state
;
2311 QTAILQ_FOREACH_SAFE(bp
, &s
->kvm_sw_breakpoints
, entry
, next
) {
2312 if (kvm_arch_remove_sw_breakpoint(cpu
, bp
) != 0) {
2313 /* Try harder to find a CPU that currently sees the breakpoint. */
2314 CPU_FOREACH(tmpcpu
) {
2315 if (kvm_arch_remove_sw_breakpoint(tmpcpu
, bp
) == 0) {
2320 QTAILQ_REMOVE(&s
->kvm_sw_breakpoints
, bp
, entry
);
2323 kvm_arch_remove_all_hw_breakpoints();
2326 kvm_update_guest_debug(cpu
, 0);
2330 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2332 int kvm_update_guest_debug(CPUState
*cpu
, unsigned long reinject_trap
)
2337 int kvm_insert_breakpoint(CPUState
*cpu
, target_ulong addr
,
2338 target_ulong len
, int type
)
2343 int kvm_remove_breakpoint(CPUState
*cpu
, target_ulong addr
,
2344 target_ulong len
, int type
)
2349 void kvm_remove_all_breakpoints(CPUState
*cpu
)
2352 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2354 static int kvm_set_signal_mask(CPUState
*cpu
, const sigset_t
*sigset
)
2356 KVMState
*s
= kvm_state
;
2357 struct kvm_signal_mask
*sigmask
;
2360 sigmask
= g_malloc(sizeof(*sigmask
) + sizeof(*sigset
));
2362 sigmask
->len
= s
->sigmask_len
;
2363 memcpy(sigmask
->sigset
, sigset
, sizeof(*sigset
));
2364 r
= kvm_vcpu_ioctl(cpu
, KVM_SET_SIGNAL_MASK
, sigmask
);
2370 static void kvm_ipi_signal(int sig
)
2373 assert(kvm_immediate_exit
);
2374 kvm_cpu_kick(current_cpu
);
2378 void kvm_init_cpu_signals(CPUState
*cpu
)
2382 struct sigaction sigact
;
2384 memset(&sigact
, 0, sizeof(sigact
));
2385 sigact
.sa_handler
= kvm_ipi_signal
;
2386 sigaction(SIG_IPI
, &sigact
, NULL
);
2388 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
2389 #if defined KVM_HAVE_MCE_INJECTION
2390 sigdelset(&set
, SIGBUS
);
2391 pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
2393 sigdelset(&set
, SIG_IPI
);
2394 if (kvm_immediate_exit
) {
2395 r
= pthread_sigmask(SIG_SETMASK
, &set
, NULL
);
2397 r
= kvm_set_signal_mask(cpu
, &set
);
2400 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(-r
));
2405 /* Called asynchronously in VCPU thread. */
2406 int kvm_on_sigbus_vcpu(CPUState
*cpu
, int code
, void *addr
)
2408 #ifdef KVM_HAVE_MCE_INJECTION
2409 if (have_sigbus_pending
) {
2412 have_sigbus_pending
= true;
2413 pending_sigbus_addr
= addr
;
2414 pending_sigbus_code
= code
;
2415 atomic_set(&cpu
->exit_request
, 1);
2422 /* Called synchronously (via signalfd) in main thread. */
2423 int kvm_on_sigbus(int code
, void *addr
)
2425 #ifdef KVM_HAVE_MCE_INJECTION
2426 /* Action required MCE kills the process if SIGBUS is blocked. Because
2427 * that's what happens in the I/O thread, where we handle MCE via signalfd,
2428 * we can only get action optional here.
2430 assert(code
!= BUS_MCEERR_AR
);
2431 kvm_arch_on_sigbus_vcpu(first_cpu
, code
, addr
);
2438 int kvm_create_device(KVMState
*s
, uint64_t type
, bool test
)
2441 struct kvm_create_device create_dev
;
2443 create_dev
.type
= type
;
2445 create_dev
.flags
= test
? KVM_CREATE_DEVICE_TEST
: 0;
2447 if (!kvm_check_extension(s
, KVM_CAP_DEVICE_CTRL
)) {
2451 ret
= kvm_vm_ioctl(s
, KVM_CREATE_DEVICE
, &create_dev
);
2456 return test
? 0 : create_dev
.fd
;
2459 bool kvm_device_supported(int vmfd
, uint64_t type
)
2461 struct kvm_create_device create_dev
= {
2464 .flags
= KVM_CREATE_DEVICE_TEST
,
2467 if (ioctl(vmfd
, KVM_CHECK_EXTENSION
, KVM_CAP_DEVICE_CTRL
) <= 0) {
2471 return (ioctl(vmfd
, KVM_CREATE_DEVICE
, &create_dev
) >= 0);
2474 int kvm_set_one_reg(CPUState
*cs
, uint64_t id
, void *source
)
2476 struct kvm_one_reg reg
;
2480 reg
.addr
= (uintptr_t) source
;
2481 r
= kvm_vcpu_ioctl(cs
, KVM_SET_ONE_REG
, ®
);
2483 trace_kvm_failed_reg_set(id
, strerror(-r
));
2488 int kvm_get_one_reg(CPUState
*cs
, uint64_t id
, void *target
)
2490 struct kvm_one_reg reg
;
2494 reg
.addr
= (uintptr_t) target
;
2495 r
= kvm_vcpu_ioctl(cs
, KVM_GET_ONE_REG
, ®
);
2497 trace_kvm_failed_reg_get(id
, strerror(-r
));
2502 static void kvm_accel_class_init(ObjectClass
*oc
, void *data
)
2504 AccelClass
*ac
= ACCEL_CLASS(oc
);
2506 ac
->init_machine
= kvm_init
;
2507 ac
->allowed
= &kvm_allowed
;
2510 static const TypeInfo kvm_accel_type
= {
2511 .name
= TYPE_KVM_ACCEL
,
2512 .parent
= TYPE_ACCEL
,
2513 .class_init
= kvm_accel_class_init
,
2514 .instance_size
= sizeof(KVMState
),
2517 static void kvm_type_init(void)
2519 type_register_static(&kvm_accel_type
);
2522 type_init(kvm_type_init
);