memory: provide defaults for MemoryListener operations
[qemu.git] / kvm-all.c
blobc69e01200461c7a87440f7a915bd171a9fc8f318
1 /*
2 * QEMU KVM support
4 * Copyright IBM, Corp. 2008
5 * Red Hat, Inc. 2008
7 * Authors:
8 * Anthony Liguori <aliguori@us.ibm.com>
9 * Glauber Costa <gcosta@redhat.com>
11 * This work is licensed under the terms of the GNU GPL, version 2 or later.
12 * See the COPYING file in the top-level directory.
16 #include <sys/types.h>
17 #include <sys/ioctl.h>
18 #include <sys/mman.h>
19 #include <stdarg.h>
21 #include <linux/kvm.h>
23 #include "qemu-common.h"
24 #include "qemu-barrier.h"
25 #include "qemu-option.h"
26 #include "qemu-config.h"
27 #include "sysemu.h"
28 #include "hw/hw.h"
29 #include "hw/msi.h"
30 #include "gdbstub.h"
31 #include "kvm.h"
32 #include "bswap.h"
33 #include "memory.h"
34 #include "exec-memory.h"
35 #include "event_notifier.h"
37 /* This check must be after config-host.h is included */
38 #ifdef CONFIG_EVENTFD
39 #include <sys/eventfd.h>
40 #endif
42 #ifdef CONFIG_VALGRIND_H
43 #include <valgrind/memcheck.h>
44 #endif
46 /* KVM uses PAGE_SIZE in its definition of COALESCED_MMIO_MAX */
47 #define PAGE_SIZE TARGET_PAGE_SIZE
49 //#define DEBUG_KVM
51 #ifdef DEBUG_KVM
52 #define DPRINTF(fmt, ...) \
53 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
54 #else
55 #define DPRINTF(fmt, ...) \
56 do { } while (0)
57 #endif
59 #define KVM_MSI_HASHTAB_SIZE 256
61 typedef struct KVMSlot
63 target_phys_addr_t start_addr;
64 ram_addr_t memory_size;
65 void *ram;
66 int slot;
67 int flags;
68 } KVMSlot;
70 typedef struct kvm_dirty_log KVMDirtyLog;
72 struct KVMState
74 KVMSlot slots[32];
75 int fd;
76 int vmfd;
77 int coalesced_mmio;
78 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
79 bool coalesced_flush_in_progress;
80 int broken_set_mem_region;
81 int migration_log;
82 int vcpu_events;
83 int robust_singlestep;
84 int debugregs;
85 #ifdef KVM_CAP_SET_GUEST_DEBUG
86 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
87 #endif
88 int pit_state2;
89 int xsave, xcrs;
90 int many_ioeventfds;
91 int intx_set_mask;
92 /* The man page (and posix) say ioctl numbers are signed int, but
93 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
94 * unsigned, and treating them as signed here can break things */
95 unsigned irq_set_ioctl;
96 #ifdef KVM_CAP_IRQ_ROUTING
97 struct kvm_irq_routing *irq_routes;
98 int nr_allocated_irq_routes;
99 uint32_t *used_gsi_bitmap;
100 unsigned int gsi_count;
101 QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
102 bool direct_msi;
103 #endif
106 KVMState *kvm_state;
107 bool kvm_kernel_irqchip;
108 bool kvm_async_interrupts_allowed;
109 bool kvm_irqfds_allowed;
110 bool kvm_msi_via_irqfd_allowed;
111 bool kvm_gsi_routing_allowed;
113 static const KVMCapabilityInfo kvm_required_capabilites[] = {
114 KVM_CAP_INFO(USER_MEMORY),
115 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
116 KVM_CAP_LAST_INFO
119 static KVMSlot *kvm_alloc_slot(KVMState *s)
121 int i;
123 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
124 if (s->slots[i].memory_size == 0) {
125 return &s->slots[i];
129 fprintf(stderr, "%s: no free slot available\n", __func__);
130 abort();
133 static KVMSlot *kvm_lookup_matching_slot(KVMState *s,
134 target_phys_addr_t start_addr,
135 target_phys_addr_t end_addr)
137 int i;
139 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
140 KVMSlot *mem = &s->slots[i];
142 if (start_addr == mem->start_addr &&
143 end_addr == mem->start_addr + mem->memory_size) {
144 return mem;
148 return NULL;
152 * Find overlapping slot with lowest start address
154 static KVMSlot *kvm_lookup_overlapping_slot(KVMState *s,
155 target_phys_addr_t start_addr,
156 target_phys_addr_t end_addr)
158 KVMSlot *found = NULL;
159 int i;
161 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
162 KVMSlot *mem = &s->slots[i];
164 if (mem->memory_size == 0 ||
165 (found && found->start_addr < mem->start_addr)) {
166 continue;
169 if (end_addr > mem->start_addr &&
170 start_addr < mem->start_addr + mem->memory_size) {
171 found = mem;
175 return found;
178 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
179 target_phys_addr_t *phys_addr)
181 int i;
183 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
184 KVMSlot *mem = &s->slots[i];
186 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
187 *phys_addr = mem->start_addr + (ram - mem->ram);
188 return 1;
192 return 0;
195 static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)
197 struct kvm_userspace_memory_region mem;
199 mem.slot = slot->slot;
200 mem.guest_phys_addr = slot->start_addr;
201 mem.memory_size = slot->memory_size;
202 mem.userspace_addr = (unsigned long)slot->ram;
203 mem.flags = slot->flags;
204 if (s->migration_log) {
205 mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;
207 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
210 static void kvm_reset_vcpu(void *opaque)
212 CPUArchState *env = opaque;
214 kvm_arch_reset_vcpu(env);
217 int kvm_init_vcpu(CPUArchState *env)
219 KVMState *s = kvm_state;
220 long mmap_size;
221 int ret;
223 DPRINTF("kvm_init_vcpu\n");
225 ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, env->cpu_index);
226 if (ret < 0) {
227 DPRINTF("kvm_create_vcpu failed\n");
228 goto err;
231 env->kvm_fd = ret;
232 env->kvm_state = s;
233 env->kvm_vcpu_dirty = 1;
235 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
236 if (mmap_size < 0) {
237 ret = mmap_size;
238 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
239 goto err;
242 env->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
243 env->kvm_fd, 0);
244 if (env->kvm_run == MAP_FAILED) {
245 ret = -errno;
246 DPRINTF("mmap'ing vcpu state failed\n");
247 goto err;
250 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
251 s->coalesced_mmio_ring =
252 (void *)env->kvm_run + s->coalesced_mmio * PAGE_SIZE;
255 ret = kvm_arch_init_vcpu(env);
256 if (ret == 0) {
257 qemu_register_reset(kvm_reset_vcpu, env);
258 kvm_arch_reset_vcpu(env);
260 err:
261 return ret;
265 * dirty pages logging control
268 static int kvm_mem_flags(KVMState *s, bool log_dirty)
270 return log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
273 static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
275 KVMState *s = kvm_state;
276 int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
277 int old_flags;
279 old_flags = mem->flags;
281 flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty);
282 mem->flags = flags;
284 /* If nothing changed effectively, no need to issue ioctl */
285 if (s->migration_log) {
286 flags |= KVM_MEM_LOG_DIRTY_PAGES;
289 if (flags == old_flags) {
290 return 0;
293 return kvm_set_user_memory_region(s, mem);
296 static int kvm_dirty_pages_log_change(target_phys_addr_t phys_addr,
297 ram_addr_t size, bool log_dirty)
299 KVMState *s = kvm_state;
300 KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
302 if (mem == NULL) {
303 fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
304 TARGET_FMT_plx "\n", __func__, phys_addr,
305 (target_phys_addr_t)(phys_addr + size - 1));
306 return -EINVAL;
308 return kvm_slot_dirty_pages_log_change(mem, log_dirty);
311 static void kvm_log_start(MemoryListener *listener,
312 MemoryRegionSection *section)
314 int r;
316 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
317 section->size, true);
318 if (r < 0) {
319 abort();
323 static void kvm_log_stop(MemoryListener *listener,
324 MemoryRegionSection *section)
326 int r;
328 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
329 section->size, false);
330 if (r < 0) {
331 abort();
335 static int kvm_set_migration_log(int enable)
337 KVMState *s = kvm_state;
338 KVMSlot *mem;
339 int i, err;
341 s->migration_log = enable;
343 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
344 mem = &s->slots[i];
346 if (!mem->memory_size) {
347 continue;
349 if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
350 continue;
352 err = kvm_set_user_memory_region(s, mem);
353 if (err) {
354 return err;
357 return 0;
360 /* get kvm's dirty pages bitmap and update qemu's */
361 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
362 unsigned long *bitmap)
364 unsigned int i, j;
365 unsigned long page_number, c;
366 target_phys_addr_t addr, addr1;
367 unsigned int len = ((section->size / TARGET_PAGE_SIZE) + HOST_LONG_BITS - 1) / HOST_LONG_BITS;
368 unsigned long hpratio = getpagesize() / TARGET_PAGE_SIZE;
371 * bitmap-traveling is faster than memory-traveling (for addr...)
372 * especially when most of the memory is not dirty.
374 for (i = 0; i < len; i++) {
375 if (bitmap[i] != 0) {
376 c = leul_to_cpu(bitmap[i]);
377 do {
378 j = ffsl(c) - 1;
379 c &= ~(1ul << j);
380 page_number = (i * HOST_LONG_BITS + j) * hpratio;
381 addr1 = page_number * TARGET_PAGE_SIZE;
382 addr = section->offset_within_region + addr1;
383 memory_region_set_dirty(section->mr, addr,
384 TARGET_PAGE_SIZE * hpratio);
385 } while (c != 0);
388 return 0;
391 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
394 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
395 * This function updates qemu's dirty bitmap using
396 * memory_region_set_dirty(). This means all bits are set
397 * to dirty.
399 * @start_add: start of logged region.
400 * @end_addr: end of logged region.
402 static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)
404 KVMState *s = kvm_state;
405 unsigned long size, allocated_size = 0;
406 KVMDirtyLog d;
407 KVMSlot *mem;
408 int ret = 0;
409 target_phys_addr_t start_addr = section->offset_within_address_space;
410 target_phys_addr_t end_addr = start_addr + section->size;
412 d.dirty_bitmap = NULL;
413 while (start_addr < end_addr) {
414 mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
415 if (mem == NULL) {
416 break;
419 /* XXX bad kernel interface alert
420 * For dirty bitmap, kernel allocates array of size aligned to
421 * bits-per-long. But for case when the kernel is 64bits and
422 * the userspace is 32bits, userspace can't align to the same
423 * bits-per-long, since sizeof(long) is different between kernel
424 * and user space. This way, userspace will provide buffer which
425 * may be 4 bytes less than the kernel will use, resulting in
426 * userspace memory corruption (which is not detectable by valgrind
427 * too, in most cases).
428 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
429 * a hope that sizeof(long) wont become >8 any time soon.
431 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
432 /*HOST_LONG_BITS*/ 64) / 8;
433 if (!d.dirty_bitmap) {
434 d.dirty_bitmap = g_malloc(size);
435 } else if (size > allocated_size) {
436 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
438 allocated_size = size;
439 memset(d.dirty_bitmap, 0, allocated_size);
441 d.slot = mem->slot;
443 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
444 DPRINTF("ioctl failed %d\n", errno);
445 ret = -1;
446 break;
449 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
450 start_addr = mem->start_addr + mem->memory_size;
452 g_free(d.dirty_bitmap);
454 return ret;
457 int kvm_coalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
459 int ret = -ENOSYS;
460 KVMState *s = kvm_state;
462 if (s->coalesced_mmio) {
463 struct kvm_coalesced_mmio_zone zone;
465 zone.addr = start;
466 zone.size = size;
467 zone.pad = 0;
469 ret = kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
472 return ret;
475 int kvm_uncoalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
477 int ret = -ENOSYS;
478 KVMState *s = kvm_state;
480 if (s->coalesced_mmio) {
481 struct kvm_coalesced_mmio_zone zone;
483 zone.addr = start;
484 zone.size = size;
485 zone.pad = 0;
487 ret = kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
490 return ret;
493 int kvm_check_extension(KVMState *s, unsigned int extension)
495 int ret;
497 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
498 if (ret < 0) {
499 ret = 0;
502 return ret;
505 static int kvm_check_many_ioeventfds(void)
507 /* Userspace can use ioeventfd for io notification. This requires a host
508 * that supports eventfd(2) and an I/O thread; since eventfd does not
509 * support SIGIO it cannot interrupt the vcpu.
511 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
512 * can avoid creating too many ioeventfds.
514 #if defined(CONFIG_EVENTFD)
515 int ioeventfds[7];
516 int i, ret = 0;
517 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
518 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
519 if (ioeventfds[i] < 0) {
520 break;
522 ret = kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, true);
523 if (ret < 0) {
524 close(ioeventfds[i]);
525 break;
529 /* Decide whether many devices are supported or not */
530 ret = i == ARRAY_SIZE(ioeventfds);
532 while (i-- > 0) {
533 kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, false);
534 close(ioeventfds[i]);
536 return ret;
537 #else
538 return 0;
539 #endif
542 static const KVMCapabilityInfo *
543 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
545 while (list->name) {
546 if (!kvm_check_extension(s, list->value)) {
547 return list;
549 list++;
551 return NULL;
554 static void kvm_set_phys_mem(MemoryRegionSection *section, bool add)
556 KVMState *s = kvm_state;
557 KVMSlot *mem, old;
558 int err;
559 MemoryRegion *mr = section->mr;
560 bool log_dirty = memory_region_is_logging(mr);
561 target_phys_addr_t start_addr = section->offset_within_address_space;
562 ram_addr_t size = section->size;
563 void *ram = NULL;
564 unsigned delta;
566 /* kvm works in page size chunks, but the function may be called
567 with sub-page size and unaligned start address. */
568 delta = TARGET_PAGE_ALIGN(size) - size;
569 if (delta > size) {
570 return;
572 start_addr += delta;
573 size -= delta;
574 size &= TARGET_PAGE_MASK;
575 if (!size || (start_addr & ~TARGET_PAGE_MASK)) {
576 return;
579 if (!memory_region_is_ram(mr)) {
580 return;
583 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
585 while (1) {
586 mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
587 if (!mem) {
588 break;
591 if (add && start_addr >= mem->start_addr &&
592 (start_addr + size <= mem->start_addr + mem->memory_size) &&
593 (ram - start_addr == mem->ram - mem->start_addr)) {
594 /* The new slot fits into the existing one and comes with
595 * identical parameters - update flags and done. */
596 kvm_slot_dirty_pages_log_change(mem, log_dirty);
597 return;
600 old = *mem;
602 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
603 kvm_physical_sync_dirty_bitmap(section);
606 /* unregister the overlapping slot */
607 mem->memory_size = 0;
608 err = kvm_set_user_memory_region(s, mem);
609 if (err) {
610 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
611 __func__, strerror(-err));
612 abort();
615 /* Workaround for older KVM versions: we can't join slots, even not by
616 * unregistering the previous ones and then registering the larger
617 * slot. We have to maintain the existing fragmentation. Sigh.
619 * This workaround assumes that the new slot starts at the same
620 * address as the first existing one. If not or if some overlapping
621 * slot comes around later, we will fail (not seen in practice so far)
622 * - and actually require a recent KVM version. */
623 if (s->broken_set_mem_region &&
624 old.start_addr == start_addr && old.memory_size < size && add) {
625 mem = kvm_alloc_slot(s);
626 mem->memory_size = old.memory_size;
627 mem->start_addr = old.start_addr;
628 mem->ram = old.ram;
629 mem->flags = kvm_mem_flags(s, log_dirty);
631 err = kvm_set_user_memory_region(s, mem);
632 if (err) {
633 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
634 strerror(-err));
635 abort();
638 start_addr += old.memory_size;
639 ram += old.memory_size;
640 size -= old.memory_size;
641 continue;
644 /* register prefix slot */
645 if (old.start_addr < start_addr) {
646 mem = kvm_alloc_slot(s);
647 mem->memory_size = start_addr - old.start_addr;
648 mem->start_addr = old.start_addr;
649 mem->ram = old.ram;
650 mem->flags = kvm_mem_flags(s, log_dirty);
652 err = kvm_set_user_memory_region(s, mem);
653 if (err) {
654 fprintf(stderr, "%s: error registering prefix slot: %s\n",
655 __func__, strerror(-err));
656 #ifdef TARGET_PPC
657 fprintf(stderr, "%s: This is probably because your kernel's " \
658 "PAGE_SIZE is too big. Please try to use 4k " \
659 "PAGE_SIZE!\n", __func__);
660 #endif
661 abort();
665 /* register suffix slot */
666 if (old.start_addr + old.memory_size > start_addr + size) {
667 ram_addr_t size_delta;
669 mem = kvm_alloc_slot(s);
670 mem->start_addr = start_addr + size;
671 size_delta = mem->start_addr - old.start_addr;
672 mem->memory_size = old.memory_size - size_delta;
673 mem->ram = old.ram + size_delta;
674 mem->flags = kvm_mem_flags(s, log_dirty);
676 err = kvm_set_user_memory_region(s, mem);
677 if (err) {
678 fprintf(stderr, "%s: error registering suffix slot: %s\n",
679 __func__, strerror(-err));
680 abort();
685 /* in case the KVM bug workaround already "consumed" the new slot */
686 if (!size) {
687 return;
689 if (!add) {
690 return;
692 mem = kvm_alloc_slot(s);
693 mem->memory_size = size;
694 mem->start_addr = start_addr;
695 mem->ram = ram;
696 mem->flags = kvm_mem_flags(s, log_dirty);
698 err = kvm_set_user_memory_region(s, mem);
699 if (err) {
700 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
701 strerror(-err));
702 abort();
706 static void kvm_begin(MemoryListener *listener)
710 static void kvm_commit(MemoryListener *listener)
714 static void kvm_region_add(MemoryListener *listener,
715 MemoryRegionSection *section)
717 kvm_set_phys_mem(section, true);
720 static void kvm_region_del(MemoryListener *listener,
721 MemoryRegionSection *section)
723 kvm_set_phys_mem(section, false);
726 static void kvm_region_nop(MemoryListener *listener,
727 MemoryRegionSection *section)
731 static void kvm_log_sync(MemoryListener *listener,
732 MemoryRegionSection *section)
734 int r;
736 r = kvm_physical_sync_dirty_bitmap(section);
737 if (r < 0) {
738 abort();
742 static void kvm_log_global_start(struct MemoryListener *listener)
744 int r;
746 r = kvm_set_migration_log(1);
747 assert(r >= 0);
750 static void kvm_log_global_stop(struct MemoryListener *listener)
752 int r;
754 r = kvm_set_migration_log(0);
755 assert(r >= 0);
758 static void kvm_log_nop(struct MemoryListener *listener)
762 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
763 MemoryRegionSection *section,
764 bool match_data, uint64_t data,
765 EventNotifier *e)
767 int fd = event_notifier_get_fd(e);
768 int r;
770 assert(match_data && section->size <= 8);
772 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
773 data, true, section->size);
774 if (r < 0) {
775 abort();
779 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
780 MemoryRegionSection *section,
781 bool match_data, uint64_t data,
782 EventNotifier *e)
784 int fd = event_notifier_get_fd(e);
785 int r;
787 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
788 data, false, section->size);
789 if (r < 0) {
790 abort();
794 static void kvm_io_ioeventfd_add(MemoryListener *listener,
795 MemoryRegionSection *section,
796 bool match_data, uint64_t data,
797 EventNotifier *e)
799 int fd = event_notifier_get_fd(e);
800 int r;
802 assert(match_data && section->size == 2);
804 r = kvm_set_ioeventfd_pio_word(fd, section->offset_within_address_space,
805 data, true);
806 if (r < 0) {
807 abort();
811 static void kvm_io_ioeventfd_del(MemoryListener *listener,
812 MemoryRegionSection *section,
813 bool match_data, uint64_t data,
814 EventNotifier *e)
817 int fd = event_notifier_get_fd(e);
818 int r;
820 r = kvm_set_ioeventfd_pio_word(fd, section->offset_within_address_space,
821 data, false);
822 if (r < 0) {
823 abort();
827 static MemoryListener kvm_memory_listener = {
828 .begin = kvm_begin,
829 .commit = kvm_commit,
830 .region_add = kvm_region_add,
831 .region_del = kvm_region_del,
832 .region_nop = kvm_region_nop,
833 .log_start = kvm_log_start,
834 .log_stop = kvm_log_stop,
835 .log_sync = kvm_log_sync,
836 .log_global_start = kvm_log_global_start,
837 .log_global_stop = kvm_log_global_stop,
838 .eventfd_add = kvm_mem_ioeventfd_add,
839 .eventfd_del = kvm_mem_ioeventfd_del,
840 .priority = 10,
843 static MemoryListener kvm_io_listener = {
844 .begin = kvm_begin,
845 .commit = kvm_commit,
846 .region_add = kvm_region_nop,
847 .region_del = kvm_region_nop,
848 .region_nop = kvm_region_nop,
849 .log_start = kvm_region_nop,
850 .log_stop = kvm_region_nop,
851 .log_sync = kvm_region_nop,
852 .log_global_start = kvm_log_nop,
853 .log_global_stop = kvm_log_nop,
854 .eventfd_add = kvm_io_ioeventfd_add,
855 .eventfd_del = kvm_io_ioeventfd_del,
856 .priority = 10,
859 static void kvm_handle_interrupt(CPUArchState *env, int mask)
861 env->interrupt_request |= mask;
863 if (!qemu_cpu_is_self(env)) {
864 qemu_cpu_kick(env);
868 int kvm_set_irq(KVMState *s, int irq, int level)
870 struct kvm_irq_level event;
871 int ret;
873 assert(kvm_async_interrupts_enabled());
875 event.level = level;
876 event.irq = irq;
877 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
878 if (ret < 0) {
879 perror("kvm_set_irq");
880 abort();
883 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
886 #ifdef KVM_CAP_IRQ_ROUTING
887 typedef struct KVMMSIRoute {
888 struct kvm_irq_routing_entry kroute;
889 QTAILQ_ENTRY(KVMMSIRoute) entry;
890 } KVMMSIRoute;
892 static void set_gsi(KVMState *s, unsigned int gsi)
894 s->used_gsi_bitmap[gsi / 32] |= 1U << (gsi % 32);
897 static void clear_gsi(KVMState *s, unsigned int gsi)
899 s->used_gsi_bitmap[gsi / 32] &= ~(1U << (gsi % 32));
902 static void kvm_init_irq_routing(KVMState *s)
904 int gsi_count, i;
906 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING);
907 if (gsi_count > 0) {
908 unsigned int gsi_bits, i;
910 /* Round up so we can search ints using ffs */
911 gsi_bits = ALIGN(gsi_count, 32);
912 s->used_gsi_bitmap = g_malloc0(gsi_bits / 8);
913 s->gsi_count = gsi_count;
915 /* Mark any over-allocated bits as already in use */
916 for (i = gsi_count; i < gsi_bits; i++) {
917 set_gsi(s, i);
921 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
922 s->nr_allocated_irq_routes = 0;
924 if (!s->direct_msi) {
925 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
926 QTAILQ_INIT(&s->msi_hashtab[i]);
930 kvm_arch_init_irq_routing(s);
933 static void kvm_irqchip_commit_routes(KVMState *s)
935 int ret;
937 s->irq_routes->flags = 0;
938 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
939 assert(ret == 0);
942 static void kvm_add_routing_entry(KVMState *s,
943 struct kvm_irq_routing_entry *entry)
945 struct kvm_irq_routing_entry *new;
946 int n, size;
948 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
949 n = s->nr_allocated_irq_routes * 2;
950 if (n < 64) {
951 n = 64;
953 size = sizeof(struct kvm_irq_routing);
954 size += n * sizeof(*new);
955 s->irq_routes = g_realloc(s->irq_routes, size);
956 s->nr_allocated_irq_routes = n;
958 n = s->irq_routes->nr++;
959 new = &s->irq_routes->entries[n];
960 memset(new, 0, sizeof(*new));
961 new->gsi = entry->gsi;
962 new->type = entry->type;
963 new->flags = entry->flags;
964 new->u = entry->u;
966 set_gsi(s, entry->gsi);
968 kvm_irqchip_commit_routes(s);
971 static int kvm_update_routing_entry(KVMState *s,
972 struct kvm_irq_routing_entry *new_entry)
974 struct kvm_irq_routing_entry *entry;
975 int n;
977 for (n = 0; n < s->irq_routes->nr; n++) {
978 entry = &s->irq_routes->entries[n];
979 if (entry->gsi != new_entry->gsi) {
980 continue;
983 entry->type = new_entry->type;
984 entry->flags = new_entry->flags;
985 entry->u = new_entry->u;
987 kvm_irqchip_commit_routes(s);
989 return 0;
992 return -ESRCH;
995 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
997 struct kvm_irq_routing_entry e;
999 assert(pin < s->gsi_count);
1001 e.gsi = irq;
1002 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1003 e.flags = 0;
1004 e.u.irqchip.irqchip = irqchip;
1005 e.u.irqchip.pin = pin;
1006 kvm_add_routing_entry(s, &e);
1009 void kvm_irqchip_release_virq(KVMState *s, int virq)
1011 struct kvm_irq_routing_entry *e;
1012 int i;
1014 for (i = 0; i < s->irq_routes->nr; i++) {
1015 e = &s->irq_routes->entries[i];
1016 if (e->gsi == virq) {
1017 s->irq_routes->nr--;
1018 *e = s->irq_routes->entries[s->irq_routes->nr];
1021 clear_gsi(s, virq);
1023 kvm_irqchip_commit_routes(s);
1026 static unsigned int kvm_hash_msi(uint32_t data)
1028 /* This is optimized for IA32 MSI layout. However, no other arch shall
1029 * repeat the mistake of not providing a direct MSI injection API. */
1030 return data & 0xff;
1033 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1035 KVMMSIRoute *route, *next;
1036 unsigned int hash;
1038 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1039 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1040 kvm_irqchip_release_virq(s, route->kroute.gsi);
1041 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1042 g_free(route);
1047 static int kvm_irqchip_get_virq(KVMState *s)
1049 uint32_t *word = s->used_gsi_bitmap;
1050 int max_words = ALIGN(s->gsi_count, 32) / 32;
1051 int i, bit;
1052 bool retry = true;
1054 again:
1055 /* Return the lowest unused GSI in the bitmap */
1056 for (i = 0; i < max_words; i++) {
1057 bit = ffs(~word[i]);
1058 if (!bit) {
1059 continue;
1062 return bit - 1 + i * 32;
1064 if (!s->direct_msi && retry) {
1065 retry = false;
1066 kvm_flush_dynamic_msi_routes(s);
1067 goto again;
1069 return -ENOSPC;
1073 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1075 unsigned int hash = kvm_hash_msi(msg.data);
1076 KVMMSIRoute *route;
1078 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1079 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1080 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1081 route->kroute.u.msi.data == msg.data) {
1082 return route;
1085 return NULL;
1088 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1090 struct kvm_msi msi;
1091 KVMMSIRoute *route;
1093 if (s->direct_msi) {
1094 msi.address_lo = (uint32_t)msg.address;
1095 msi.address_hi = msg.address >> 32;
1096 msi.data = msg.data;
1097 msi.flags = 0;
1098 memset(msi.pad, 0, sizeof(msi.pad));
1100 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1103 route = kvm_lookup_msi_route(s, msg);
1104 if (!route) {
1105 int virq;
1107 virq = kvm_irqchip_get_virq(s);
1108 if (virq < 0) {
1109 return virq;
1112 route = g_malloc(sizeof(KVMMSIRoute));
1113 route->kroute.gsi = virq;
1114 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1115 route->kroute.flags = 0;
1116 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1117 route->kroute.u.msi.address_hi = msg.address >> 32;
1118 route->kroute.u.msi.data = msg.data;
1120 kvm_add_routing_entry(s, &route->kroute);
1122 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1123 entry);
1126 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1128 return kvm_set_irq(s, route->kroute.gsi, 1);
1131 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1133 struct kvm_irq_routing_entry kroute;
1134 int virq;
1136 if (!kvm_gsi_routing_enabled()) {
1137 return -ENOSYS;
1140 virq = kvm_irqchip_get_virq(s);
1141 if (virq < 0) {
1142 return virq;
1145 kroute.gsi = virq;
1146 kroute.type = KVM_IRQ_ROUTING_MSI;
1147 kroute.flags = 0;
1148 kroute.u.msi.address_lo = (uint32_t)msg.address;
1149 kroute.u.msi.address_hi = msg.address >> 32;
1150 kroute.u.msi.data = msg.data;
1152 kvm_add_routing_entry(s, &kroute);
1154 return virq;
1157 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1159 struct kvm_irq_routing_entry kroute;
1161 if (!kvm_irqchip_in_kernel()) {
1162 return -ENOSYS;
1165 kroute.gsi = virq;
1166 kroute.type = KVM_IRQ_ROUTING_MSI;
1167 kroute.flags = 0;
1168 kroute.u.msi.address_lo = (uint32_t)msg.address;
1169 kroute.u.msi.address_hi = msg.address >> 32;
1170 kroute.u.msi.data = msg.data;
1172 return kvm_update_routing_entry(s, &kroute);
1175 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1177 struct kvm_irqfd irqfd = {
1178 .fd = fd,
1179 .gsi = virq,
1180 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1183 if (!kvm_irqfds_enabled()) {
1184 return -ENOSYS;
1187 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1190 #else /* !KVM_CAP_IRQ_ROUTING */
1192 static void kvm_init_irq_routing(KVMState *s)
1196 void kvm_irqchip_release_virq(KVMState *s, int virq)
1200 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1202 abort();
1205 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1207 return -ENOSYS;
1210 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1212 abort();
1214 #endif /* !KVM_CAP_IRQ_ROUTING */
1216 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n, int virq)
1218 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), virq, true);
1221 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n, int virq)
1223 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), virq, false);
1226 static int kvm_irqchip_create(KVMState *s)
1228 QemuOptsList *list = qemu_find_opts("machine");
1229 int ret;
1231 if (QTAILQ_EMPTY(&list->head) ||
1232 !qemu_opt_get_bool(QTAILQ_FIRST(&list->head),
1233 "kernel_irqchip", true) ||
1234 !kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
1235 return 0;
1238 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1239 if (ret < 0) {
1240 fprintf(stderr, "Create kernel irqchip failed\n");
1241 return ret;
1244 kvm_kernel_irqchip = true;
1245 /* If we have an in-kernel IRQ chip then we must have asynchronous
1246 * interrupt delivery (though the reverse is not necessarily true)
1248 kvm_async_interrupts_allowed = true;
1250 kvm_init_irq_routing(s);
1252 return 0;
1255 static int kvm_max_vcpus(KVMState *s)
1257 int ret;
1259 /* Find number of supported CPUs using the recommended
1260 * procedure from the kernel API documentation to cope with
1261 * older kernels that may be missing capabilities.
1263 ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1264 if (ret) {
1265 return ret;
1267 ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
1268 if (ret) {
1269 return ret;
1272 return 4;
1275 int kvm_init(void)
1277 static const char upgrade_note[] =
1278 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1279 "(see http://sourceforge.net/projects/kvm).\n";
1280 KVMState *s;
1281 const KVMCapabilityInfo *missing_cap;
1282 int ret;
1283 int i;
1284 int max_vcpus;
1286 s = g_malloc0(sizeof(KVMState));
1289 * On systems where the kernel can support different base page
1290 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1291 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1292 * page size for the system though.
1294 assert(TARGET_PAGE_SIZE <= getpagesize());
1296 #ifdef KVM_CAP_SET_GUEST_DEBUG
1297 QTAILQ_INIT(&s->kvm_sw_breakpoints);
1298 #endif
1299 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
1300 s->slots[i].slot = i;
1302 s->vmfd = -1;
1303 s->fd = qemu_open("/dev/kvm", O_RDWR);
1304 if (s->fd == -1) {
1305 fprintf(stderr, "Could not access KVM kernel module: %m\n");
1306 ret = -errno;
1307 goto err;
1310 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1311 if (ret < KVM_API_VERSION) {
1312 if (ret > 0) {
1313 ret = -EINVAL;
1315 fprintf(stderr, "kvm version too old\n");
1316 goto err;
1319 if (ret > KVM_API_VERSION) {
1320 ret = -EINVAL;
1321 fprintf(stderr, "kvm version not supported\n");
1322 goto err;
1325 max_vcpus = kvm_max_vcpus(s);
1326 if (smp_cpus > max_vcpus) {
1327 ret = -EINVAL;
1328 fprintf(stderr, "Number of SMP cpus requested (%d) exceeds max cpus "
1329 "supported by KVM (%d)\n", smp_cpus, max_vcpus);
1330 goto err;
1333 s->vmfd = kvm_ioctl(s, KVM_CREATE_VM, 0);
1334 if (s->vmfd < 0) {
1335 #ifdef TARGET_S390X
1336 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
1337 "your host kernel command line\n");
1338 #endif
1339 ret = s->vmfd;
1340 goto err;
1343 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1344 if (!missing_cap) {
1345 missing_cap =
1346 kvm_check_extension_list(s, kvm_arch_required_capabilities);
1348 if (missing_cap) {
1349 ret = -EINVAL;
1350 fprintf(stderr, "kvm does not support %s\n%s",
1351 missing_cap->name, upgrade_note);
1352 goto err;
1355 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1357 s->broken_set_mem_region = 1;
1358 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
1359 if (ret > 0) {
1360 s->broken_set_mem_region = 0;
1363 #ifdef KVM_CAP_VCPU_EVENTS
1364 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1365 #endif
1367 s->robust_singlestep =
1368 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1370 #ifdef KVM_CAP_DEBUGREGS
1371 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1372 #endif
1374 #ifdef KVM_CAP_XSAVE
1375 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1376 #endif
1378 #ifdef KVM_CAP_XCRS
1379 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1380 #endif
1382 #ifdef KVM_CAP_PIT_STATE2
1383 s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1384 #endif
1386 #ifdef KVM_CAP_IRQ_ROUTING
1387 s->direct_msi = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1388 #endif
1390 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1392 s->irq_set_ioctl = KVM_IRQ_LINE;
1393 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1394 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1397 ret = kvm_arch_init(s);
1398 if (ret < 0) {
1399 goto err;
1402 ret = kvm_irqchip_create(s);
1403 if (ret < 0) {
1404 goto err;
1407 kvm_state = s;
1408 memory_listener_register(&kvm_memory_listener, get_system_memory());
1409 memory_listener_register(&kvm_io_listener, get_system_io());
1411 s->many_ioeventfds = kvm_check_many_ioeventfds();
1413 cpu_interrupt_handler = kvm_handle_interrupt;
1415 return 0;
1417 err:
1418 if (s->vmfd >= 0) {
1419 close(s->vmfd);
1421 if (s->fd != -1) {
1422 close(s->fd);
1424 g_free(s);
1426 return ret;
1429 static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
1430 uint32_t count)
1432 int i;
1433 uint8_t *ptr = data;
1435 for (i = 0; i < count; i++) {
1436 if (direction == KVM_EXIT_IO_IN) {
1437 switch (size) {
1438 case 1:
1439 stb_p(ptr, cpu_inb(port));
1440 break;
1441 case 2:
1442 stw_p(ptr, cpu_inw(port));
1443 break;
1444 case 4:
1445 stl_p(ptr, cpu_inl(port));
1446 break;
1448 } else {
1449 switch (size) {
1450 case 1:
1451 cpu_outb(port, ldub_p(ptr));
1452 break;
1453 case 2:
1454 cpu_outw(port, lduw_p(ptr));
1455 break;
1456 case 4:
1457 cpu_outl(port, ldl_p(ptr));
1458 break;
1462 ptr += size;
1466 static int kvm_handle_internal_error(CPUArchState *env, struct kvm_run *run)
1468 fprintf(stderr, "KVM internal error.");
1469 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1470 int i;
1472 fprintf(stderr, " Suberror: %d\n", run->internal.suberror);
1473 for (i = 0; i < run->internal.ndata; ++i) {
1474 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1475 i, (uint64_t)run->internal.data[i]);
1477 } else {
1478 fprintf(stderr, "\n");
1480 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1481 fprintf(stderr, "emulation failure\n");
1482 if (!kvm_arch_stop_on_emulation_error(env)) {
1483 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1484 return EXCP_INTERRUPT;
1487 /* FIXME: Should trigger a qmp message to let management know
1488 * something went wrong.
1490 return -1;
1493 void kvm_flush_coalesced_mmio_buffer(void)
1495 KVMState *s = kvm_state;
1497 if (s->coalesced_flush_in_progress) {
1498 return;
1501 s->coalesced_flush_in_progress = true;
1503 if (s->coalesced_mmio_ring) {
1504 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1505 while (ring->first != ring->last) {
1506 struct kvm_coalesced_mmio *ent;
1508 ent = &ring->coalesced_mmio[ring->first];
1510 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1511 smp_wmb();
1512 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1516 s->coalesced_flush_in_progress = false;
1519 static void do_kvm_cpu_synchronize_state(void *_env)
1521 CPUArchState *env = _env;
1523 if (!env->kvm_vcpu_dirty) {
1524 kvm_arch_get_registers(env);
1525 env->kvm_vcpu_dirty = 1;
1529 void kvm_cpu_synchronize_state(CPUArchState *env)
1531 if (!env->kvm_vcpu_dirty) {
1532 run_on_cpu(env, do_kvm_cpu_synchronize_state, env);
1536 void kvm_cpu_synchronize_post_reset(CPUArchState *env)
1538 kvm_arch_put_registers(env, KVM_PUT_RESET_STATE);
1539 env->kvm_vcpu_dirty = 0;
1542 void kvm_cpu_synchronize_post_init(CPUArchState *env)
1544 kvm_arch_put_registers(env, KVM_PUT_FULL_STATE);
1545 env->kvm_vcpu_dirty = 0;
1548 int kvm_cpu_exec(CPUArchState *env)
1550 struct kvm_run *run = env->kvm_run;
1551 int ret, run_ret;
1553 DPRINTF("kvm_cpu_exec()\n");
1555 if (kvm_arch_process_async_events(env)) {
1556 env->exit_request = 0;
1557 return EXCP_HLT;
1560 do {
1561 if (env->kvm_vcpu_dirty) {
1562 kvm_arch_put_registers(env, KVM_PUT_RUNTIME_STATE);
1563 env->kvm_vcpu_dirty = 0;
1566 kvm_arch_pre_run(env, run);
1567 if (env->exit_request) {
1568 DPRINTF("interrupt exit requested\n");
1570 * KVM requires us to reenter the kernel after IO exits to complete
1571 * instruction emulation. This self-signal will ensure that we
1572 * leave ASAP again.
1574 qemu_cpu_kick_self();
1576 qemu_mutex_unlock_iothread();
1578 run_ret = kvm_vcpu_ioctl(env, KVM_RUN, 0);
1580 qemu_mutex_lock_iothread();
1581 kvm_arch_post_run(env, run);
1583 if (run_ret < 0) {
1584 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1585 DPRINTF("io window exit\n");
1586 ret = EXCP_INTERRUPT;
1587 break;
1589 fprintf(stderr, "error: kvm run failed %s\n",
1590 strerror(-run_ret));
1591 abort();
1594 switch (run->exit_reason) {
1595 case KVM_EXIT_IO:
1596 DPRINTF("handle_io\n");
1597 kvm_handle_io(run->io.port,
1598 (uint8_t *)run + run->io.data_offset,
1599 run->io.direction,
1600 run->io.size,
1601 run->io.count);
1602 ret = 0;
1603 break;
1604 case KVM_EXIT_MMIO:
1605 DPRINTF("handle_mmio\n");
1606 cpu_physical_memory_rw(run->mmio.phys_addr,
1607 run->mmio.data,
1608 run->mmio.len,
1609 run->mmio.is_write);
1610 ret = 0;
1611 break;
1612 case KVM_EXIT_IRQ_WINDOW_OPEN:
1613 DPRINTF("irq_window_open\n");
1614 ret = EXCP_INTERRUPT;
1615 break;
1616 case KVM_EXIT_SHUTDOWN:
1617 DPRINTF("shutdown\n");
1618 qemu_system_reset_request();
1619 ret = EXCP_INTERRUPT;
1620 break;
1621 case KVM_EXIT_UNKNOWN:
1622 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1623 (uint64_t)run->hw.hardware_exit_reason);
1624 ret = -1;
1625 break;
1626 case KVM_EXIT_INTERNAL_ERROR:
1627 ret = kvm_handle_internal_error(env, run);
1628 break;
1629 default:
1630 DPRINTF("kvm_arch_handle_exit\n");
1631 ret = kvm_arch_handle_exit(env, run);
1632 break;
1634 } while (ret == 0);
1636 if (ret < 0) {
1637 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1638 vm_stop(RUN_STATE_INTERNAL_ERROR);
1641 env->exit_request = 0;
1642 return ret;
1645 int kvm_ioctl(KVMState *s, int type, ...)
1647 int ret;
1648 void *arg;
1649 va_list ap;
1651 va_start(ap, type);
1652 arg = va_arg(ap, void *);
1653 va_end(ap);
1655 ret = ioctl(s->fd, type, arg);
1656 if (ret == -1) {
1657 ret = -errno;
1659 return ret;
1662 int kvm_vm_ioctl(KVMState *s, int type, ...)
1664 int ret;
1665 void *arg;
1666 va_list ap;
1668 va_start(ap, type);
1669 arg = va_arg(ap, void *);
1670 va_end(ap);
1672 ret = ioctl(s->vmfd, type, arg);
1673 if (ret == -1) {
1674 ret = -errno;
1676 return ret;
1679 int kvm_vcpu_ioctl(CPUArchState *env, int type, ...)
1681 int ret;
1682 void *arg;
1683 va_list ap;
1685 va_start(ap, type);
1686 arg = va_arg(ap, void *);
1687 va_end(ap);
1689 ret = ioctl(env->kvm_fd, type, arg);
1690 if (ret == -1) {
1691 ret = -errno;
1693 return ret;
1696 int kvm_has_sync_mmu(void)
1698 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1701 int kvm_has_vcpu_events(void)
1703 return kvm_state->vcpu_events;
1706 int kvm_has_robust_singlestep(void)
1708 return kvm_state->robust_singlestep;
1711 int kvm_has_debugregs(void)
1713 return kvm_state->debugregs;
1716 int kvm_has_xsave(void)
1718 return kvm_state->xsave;
1721 int kvm_has_xcrs(void)
1723 return kvm_state->xcrs;
1726 int kvm_has_pit_state2(void)
1728 return kvm_state->pit_state2;
1731 int kvm_has_many_ioeventfds(void)
1733 if (!kvm_enabled()) {
1734 return 0;
1736 return kvm_state->many_ioeventfds;
1739 int kvm_has_gsi_routing(void)
1741 #ifdef KVM_CAP_IRQ_ROUTING
1742 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
1743 #else
1744 return false;
1745 #endif
1748 int kvm_has_intx_set_mask(void)
1750 return kvm_state->intx_set_mask;
1753 void *kvm_vmalloc(ram_addr_t size)
1755 #ifdef TARGET_S390X
1756 void *mem;
1758 mem = kvm_arch_vmalloc(size);
1759 if (mem) {
1760 return mem;
1762 #endif
1763 return qemu_vmalloc(size);
1766 void kvm_setup_guest_memory(void *start, size_t size)
1768 #ifdef CONFIG_VALGRIND_H
1769 VALGRIND_MAKE_MEM_DEFINED(start, size);
1770 #endif
1771 if (!kvm_has_sync_mmu()) {
1772 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1774 if (ret) {
1775 perror("qemu_madvise");
1776 fprintf(stderr,
1777 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1778 exit(1);
1783 #ifdef KVM_CAP_SET_GUEST_DEBUG
1784 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUArchState *env,
1785 target_ulong pc)
1787 struct kvm_sw_breakpoint *bp;
1789 QTAILQ_FOREACH(bp, &env->kvm_state->kvm_sw_breakpoints, entry) {
1790 if (bp->pc == pc) {
1791 return bp;
1794 return NULL;
1797 int kvm_sw_breakpoints_active(CPUArchState *env)
1799 return !QTAILQ_EMPTY(&env->kvm_state->kvm_sw_breakpoints);
1802 struct kvm_set_guest_debug_data {
1803 struct kvm_guest_debug dbg;
1804 CPUArchState *env;
1805 int err;
1808 static void kvm_invoke_set_guest_debug(void *data)
1810 struct kvm_set_guest_debug_data *dbg_data = data;
1811 CPUArchState *env = dbg_data->env;
1813 dbg_data->err = kvm_vcpu_ioctl(env, KVM_SET_GUEST_DEBUG, &dbg_data->dbg);
1816 int kvm_update_guest_debug(CPUArchState *env, unsigned long reinject_trap)
1818 struct kvm_set_guest_debug_data data;
1820 data.dbg.control = reinject_trap;
1822 if (env->singlestep_enabled) {
1823 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
1825 kvm_arch_update_guest_debug(env, &data.dbg);
1826 data.env = env;
1828 run_on_cpu(env, kvm_invoke_set_guest_debug, &data);
1829 return data.err;
1832 int kvm_insert_breakpoint(CPUArchState *current_env, target_ulong addr,
1833 target_ulong len, int type)
1835 struct kvm_sw_breakpoint *bp;
1836 CPUArchState *env;
1837 int err;
1839 if (type == GDB_BREAKPOINT_SW) {
1840 bp = kvm_find_sw_breakpoint(current_env, addr);
1841 if (bp) {
1842 bp->use_count++;
1843 return 0;
1846 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
1847 if (!bp) {
1848 return -ENOMEM;
1851 bp->pc = addr;
1852 bp->use_count = 1;
1853 err = kvm_arch_insert_sw_breakpoint(current_env, bp);
1854 if (err) {
1855 g_free(bp);
1856 return err;
1859 QTAILQ_INSERT_HEAD(&current_env->kvm_state->kvm_sw_breakpoints,
1860 bp, entry);
1861 } else {
1862 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
1863 if (err) {
1864 return err;
1868 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1869 err = kvm_update_guest_debug(env, 0);
1870 if (err) {
1871 return err;
1874 return 0;
1877 int kvm_remove_breakpoint(CPUArchState *current_env, target_ulong addr,
1878 target_ulong len, int type)
1880 struct kvm_sw_breakpoint *bp;
1881 CPUArchState *env;
1882 int err;
1884 if (type == GDB_BREAKPOINT_SW) {
1885 bp = kvm_find_sw_breakpoint(current_env, addr);
1886 if (!bp) {
1887 return -ENOENT;
1890 if (bp->use_count > 1) {
1891 bp->use_count--;
1892 return 0;
1895 err = kvm_arch_remove_sw_breakpoint(current_env, bp);
1896 if (err) {
1897 return err;
1900 QTAILQ_REMOVE(&current_env->kvm_state->kvm_sw_breakpoints, bp, entry);
1901 g_free(bp);
1902 } else {
1903 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
1904 if (err) {
1905 return err;
1909 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1910 err = kvm_update_guest_debug(env, 0);
1911 if (err) {
1912 return err;
1915 return 0;
1918 void kvm_remove_all_breakpoints(CPUArchState *current_env)
1920 struct kvm_sw_breakpoint *bp, *next;
1921 KVMState *s = current_env->kvm_state;
1922 CPUArchState *env;
1924 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
1925 if (kvm_arch_remove_sw_breakpoint(current_env, bp) != 0) {
1926 /* Try harder to find a CPU that currently sees the breakpoint. */
1927 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1928 if (kvm_arch_remove_sw_breakpoint(env, bp) == 0) {
1929 break;
1934 kvm_arch_remove_all_hw_breakpoints();
1936 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1937 kvm_update_guest_debug(env, 0);
1941 #else /* !KVM_CAP_SET_GUEST_DEBUG */
1943 int kvm_update_guest_debug(CPUArchState *env, unsigned long reinject_trap)
1945 return -EINVAL;
1948 int kvm_insert_breakpoint(CPUArchState *current_env, target_ulong addr,
1949 target_ulong len, int type)
1951 return -EINVAL;
1954 int kvm_remove_breakpoint(CPUArchState *current_env, target_ulong addr,
1955 target_ulong len, int type)
1957 return -EINVAL;
1960 void kvm_remove_all_breakpoints(CPUArchState *current_env)
1963 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
1965 int kvm_set_signal_mask(CPUArchState *env, const sigset_t *sigset)
1967 struct kvm_signal_mask *sigmask;
1968 int r;
1970 if (!sigset) {
1971 return kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, NULL);
1974 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
1976 sigmask->len = 8;
1977 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
1978 r = kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, sigmask);
1979 g_free(sigmask);
1981 return r;
1984 int kvm_set_ioeventfd_mmio(int fd, uint32_t addr, uint32_t val, bool assign,
1985 uint32_t size)
1987 int ret;
1988 struct kvm_ioeventfd iofd;
1990 iofd.datamatch = val;
1991 iofd.addr = addr;
1992 iofd.len = size;
1993 iofd.flags = KVM_IOEVENTFD_FLAG_DATAMATCH;
1994 iofd.fd = fd;
1996 if (!kvm_enabled()) {
1997 return -ENOSYS;
2000 if (!assign) {
2001 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
2004 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
2006 if (ret < 0) {
2007 return -errno;
2010 return 0;
2013 int kvm_set_ioeventfd_pio_word(int fd, uint16_t addr, uint16_t val, bool assign)
2015 struct kvm_ioeventfd kick = {
2016 .datamatch = val,
2017 .addr = addr,
2018 .len = 2,
2019 .flags = KVM_IOEVENTFD_FLAG_DATAMATCH | KVM_IOEVENTFD_FLAG_PIO,
2020 .fd = fd,
2022 int r;
2023 if (!kvm_enabled()) {
2024 return -ENOSYS;
2026 if (!assign) {
2027 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
2029 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
2030 if (r < 0) {
2031 return r;
2033 return 0;
2036 int kvm_on_sigbus_vcpu(CPUArchState *env, int code, void *addr)
2038 return kvm_arch_on_sigbus_vcpu(env, code, addr);
2041 int kvm_on_sigbus(int code, void *addr)
2043 return kvm_arch_on_sigbus(code, addr);