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 <sys/types.h>
17 #include <sys/ioctl.h>
21 #include <linux/kvm.h>
23 #include "qemu-common.h"
24 #include "qemu-barrier.h"
32 #include "exec-memory.h"
34 /* This check must be after config-host.h is included */
36 #include <sys/eventfd.h>
39 /* KVM uses PAGE_SIZE in its definition of COALESCED_MMIO_MAX */
40 #define PAGE_SIZE TARGET_PAGE_SIZE
45 #define DPRINTF(fmt, ...) \
46 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
48 #define DPRINTF(fmt, ...) \
52 #define KVM_MSI_HASHTAB_SIZE 256
54 typedef struct KVMSlot
56 target_phys_addr_t start_addr
;
57 ram_addr_t memory_size
;
63 typedef struct kvm_dirty_log KVMDirtyLog
;
65 typedef struct KVMMSIRoute
{
66 struct kvm_irq_routing_entry kroute
;
67 QTAILQ_ENTRY(KVMMSIRoute
) entry
;
76 struct kvm_coalesced_mmio_ring
*coalesced_mmio_ring
;
77 bool coalesced_flush_in_progress
;
78 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
;
89 /* The man page (and posix) say ioctl numbers are signed int, but
90 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
91 * unsigned, and treating them as signed here can break things */
92 unsigned irqchip_inject_ioctl
;
93 #ifdef KVM_CAP_IRQ_ROUTING
94 struct kvm_irq_routing
*irq_routes
;
95 int nr_allocated_irq_routes
;
96 uint32_t *used_gsi_bitmap
;
97 unsigned int gsi_count
;
98 QTAILQ_HEAD(msi_hashtab
, KVMMSIRoute
) msi_hashtab
[KVM_MSI_HASHTAB_SIZE
];
103 bool kvm_kernel_irqchip
;
105 static const KVMCapabilityInfo kvm_required_capabilites
[] = {
106 KVM_CAP_INFO(USER_MEMORY
),
107 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS
),
111 static KVMSlot
*kvm_alloc_slot(KVMState
*s
)
115 for (i
= 0; i
< ARRAY_SIZE(s
->slots
); i
++) {
116 if (s
->slots
[i
].memory_size
== 0) {
121 fprintf(stderr
, "%s: no free slot available\n", __func__
);
125 static KVMSlot
*kvm_lookup_matching_slot(KVMState
*s
,
126 target_phys_addr_t start_addr
,
127 target_phys_addr_t end_addr
)
131 for (i
= 0; i
< ARRAY_SIZE(s
->slots
); i
++) {
132 KVMSlot
*mem
= &s
->slots
[i
];
134 if (start_addr
== mem
->start_addr
&&
135 end_addr
== mem
->start_addr
+ mem
->memory_size
) {
144 * Find overlapping slot with lowest start address
146 static KVMSlot
*kvm_lookup_overlapping_slot(KVMState
*s
,
147 target_phys_addr_t start_addr
,
148 target_phys_addr_t end_addr
)
150 KVMSlot
*found
= NULL
;
153 for (i
= 0; i
< ARRAY_SIZE(s
->slots
); i
++) {
154 KVMSlot
*mem
= &s
->slots
[i
];
156 if (mem
->memory_size
== 0 ||
157 (found
&& found
->start_addr
< mem
->start_addr
)) {
161 if (end_addr
> mem
->start_addr
&&
162 start_addr
< mem
->start_addr
+ mem
->memory_size
) {
170 int kvm_physical_memory_addr_from_host(KVMState
*s
, void *ram
,
171 target_phys_addr_t
*phys_addr
)
175 for (i
= 0; i
< ARRAY_SIZE(s
->slots
); i
++) {
176 KVMSlot
*mem
= &s
->slots
[i
];
178 if (ram
>= mem
->ram
&& ram
< mem
->ram
+ mem
->memory_size
) {
179 *phys_addr
= mem
->start_addr
+ (ram
- mem
->ram
);
187 static int kvm_set_user_memory_region(KVMState
*s
, KVMSlot
*slot
)
189 struct kvm_userspace_memory_region mem
;
191 mem
.slot
= slot
->slot
;
192 mem
.guest_phys_addr
= slot
->start_addr
;
193 mem
.memory_size
= slot
->memory_size
;
194 mem
.userspace_addr
= (unsigned long)slot
->ram
;
195 mem
.flags
= slot
->flags
;
196 if (s
->migration_log
) {
197 mem
.flags
|= KVM_MEM_LOG_DIRTY_PAGES
;
199 return kvm_vm_ioctl(s
, KVM_SET_USER_MEMORY_REGION
, &mem
);
202 static void kvm_reset_vcpu(void *opaque
)
204 CPUArchState
*env
= opaque
;
206 kvm_arch_reset_vcpu(env
);
209 int kvm_init_vcpu(CPUArchState
*env
)
211 KVMState
*s
= kvm_state
;
215 DPRINTF("kvm_init_vcpu\n");
217 ret
= kvm_vm_ioctl(s
, KVM_CREATE_VCPU
, env
->cpu_index
);
219 DPRINTF("kvm_create_vcpu failed\n");
225 env
->kvm_vcpu_dirty
= 1;
227 mmap_size
= kvm_ioctl(s
, KVM_GET_VCPU_MMAP_SIZE
, 0);
230 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
234 env
->kvm_run
= mmap(NULL
, mmap_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
236 if (env
->kvm_run
== MAP_FAILED
) {
238 DPRINTF("mmap'ing vcpu state failed\n");
242 if (s
->coalesced_mmio
&& !s
->coalesced_mmio_ring
) {
243 s
->coalesced_mmio_ring
=
244 (void *)env
->kvm_run
+ s
->coalesced_mmio
* PAGE_SIZE
;
247 ret
= kvm_arch_init_vcpu(env
);
249 qemu_register_reset(kvm_reset_vcpu
, env
);
250 kvm_arch_reset_vcpu(env
);
257 * dirty pages logging control
260 static int kvm_mem_flags(KVMState
*s
, bool log_dirty
)
262 return log_dirty
? KVM_MEM_LOG_DIRTY_PAGES
: 0;
265 static int kvm_slot_dirty_pages_log_change(KVMSlot
*mem
, bool log_dirty
)
267 KVMState
*s
= kvm_state
;
268 int flags
, mask
= KVM_MEM_LOG_DIRTY_PAGES
;
271 old_flags
= mem
->flags
;
273 flags
= (mem
->flags
& ~mask
) | kvm_mem_flags(s
, log_dirty
);
276 /* If nothing changed effectively, no need to issue ioctl */
277 if (s
->migration_log
) {
278 flags
|= KVM_MEM_LOG_DIRTY_PAGES
;
281 if (flags
== old_flags
) {
285 return kvm_set_user_memory_region(s
, mem
);
288 static int kvm_dirty_pages_log_change(target_phys_addr_t phys_addr
,
289 ram_addr_t size
, bool log_dirty
)
291 KVMState
*s
= kvm_state
;
292 KVMSlot
*mem
= kvm_lookup_matching_slot(s
, phys_addr
, phys_addr
+ size
);
295 fprintf(stderr
, "BUG: %s: invalid parameters " TARGET_FMT_plx
"-"
296 TARGET_FMT_plx
"\n", __func__
, phys_addr
,
297 (target_phys_addr_t
)(phys_addr
+ size
- 1));
300 return kvm_slot_dirty_pages_log_change(mem
, log_dirty
);
303 static void kvm_log_start(MemoryListener
*listener
,
304 MemoryRegionSection
*section
)
308 r
= kvm_dirty_pages_log_change(section
->offset_within_address_space
,
309 section
->size
, true);
315 static void kvm_log_stop(MemoryListener
*listener
,
316 MemoryRegionSection
*section
)
320 r
= kvm_dirty_pages_log_change(section
->offset_within_address_space
,
321 section
->size
, false);
327 static int kvm_set_migration_log(int enable
)
329 KVMState
*s
= kvm_state
;
333 s
->migration_log
= enable
;
335 for (i
= 0; i
< ARRAY_SIZE(s
->slots
); i
++) {
338 if (!mem
->memory_size
) {
341 if (!!(mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) == enable
) {
344 err
= kvm_set_user_memory_region(s
, mem
);
352 /* get kvm's dirty pages bitmap and update qemu's */
353 static int kvm_get_dirty_pages_log_range(MemoryRegionSection
*section
,
354 unsigned long *bitmap
)
357 unsigned long page_number
, c
;
358 target_phys_addr_t addr
, addr1
;
359 unsigned int len
= ((section
->size
/ TARGET_PAGE_SIZE
) + HOST_LONG_BITS
- 1) / HOST_LONG_BITS
;
360 unsigned long hpratio
= getpagesize() / TARGET_PAGE_SIZE
;
363 * bitmap-traveling is faster than memory-traveling (for addr...)
364 * especially when most of the memory is not dirty.
366 for (i
= 0; i
< len
; i
++) {
367 if (bitmap
[i
] != 0) {
368 c
= leul_to_cpu(bitmap
[i
]);
372 page_number
= (i
* HOST_LONG_BITS
+ j
) * hpratio
;
373 addr1
= page_number
* TARGET_PAGE_SIZE
;
374 addr
= section
->offset_within_region
+ addr1
;
375 memory_region_set_dirty(section
->mr
, addr
,
376 TARGET_PAGE_SIZE
* hpratio
);
383 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
386 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
387 * This function updates qemu's dirty bitmap using
388 * memory_region_set_dirty(). This means all bits are set
391 * @start_add: start of logged region.
392 * @end_addr: end of logged region.
394 static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection
*section
)
396 KVMState
*s
= kvm_state
;
397 unsigned long size
, allocated_size
= 0;
401 target_phys_addr_t start_addr
= section
->offset_within_address_space
;
402 target_phys_addr_t end_addr
= start_addr
+ section
->size
;
404 d
.dirty_bitmap
= NULL
;
405 while (start_addr
< end_addr
) {
406 mem
= kvm_lookup_overlapping_slot(s
, start_addr
, end_addr
);
411 /* XXX bad kernel interface alert
412 * For dirty bitmap, kernel allocates array of size aligned to
413 * bits-per-long. But for case when the kernel is 64bits and
414 * the userspace is 32bits, userspace can't align to the same
415 * bits-per-long, since sizeof(long) is different between kernel
416 * and user space. This way, userspace will provide buffer which
417 * may be 4 bytes less than the kernel will use, resulting in
418 * userspace memory corruption (which is not detectable by valgrind
419 * too, in most cases).
420 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
421 * a hope that sizeof(long) wont become >8 any time soon.
423 size
= ALIGN(((mem
->memory_size
) >> TARGET_PAGE_BITS
),
424 /*HOST_LONG_BITS*/ 64) / 8;
425 if (!d
.dirty_bitmap
) {
426 d
.dirty_bitmap
= g_malloc(size
);
427 } else if (size
> allocated_size
) {
428 d
.dirty_bitmap
= g_realloc(d
.dirty_bitmap
, size
);
430 allocated_size
= size
;
431 memset(d
.dirty_bitmap
, 0, allocated_size
);
435 if (kvm_vm_ioctl(s
, KVM_GET_DIRTY_LOG
, &d
) == -1) {
436 DPRINTF("ioctl failed %d\n", errno
);
441 kvm_get_dirty_pages_log_range(section
, d
.dirty_bitmap
);
442 start_addr
= mem
->start_addr
+ mem
->memory_size
;
444 g_free(d
.dirty_bitmap
);
449 int kvm_coalesce_mmio_region(target_phys_addr_t start
, ram_addr_t size
)
452 KVMState
*s
= kvm_state
;
454 if (s
->coalesced_mmio
) {
455 struct kvm_coalesced_mmio_zone zone
;
461 ret
= kvm_vm_ioctl(s
, KVM_REGISTER_COALESCED_MMIO
, &zone
);
467 int kvm_uncoalesce_mmio_region(target_phys_addr_t start
, ram_addr_t size
)
470 KVMState
*s
= kvm_state
;
472 if (s
->coalesced_mmio
) {
473 struct kvm_coalesced_mmio_zone zone
;
479 ret
= kvm_vm_ioctl(s
, KVM_UNREGISTER_COALESCED_MMIO
, &zone
);
485 int kvm_check_extension(KVMState
*s
, unsigned int extension
)
489 ret
= kvm_ioctl(s
, KVM_CHECK_EXTENSION
, extension
);
497 static int kvm_check_many_ioeventfds(void)
499 /* Userspace can use ioeventfd for io notification. This requires a host
500 * that supports eventfd(2) and an I/O thread; since eventfd does not
501 * support SIGIO it cannot interrupt the vcpu.
503 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
504 * can avoid creating too many ioeventfds.
506 #if defined(CONFIG_EVENTFD)
509 for (i
= 0; i
< ARRAY_SIZE(ioeventfds
); i
++) {
510 ioeventfds
[i
] = eventfd(0, EFD_CLOEXEC
);
511 if (ioeventfds
[i
] < 0) {
514 ret
= kvm_set_ioeventfd_pio_word(ioeventfds
[i
], 0, i
, true);
516 close(ioeventfds
[i
]);
521 /* Decide whether many devices are supported or not */
522 ret
= i
== ARRAY_SIZE(ioeventfds
);
525 kvm_set_ioeventfd_pio_word(ioeventfds
[i
], 0, i
, false);
526 close(ioeventfds
[i
]);
534 static const KVMCapabilityInfo
*
535 kvm_check_extension_list(KVMState
*s
, const KVMCapabilityInfo
*list
)
538 if (!kvm_check_extension(s
, list
->value
)) {
546 static void kvm_set_phys_mem(MemoryRegionSection
*section
, bool add
)
548 KVMState
*s
= kvm_state
;
551 MemoryRegion
*mr
= section
->mr
;
552 bool log_dirty
= memory_region_is_logging(mr
);
553 target_phys_addr_t start_addr
= section
->offset_within_address_space
;
554 ram_addr_t size
= section
->size
;
558 /* kvm works in page size chunks, but the function may be called
559 with sub-page size and unaligned start address. */
560 delta
= TARGET_PAGE_ALIGN(size
) - size
;
566 size
&= TARGET_PAGE_MASK
;
567 if (!size
|| (start_addr
& ~TARGET_PAGE_MASK
)) {
571 if (!memory_region_is_ram(mr
)) {
575 ram
= memory_region_get_ram_ptr(mr
) + section
->offset_within_region
+ delta
;
578 mem
= kvm_lookup_overlapping_slot(s
, start_addr
, start_addr
+ size
);
583 if (add
&& start_addr
>= mem
->start_addr
&&
584 (start_addr
+ size
<= mem
->start_addr
+ mem
->memory_size
) &&
585 (ram
- start_addr
== mem
->ram
- mem
->start_addr
)) {
586 /* The new slot fits into the existing one and comes with
587 * identical parameters - update flags and done. */
588 kvm_slot_dirty_pages_log_change(mem
, log_dirty
);
594 if (mem
->flags
& KVM_MEM_LOG_DIRTY_PAGES
) {
595 kvm_physical_sync_dirty_bitmap(section
);
598 /* unregister the overlapping slot */
599 mem
->memory_size
= 0;
600 err
= kvm_set_user_memory_region(s
, mem
);
602 fprintf(stderr
, "%s: error unregistering overlapping slot: %s\n",
603 __func__
, strerror(-err
));
607 /* Workaround for older KVM versions: we can't join slots, even not by
608 * unregistering the previous ones and then registering the larger
609 * slot. We have to maintain the existing fragmentation. Sigh.
611 * This workaround assumes that the new slot starts at the same
612 * address as the first existing one. If not or if some overlapping
613 * slot comes around later, we will fail (not seen in practice so far)
614 * - and actually require a recent KVM version. */
615 if (s
->broken_set_mem_region
&&
616 old
.start_addr
== start_addr
&& old
.memory_size
< size
&& add
) {
617 mem
= kvm_alloc_slot(s
);
618 mem
->memory_size
= old
.memory_size
;
619 mem
->start_addr
= old
.start_addr
;
621 mem
->flags
= kvm_mem_flags(s
, log_dirty
);
623 err
= kvm_set_user_memory_region(s
, mem
);
625 fprintf(stderr
, "%s: error updating slot: %s\n", __func__
,
630 start_addr
+= old
.memory_size
;
631 ram
+= old
.memory_size
;
632 size
-= old
.memory_size
;
636 /* register prefix slot */
637 if (old
.start_addr
< start_addr
) {
638 mem
= kvm_alloc_slot(s
);
639 mem
->memory_size
= start_addr
- old
.start_addr
;
640 mem
->start_addr
= old
.start_addr
;
642 mem
->flags
= kvm_mem_flags(s
, log_dirty
);
644 err
= kvm_set_user_memory_region(s
, mem
);
646 fprintf(stderr
, "%s: error registering prefix slot: %s\n",
647 __func__
, strerror(-err
));
649 fprintf(stderr
, "%s: This is probably because your kernel's " \
650 "PAGE_SIZE is too big. Please try to use 4k " \
651 "PAGE_SIZE!\n", __func__
);
657 /* register suffix slot */
658 if (old
.start_addr
+ old
.memory_size
> start_addr
+ size
) {
659 ram_addr_t size_delta
;
661 mem
= kvm_alloc_slot(s
);
662 mem
->start_addr
= start_addr
+ size
;
663 size_delta
= mem
->start_addr
- old
.start_addr
;
664 mem
->memory_size
= old
.memory_size
- size_delta
;
665 mem
->ram
= old
.ram
+ size_delta
;
666 mem
->flags
= kvm_mem_flags(s
, log_dirty
);
668 err
= kvm_set_user_memory_region(s
, mem
);
670 fprintf(stderr
, "%s: error registering suffix slot: %s\n",
671 __func__
, strerror(-err
));
677 /* in case the KVM bug workaround already "consumed" the new slot */
684 mem
= kvm_alloc_slot(s
);
685 mem
->memory_size
= size
;
686 mem
->start_addr
= start_addr
;
688 mem
->flags
= kvm_mem_flags(s
, log_dirty
);
690 err
= kvm_set_user_memory_region(s
, mem
);
692 fprintf(stderr
, "%s: error registering slot: %s\n", __func__
,
698 static void kvm_begin(MemoryListener
*listener
)
702 static void kvm_commit(MemoryListener
*listener
)
706 static void kvm_region_add(MemoryListener
*listener
,
707 MemoryRegionSection
*section
)
709 kvm_set_phys_mem(section
, true);
712 static void kvm_region_del(MemoryListener
*listener
,
713 MemoryRegionSection
*section
)
715 kvm_set_phys_mem(section
, false);
718 static void kvm_region_nop(MemoryListener
*listener
,
719 MemoryRegionSection
*section
)
723 static void kvm_log_sync(MemoryListener
*listener
,
724 MemoryRegionSection
*section
)
728 r
= kvm_physical_sync_dirty_bitmap(section
);
734 static void kvm_log_global_start(struct MemoryListener
*listener
)
738 r
= kvm_set_migration_log(1);
742 static void kvm_log_global_stop(struct MemoryListener
*listener
)
746 r
= kvm_set_migration_log(0);
750 static void kvm_mem_ioeventfd_add(MemoryRegionSection
*section
,
751 bool match_data
, uint64_t data
, int fd
)
755 assert(match_data
&& section
->size
<= 8);
757 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
758 data
, true, section
->size
);
764 static void kvm_mem_ioeventfd_del(MemoryRegionSection
*section
,
765 bool match_data
, uint64_t data
, int fd
)
769 r
= kvm_set_ioeventfd_mmio(fd
, section
->offset_within_address_space
,
770 data
, false, section
->size
);
776 static void kvm_io_ioeventfd_add(MemoryRegionSection
*section
,
777 bool match_data
, uint64_t data
, int fd
)
781 assert(match_data
&& section
->size
== 2);
783 r
= kvm_set_ioeventfd_pio_word(fd
, section
->offset_within_address_space
,
790 static void kvm_io_ioeventfd_del(MemoryRegionSection
*section
,
791 bool match_data
, uint64_t data
, int fd
)
796 r
= kvm_set_ioeventfd_pio_word(fd
, section
->offset_within_address_space
,
803 static void kvm_eventfd_add(MemoryListener
*listener
,
804 MemoryRegionSection
*section
,
805 bool match_data
, uint64_t data
, int fd
)
807 if (section
->address_space
== get_system_memory()) {
808 kvm_mem_ioeventfd_add(section
, match_data
, data
, fd
);
810 kvm_io_ioeventfd_add(section
, match_data
, data
, fd
);
814 static void kvm_eventfd_del(MemoryListener
*listener
,
815 MemoryRegionSection
*section
,
816 bool match_data
, uint64_t data
, int fd
)
818 if (section
->address_space
== get_system_memory()) {
819 kvm_mem_ioeventfd_del(section
, match_data
, data
, fd
);
821 kvm_io_ioeventfd_del(section
, match_data
, data
, fd
);
825 static MemoryListener kvm_memory_listener
= {
827 .commit
= kvm_commit
,
828 .region_add
= kvm_region_add
,
829 .region_del
= kvm_region_del
,
830 .region_nop
= kvm_region_nop
,
831 .log_start
= kvm_log_start
,
832 .log_stop
= kvm_log_stop
,
833 .log_sync
= kvm_log_sync
,
834 .log_global_start
= kvm_log_global_start
,
835 .log_global_stop
= kvm_log_global_stop
,
836 .eventfd_add
= kvm_eventfd_add
,
837 .eventfd_del
= kvm_eventfd_del
,
841 static void kvm_handle_interrupt(CPUArchState
*env
, int mask
)
843 env
->interrupt_request
|= mask
;
845 if (!qemu_cpu_is_self(env
)) {
850 int kvm_irqchip_set_irq(KVMState
*s
, int irq
, int level
)
852 struct kvm_irq_level event
;
855 assert(kvm_irqchip_in_kernel());
859 ret
= kvm_vm_ioctl(s
, s
->irqchip_inject_ioctl
, &event
);
861 perror("kvm_set_irqchip_line");
865 return (s
->irqchip_inject_ioctl
== KVM_IRQ_LINE
) ? 1 : event
.status
;
868 #ifdef KVM_CAP_IRQ_ROUTING
869 static void set_gsi(KVMState
*s
, unsigned int gsi
)
871 s
->used_gsi_bitmap
[gsi
/ 32] |= 1U << (gsi
% 32);
874 static void clear_gsi(KVMState
*s
, unsigned int gsi
)
876 s
->used_gsi_bitmap
[gsi
/ 32] &= ~(1U << (gsi
% 32));
879 static void kvm_init_irq_routing(KVMState
*s
)
883 gsi_count
= kvm_check_extension(s
, KVM_CAP_IRQ_ROUTING
);
885 unsigned int gsi_bits
, i
;
887 /* Round up so we can search ints using ffs */
888 gsi_bits
= ALIGN(gsi_count
, 32);
889 s
->used_gsi_bitmap
= g_malloc0(gsi_bits
/ 8);
890 s
->gsi_count
= gsi_count
;
892 /* Mark any over-allocated bits as already in use */
893 for (i
= gsi_count
; i
< gsi_bits
; i
++) {
898 s
->irq_routes
= g_malloc0(sizeof(*s
->irq_routes
));
899 s
->nr_allocated_irq_routes
= 0;
901 for (i
= 0; i
< KVM_MSI_HASHTAB_SIZE
; i
++) {
902 QTAILQ_INIT(&s
->msi_hashtab
[i
]);
905 kvm_arch_init_irq_routing(s
);
908 static void kvm_add_routing_entry(KVMState
*s
,
909 struct kvm_irq_routing_entry
*entry
)
911 struct kvm_irq_routing_entry
*new;
914 if (s
->irq_routes
->nr
== s
->nr_allocated_irq_routes
) {
915 n
= s
->nr_allocated_irq_routes
* 2;
919 size
= sizeof(struct kvm_irq_routing
);
920 size
+= n
* sizeof(*new);
921 s
->irq_routes
= g_realloc(s
->irq_routes
, size
);
922 s
->nr_allocated_irq_routes
= n
;
924 n
= s
->irq_routes
->nr
++;
925 new = &s
->irq_routes
->entries
[n
];
926 memset(new, 0, sizeof(*new));
927 new->gsi
= entry
->gsi
;
928 new->type
= entry
->type
;
929 new->flags
= entry
->flags
;
932 set_gsi(s
, entry
->gsi
);
935 void kvm_irqchip_add_route(KVMState
*s
, int irq
, int irqchip
, int pin
)
937 struct kvm_irq_routing_entry e
;
939 assert(pin
< s
->gsi_count
);
942 e
.type
= KVM_IRQ_ROUTING_IRQCHIP
;
944 e
.u
.irqchip
.irqchip
= irqchip
;
945 e
.u
.irqchip
.pin
= pin
;
946 kvm_add_routing_entry(s
, &e
);
949 int kvm_irqchip_commit_routes(KVMState
*s
)
951 s
->irq_routes
->flags
= 0;
952 return kvm_vm_ioctl(s
, KVM_SET_GSI_ROUTING
, s
->irq_routes
);
955 static void kvm_irqchip_release_virq(KVMState
*s
, int virq
)
957 struct kvm_irq_routing_entry
*e
;
960 for (i
= 0; i
< s
->irq_routes
->nr
; i
++) {
961 e
= &s
->irq_routes
->entries
[i
];
962 if (e
->gsi
== virq
) {
964 *e
= s
->irq_routes
->entries
[s
->irq_routes
->nr
];
970 static unsigned int kvm_hash_msi(uint32_t data
)
972 /* This is optimized for IA32 MSI layout. However, no other arch shall
973 * repeat the mistake of not providing a direct MSI injection API. */
977 static void kvm_flush_dynamic_msi_routes(KVMState
*s
)
979 KVMMSIRoute
*route
, *next
;
982 for (hash
= 0; hash
< KVM_MSI_HASHTAB_SIZE
; hash
++) {
983 QTAILQ_FOREACH_SAFE(route
, &s
->msi_hashtab
[hash
], entry
, next
) {
984 kvm_irqchip_release_virq(s
, route
->kroute
.gsi
);
985 QTAILQ_REMOVE(&s
->msi_hashtab
[hash
], route
, entry
);
991 static int kvm_irqchip_get_virq(KVMState
*s
)
993 uint32_t *word
= s
->used_gsi_bitmap
;
994 int max_words
= ALIGN(s
->gsi_count
, 32) / 32;
999 /* Return the lowest unused GSI in the bitmap */
1000 for (i
= 0; i
< max_words
; i
++) {
1001 bit
= ffs(~word
[i
]);
1006 return bit
- 1 + i
* 32;
1010 kvm_flush_dynamic_msi_routes(s
);
1017 static KVMMSIRoute
*kvm_lookup_msi_route(KVMState
*s
, MSIMessage msg
)
1019 unsigned int hash
= kvm_hash_msi(msg
.data
);
1022 QTAILQ_FOREACH(route
, &s
->msi_hashtab
[hash
], entry
) {
1023 if (route
->kroute
.u
.msi
.address_lo
== (uint32_t)msg
.address
&&
1024 route
->kroute
.u
.msi
.address_hi
== (msg
.address
>> 32) &&
1025 route
->kroute
.u
.msi
.data
== msg
.data
) {
1032 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1036 route
= kvm_lookup_msi_route(s
, msg
);
1040 virq
= kvm_irqchip_get_virq(s
);
1045 route
= g_malloc(sizeof(KVMMSIRoute
));
1046 route
->kroute
.gsi
= virq
;
1047 route
->kroute
.type
= KVM_IRQ_ROUTING_MSI
;
1048 route
->kroute
.flags
= 0;
1049 route
->kroute
.u
.msi
.address_lo
= (uint32_t)msg
.address
;
1050 route
->kroute
.u
.msi
.address_hi
= msg
.address
>> 32;
1051 route
->kroute
.u
.msi
.data
= msg
.data
;
1053 kvm_add_routing_entry(s
, &route
->kroute
);
1055 QTAILQ_INSERT_TAIL(&s
->msi_hashtab
[kvm_hash_msi(msg
.data
)], route
,
1058 ret
= kvm_irqchip_commit_routes(s
);
1064 assert(route
->kroute
.type
== KVM_IRQ_ROUTING_MSI
);
1066 return kvm_irqchip_set_irq(s
, route
->kroute
.gsi
, 1);
1069 #else /* !KVM_CAP_IRQ_ROUTING */
1071 static void kvm_init_irq_routing(KVMState
*s
)
1075 int kvm_irqchip_send_msi(KVMState
*s
, MSIMessage msg
)
1079 #endif /* !KVM_CAP_IRQ_ROUTING */
1081 static int kvm_irqchip_create(KVMState
*s
)
1083 QemuOptsList
*list
= qemu_find_opts("machine");
1086 if (QTAILQ_EMPTY(&list
->head
) ||
1087 !qemu_opt_get_bool(QTAILQ_FIRST(&list
->head
),
1088 "kernel_irqchip", false) ||
1089 !kvm_check_extension(s
, KVM_CAP_IRQCHIP
)) {
1093 ret
= kvm_vm_ioctl(s
, KVM_CREATE_IRQCHIP
);
1095 fprintf(stderr
, "Create kernel irqchip failed\n");
1099 s
->irqchip_inject_ioctl
= KVM_IRQ_LINE
;
1100 if (kvm_check_extension(s
, KVM_CAP_IRQ_INJECT_STATUS
)) {
1101 s
->irqchip_inject_ioctl
= KVM_IRQ_LINE_STATUS
;
1103 kvm_kernel_irqchip
= true;
1105 kvm_init_irq_routing(s
);
1112 static const char upgrade_note
[] =
1113 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1114 "(see http://sourceforge.net/projects/kvm).\n";
1116 const KVMCapabilityInfo
*missing_cap
;
1120 s
= g_malloc0(sizeof(KVMState
));
1123 * On systems where the kernel can support different base page
1124 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1125 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1126 * page size for the system though.
1128 assert(TARGET_PAGE_SIZE
<= getpagesize());
1130 #ifdef KVM_CAP_SET_GUEST_DEBUG
1131 QTAILQ_INIT(&s
->kvm_sw_breakpoints
);
1133 for (i
= 0; i
< ARRAY_SIZE(s
->slots
); i
++) {
1134 s
->slots
[i
].slot
= i
;
1137 s
->fd
= qemu_open("/dev/kvm", O_RDWR
);
1139 fprintf(stderr
, "Could not access KVM kernel module: %m\n");
1144 ret
= kvm_ioctl(s
, KVM_GET_API_VERSION
, 0);
1145 if (ret
< KVM_API_VERSION
) {
1149 fprintf(stderr
, "kvm version too old\n");
1153 if (ret
> KVM_API_VERSION
) {
1155 fprintf(stderr
, "kvm version not supported\n");
1159 s
->vmfd
= kvm_ioctl(s
, KVM_CREATE_VM
, 0);
1162 fprintf(stderr
, "Please add the 'switch_amode' kernel parameter to "
1163 "your host kernel command line\n");
1169 missing_cap
= kvm_check_extension_list(s
, kvm_required_capabilites
);
1172 kvm_check_extension_list(s
, kvm_arch_required_capabilities
);
1176 fprintf(stderr
, "kvm does not support %s\n%s",
1177 missing_cap
->name
, upgrade_note
);
1181 s
->coalesced_mmio
= kvm_check_extension(s
, KVM_CAP_COALESCED_MMIO
);
1183 s
->broken_set_mem_region
= 1;
1184 ret
= kvm_check_extension(s
, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS
);
1186 s
->broken_set_mem_region
= 0;
1189 #ifdef KVM_CAP_VCPU_EVENTS
1190 s
->vcpu_events
= kvm_check_extension(s
, KVM_CAP_VCPU_EVENTS
);
1193 s
->robust_singlestep
=
1194 kvm_check_extension(s
, KVM_CAP_X86_ROBUST_SINGLESTEP
);
1196 #ifdef KVM_CAP_DEBUGREGS
1197 s
->debugregs
= kvm_check_extension(s
, KVM_CAP_DEBUGREGS
);
1200 #ifdef KVM_CAP_XSAVE
1201 s
->xsave
= kvm_check_extension(s
, KVM_CAP_XSAVE
);
1205 s
->xcrs
= kvm_check_extension(s
, KVM_CAP_XCRS
);
1208 #ifdef KVM_CAP_PIT_STATE2
1209 s
->pit_state2
= kvm_check_extension(s
, KVM_CAP_PIT_STATE2
);
1212 ret
= kvm_arch_init(s
);
1217 ret
= kvm_irqchip_create(s
);
1223 memory_listener_register(&kvm_memory_listener
, NULL
);
1225 s
->many_ioeventfds
= kvm_check_many_ioeventfds();
1227 cpu_interrupt_handler
= kvm_handle_interrupt
;
1245 static void kvm_handle_io(uint16_t port
, void *data
, int direction
, int size
,
1249 uint8_t *ptr
= data
;
1251 for (i
= 0; i
< count
; i
++) {
1252 if (direction
== KVM_EXIT_IO_IN
) {
1255 stb_p(ptr
, cpu_inb(port
));
1258 stw_p(ptr
, cpu_inw(port
));
1261 stl_p(ptr
, cpu_inl(port
));
1267 cpu_outb(port
, ldub_p(ptr
));
1270 cpu_outw(port
, lduw_p(ptr
));
1273 cpu_outl(port
, ldl_p(ptr
));
1282 static int kvm_handle_internal_error(CPUArchState
*env
, struct kvm_run
*run
)
1284 fprintf(stderr
, "KVM internal error.");
1285 if (kvm_check_extension(kvm_state
, KVM_CAP_INTERNAL_ERROR_DATA
)) {
1288 fprintf(stderr
, " Suberror: %d\n", run
->internal
.suberror
);
1289 for (i
= 0; i
< run
->internal
.ndata
; ++i
) {
1290 fprintf(stderr
, "extra data[%d]: %"PRIx64
"\n",
1291 i
, (uint64_t)run
->internal
.data
[i
]);
1294 fprintf(stderr
, "\n");
1296 if (run
->internal
.suberror
== KVM_INTERNAL_ERROR_EMULATION
) {
1297 fprintf(stderr
, "emulation failure\n");
1298 if (!kvm_arch_stop_on_emulation_error(env
)) {
1299 cpu_dump_state(env
, stderr
, fprintf
, CPU_DUMP_CODE
);
1300 return EXCP_INTERRUPT
;
1303 /* FIXME: Should trigger a qmp message to let management know
1304 * something went wrong.
1309 void kvm_flush_coalesced_mmio_buffer(void)
1311 KVMState
*s
= kvm_state
;
1313 if (s
->coalesced_flush_in_progress
) {
1317 s
->coalesced_flush_in_progress
= true;
1319 if (s
->coalesced_mmio_ring
) {
1320 struct kvm_coalesced_mmio_ring
*ring
= s
->coalesced_mmio_ring
;
1321 while (ring
->first
!= ring
->last
) {
1322 struct kvm_coalesced_mmio
*ent
;
1324 ent
= &ring
->coalesced_mmio
[ring
->first
];
1326 cpu_physical_memory_write(ent
->phys_addr
, ent
->data
, ent
->len
);
1328 ring
->first
= (ring
->first
+ 1) % KVM_COALESCED_MMIO_MAX
;
1332 s
->coalesced_flush_in_progress
= false;
1335 static void do_kvm_cpu_synchronize_state(void *_env
)
1337 CPUArchState
*env
= _env
;
1339 if (!env
->kvm_vcpu_dirty
) {
1340 kvm_arch_get_registers(env
);
1341 env
->kvm_vcpu_dirty
= 1;
1345 void kvm_cpu_synchronize_state(CPUArchState
*env
)
1347 if (!env
->kvm_vcpu_dirty
) {
1348 run_on_cpu(env
, do_kvm_cpu_synchronize_state
, env
);
1352 void kvm_cpu_synchronize_post_reset(CPUArchState
*env
)
1354 kvm_arch_put_registers(env
, KVM_PUT_RESET_STATE
);
1355 env
->kvm_vcpu_dirty
= 0;
1358 void kvm_cpu_synchronize_post_init(CPUArchState
*env
)
1360 kvm_arch_put_registers(env
, KVM_PUT_FULL_STATE
);
1361 env
->kvm_vcpu_dirty
= 0;
1364 int kvm_cpu_exec(CPUArchState
*env
)
1366 struct kvm_run
*run
= env
->kvm_run
;
1369 DPRINTF("kvm_cpu_exec()\n");
1371 if (kvm_arch_process_async_events(env
)) {
1372 env
->exit_request
= 0;
1377 if (env
->kvm_vcpu_dirty
) {
1378 kvm_arch_put_registers(env
, KVM_PUT_RUNTIME_STATE
);
1379 env
->kvm_vcpu_dirty
= 0;
1382 kvm_arch_pre_run(env
, run
);
1383 if (env
->exit_request
) {
1384 DPRINTF("interrupt exit requested\n");
1386 * KVM requires us to reenter the kernel after IO exits to complete
1387 * instruction emulation. This self-signal will ensure that we
1390 qemu_cpu_kick_self();
1392 qemu_mutex_unlock_iothread();
1394 run_ret
= kvm_vcpu_ioctl(env
, KVM_RUN
, 0);
1396 qemu_mutex_lock_iothread();
1397 kvm_arch_post_run(env
, run
);
1399 kvm_flush_coalesced_mmio_buffer();
1402 if (run_ret
== -EINTR
|| run_ret
== -EAGAIN
) {
1403 DPRINTF("io window exit\n");
1404 ret
= EXCP_INTERRUPT
;
1407 fprintf(stderr
, "error: kvm run failed %s\n",
1408 strerror(-run_ret
));
1412 switch (run
->exit_reason
) {
1414 DPRINTF("handle_io\n");
1415 kvm_handle_io(run
->io
.port
,
1416 (uint8_t *)run
+ run
->io
.data_offset
,
1423 DPRINTF("handle_mmio\n");
1424 cpu_physical_memory_rw(run
->mmio
.phys_addr
,
1427 run
->mmio
.is_write
);
1430 case KVM_EXIT_IRQ_WINDOW_OPEN
:
1431 DPRINTF("irq_window_open\n");
1432 ret
= EXCP_INTERRUPT
;
1434 case KVM_EXIT_SHUTDOWN
:
1435 DPRINTF("shutdown\n");
1436 qemu_system_reset_request();
1437 ret
= EXCP_INTERRUPT
;
1439 case KVM_EXIT_UNKNOWN
:
1440 fprintf(stderr
, "KVM: unknown exit, hardware reason %" PRIx64
"\n",
1441 (uint64_t)run
->hw
.hardware_exit_reason
);
1444 case KVM_EXIT_INTERNAL_ERROR
:
1445 ret
= kvm_handle_internal_error(env
, run
);
1448 DPRINTF("kvm_arch_handle_exit\n");
1449 ret
= kvm_arch_handle_exit(env
, run
);
1455 cpu_dump_state(env
, stderr
, fprintf
, CPU_DUMP_CODE
);
1456 vm_stop(RUN_STATE_INTERNAL_ERROR
);
1459 env
->exit_request
= 0;
1463 int kvm_ioctl(KVMState
*s
, int type
, ...)
1470 arg
= va_arg(ap
, void *);
1473 ret
= ioctl(s
->fd
, type
, arg
);
1480 int kvm_vm_ioctl(KVMState
*s
, int type
, ...)
1487 arg
= va_arg(ap
, void *);
1490 ret
= ioctl(s
->vmfd
, type
, arg
);
1497 int kvm_vcpu_ioctl(CPUArchState
*env
, int type
, ...)
1504 arg
= va_arg(ap
, void *);
1507 ret
= ioctl(env
->kvm_fd
, type
, arg
);
1514 int kvm_has_sync_mmu(void)
1516 return kvm_check_extension(kvm_state
, KVM_CAP_SYNC_MMU
);
1519 int kvm_has_vcpu_events(void)
1521 return kvm_state
->vcpu_events
;
1524 int kvm_has_robust_singlestep(void)
1526 return kvm_state
->robust_singlestep
;
1529 int kvm_has_debugregs(void)
1531 return kvm_state
->debugregs
;
1534 int kvm_has_xsave(void)
1536 return kvm_state
->xsave
;
1539 int kvm_has_xcrs(void)
1541 return kvm_state
->xcrs
;
1544 int kvm_has_pit_state2(void)
1546 return kvm_state
->pit_state2
;
1549 int kvm_has_many_ioeventfds(void)
1551 if (!kvm_enabled()) {
1554 return kvm_state
->many_ioeventfds
;
1557 int kvm_has_gsi_routing(void)
1559 #ifdef KVM_CAP_IRQ_ROUTING
1560 return kvm_check_extension(kvm_state
, KVM_CAP_IRQ_ROUTING
);
1566 int kvm_allows_irq0_override(void)
1568 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
1571 void kvm_setup_guest_memory(void *start
, size_t size
)
1573 if (!kvm_has_sync_mmu()) {
1574 int ret
= qemu_madvise(start
, size
, QEMU_MADV_DONTFORK
);
1577 perror("qemu_madvise");
1579 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1585 #ifdef KVM_CAP_SET_GUEST_DEBUG
1586 struct kvm_sw_breakpoint
*kvm_find_sw_breakpoint(CPUArchState
*env
,
1589 struct kvm_sw_breakpoint
*bp
;
1591 QTAILQ_FOREACH(bp
, &env
->kvm_state
->kvm_sw_breakpoints
, entry
) {
1599 int kvm_sw_breakpoints_active(CPUArchState
*env
)
1601 return !QTAILQ_EMPTY(&env
->kvm_state
->kvm_sw_breakpoints
);
1604 struct kvm_set_guest_debug_data
{
1605 struct kvm_guest_debug dbg
;
1610 static void kvm_invoke_set_guest_debug(void *data
)
1612 struct kvm_set_guest_debug_data
*dbg_data
= data
;
1613 CPUArchState
*env
= dbg_data
->env
;
1615 dbg_data
->err
= kvm_vcpu_ioctl(env
, KVM_SET_GUEST_DEBUG
, &dbg_data
->dbg
);
1618 int kvm_update_guest_debug(CPUArchState
*env
, unsigned long reinject_trap
)
1620 struct kvm_set_guest_debug_data data
;
1622 data
.dbg
.control
= reinject_trap
;
1624 if (env
->singlestep_enabled
) {
1625 data
.dbg
.control
|= KVM_GUESTDBG_ENABLE
| KVM_GUESTDBG_SINGLESTEP
;
1627 kvm_arch_update_guest_debug(env
, &data
.dbg
);
1630 run_on_cpu(env
, kvm_invoke_set_guest_debug
, &data
);
1634 int kvm_insert_breakpoint(CPUArchState
*current_env
, target_ulong addr
,
1635 target_ulong len
, int type
)
1637 struct kvm_sw_breakpoint
*bp
;
1641 if (type
== GDB_BREAKPOINT_SW
) {
1642 bp
= kvm_find_sw_breakpoint(current_env
, addr
);
1648 bp
= g_malloc(sizeof(struct kvm_sw_breakpoint
));
1655 err
= kvm_arch_insert_sw_breakpoint(current_env
, bp
);
1661 QTAILQ_INSERT_HEAD(¤t_env
->kvm_state
->kvm_sw_breakpoints
,
1664 err
= kvm_arch_insert_hw_breakpoint(addr
, len
, type
);
1670 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
1671 err
= kvm_update_guest_debug(env
, 0);
1679 int kvm_remove_breakpoint(CPUArchState
*current_env
, target_ulong addr
,
1680 target_ulong len
, int type
)
1682 struct kvm_sw_breakpoint
*bp
;
1686 if (type
== GDB_BREAKPOINT_SW
) {
1687 bp
= kvm_find_sw_breakpoint(current_env
, addr
);
1692 if (bp
->use_count
> 1) {
1697 err
= kvm_arch_remove_sw_breakpoint(current_env
, bp
);
1702 QTAILQ_REMOVE(¤t_env
->kvm_state
->kvm_sw_breakpoints
, bp
, entry
);
1705 err
= kvm_arch_remove_hw_breakpoint(addr
, len
, type
);
1711 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
1712 err
= kvm_update_guest_debug(env
, 0);
1720 void kvm_remove_all_breakpoints(CPUArchState
*current_env
)
1722 struct kvm_sw_breakpoint
*bp
, *next
;
1723 KVMState
*s
= current_env
->kvm_state
;
1726 QTAILQ_FOREACH_SAFE(bp
, &s
->kvm_sw_breakpoints
, entry
, next
) {
1727 if (kvm_arch_remove_sw_breakpoint(current_env
, bp
) != 0) {
1728 /* Try harder to find a CPU that currently sees the breakpoint. */
1729 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
1730 if (kvm_arch_remove_sw_breakpoint(env
, bp
) == 0) {
1736 kvm_arch_remove_all_hw_breakpoints();
1738 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
1739 kvm_update_guest_debug(env
, 0);
1743 #else /* !KVM_CAP_SET_GUEST_DEBUG */
1745 int kvm_update_guest_debug(CPUArchState
*env
, unsigned long reinject_trap
)
1750 int kvm_insert_breakpoint(CPUArchState
*current_env
, target_ulong addr
,
1751 target_ulong len
, int type
)
1756 int kvm_remove_breakpoint(CPUArchState
*current_env
, target_ulong addr
,
1757 target_ulong len
, int type
)
1762 void kvm_remove_all_breakpoints(CPUArchState
*current_env
)
1765 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
1767 int kvm_set_signal_mask(CPUArchState
*env
, const sigset_t
*sigset
)
1769 struct kvm_signal_mask
*sigmask
;
1773 return kvm_vcpu_ioctl(env
, KVM_SET_SIGNAL_MASK
, NULL
);
1776 sigmask
= g_malloc(sizeof(*sigmask
) + sizeof(*sigset
));
1779 memcpy(sigmask
->sigset
, sigset
, sizeof(*sigset
));
1780 r
= kvm_vcpu_ioctl(env
, KVM_SET_SIGNAL_MASK
, sigmask
);
1786 int kvm_set_ioeventfd_mmio(int fd
, uint32_t addr
, uint32_t val
, bool assign
,
1790 struct kvm_ioeventfd iofd
;
1792 iofd
.datamatch
= val
;
1795 iofd
.flags
= KVM_IOEVENTFD_FLAG_DATAMATCH
;
1798 if (!kvm_enabled()) {
1803 iofd
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
1806 ret
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &iofd
);
1815 int kvm_set_ioeventfd_pio_word(int fd
, uint16_t addr
, uint16_t val
, bool assign
)
1817 struct kvm_ioeventfd kick
= {
1821 .flags
= KVM_IOEVENTFD_FLAG_DATAMATCH
| KVM_IOEVENTFD_FLAG_PIO
,
1825 if (!kvm_enabled()) {
1829 kick
.flags
|= KVM_IOEVENTFD_FLAG_DEASSIGN
;
1831 r
= kvm_vm_ioctl(kvm_state
, KVM_IOEVENTFD
, &kick
);
1838 int kvm_on_sigbus_vcpu(CPUArchState
*env
, int code
, void *addr
)
1840 return kvm_arch_on_sigbus_vcpu(env
, code
, addr
);
1843 int kvm_on_sigbus(int code
, void *addr
)
1845 return kvm_arch_on_sigbus(code
, addr
);