scsi-disk: improve out-of-range LBA detection for WRITE SAME
[qemu-kvm.git] / kvm-all.c
blob2148b20bdbdf8c6b3f57628c8f571f66fdfc67e3
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 /* KVM uses PAGE_SIZE in its definition of COALESCED_MMIO_MAX */
43 #define PAGE_SIZE TARGET_PAGE_SIZE
45 //#define DEBUG_KVM
47 #ifdef DEBUG_KVM
48 #define DPRINTF(fmt, ...) \
49 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
50 #else
51 #define DPRINTF(fmt, ...) \
52 do { } while (0)
53 #endif
55 #define KVM_MSI_HASHTAB_SIZE 256
57 typedef struct KVMSlot
59 target_phys_addr_t start_addr;
60 ram_addr_t memory_size;
61 void *ram;
62 int slot;
63 int flags;
64 } KVMSlot;
66 typedef struct kvm_dirty_log KVMDirtyLog;
68 struct KVMState
70 KVMSlot slots[32];
71 int fd;
72 int vmfd;
73 int coalesced_mmio;
74 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
75 bool coalesced_flush_in_progress;
76 int broken_set_mem_region;
77 int migration_log;
78 int vcpu_events;
79 int robust_singlestep;
80 int debugregs;
81 #ifdef KVM_CAP_SET_GUEST_DEBUG
82 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
83 #endif
84 int pit_state2;
85 int xsave, xcrs;
86 int many_ioeventfds;
87 /* The man page (and posix) say ioctl numbers are signed int, but
88 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
89 * unsigned, and treating them as signed here can break things */
90 unsigned irqchip_inject_ioctl;
91 #ifdef KVM_CAP_IRQ_ROUTING
92 struct kvm_irq_routing *irq_routes;
93 int nr_allocated_irq_routes;
94 uint32_t *used_gsi_bitmap;
95 unsigned int gsi_count;
96 QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
97 bool direct_msi;
98 #endif
101 KVMState *kvm_state;
102 bool kvm_kernel_irqchip;
104 static const KVMCapabilityInfo kvm_required_capabilites[] = {
105 KVM_CAP_INFO(USER_MEMORY),
106 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
107 KVM_CAP_LAST_INFO
110 static KVMSlot *kvm_alloc_slot(KVMState *s)
112 int i;
114 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
115 if (s->slots[i].memory_size == 0) {
116 return &s->slots[i];
120 fprintf(stderr, "%s: no free slot available\n", __func__);
121 abort();
124 static KVMSlot *kvm_lookup_matching_slot(KVMState *s,
125 target_phys_addr_t start_addr,
126 target_phys_addr_t end_addr)
128 int i;
130 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
131 KVMSlot *mem = &s->slots[i];
133 if (start_addr == mem->start_addr &&
134 end_addr == mem->start_addr + mem->memory_size) {
135 return mem;
139 return NULL;
143 * Find overlapping slot with lowest start address
145 static KVMSlot *kvm_lookup_overlapping_slot(KVMState *s,
146 target_phys_addr_t start_addr,
147 target_phys_addr_t end_addr)
149 KVMSlot *found = NULL;
150 int i;
152 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
153 KVMSlot *mem = &s->slots[i];
155 if (mem->memory_size == 0 ||
156 (found && found->start_addr < mem->start_addr)) {
157 continue;
160 if (end_addr > mem->start_addr &&
161 start_addr < mem->start_addr + mem->memory_size) {
162 found = mem;
166 return found;
169 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
170 target_phys_addr_t *phys_addr)
172 int i;
174 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
175 KVMSlot *mem = &s->slots[i];
177 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
178 *phys_addr = mem->start_addr + (ram - mem->ram);
179 return 1;
183 return 0;
186 static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)
188 struct kvm_userspace_memory_region mem;
190 mem.slot = slot->slot;
191 mem.guest_phys_addr = slot->start_addr;
192 mem.memory_size = slot->memory_size;
193 mem.userspace_addr = (unsigned long)slot->ram;
194 mem.flags = slot->flags;
195 if (s->migration_log) {
196 mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;
198 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
201 static void kvm_reset_vcpu(void *opaque)
203 CPUArchState *env = opaque;
205 kvm_arch_reset_vcpu(env);
208 int kvm_init_vcpu(CPUArchState *env)
210 KVMState *s = kvm_state;
211 long mmap_size;
212 int ret;
214 DPRINTF("kvm_init_vcpu\n");
216 ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, env->cpu_index);
217 if (ret < 0) {
218 DPRINTF("kvm_create_vcpu failed\n");
219 goto err;
222 env->kvm_fd = ret;
223 env->kvm_state = s;
224 env->kvm_vcpu_dirty = 1;
226 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
227 if (mmap_size < 0) {
228 ret = mmap_size;
229 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
230 goto err;
233 env->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
234 env->kvm_fd, 0);
235 if (env->kvm_run == MAP_FAILED) {
236 ret = -errno;
237 DPRINTF("mmap'ing vcpu state failed\n");
238 goto err;
241 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
242 s->coalesced_mmio_ring =
243 (void *)env->kvm_run + s->coalesced_mmio * PAGE_SIZE;
246 ret = kvm_arch_init_vcpu(env);
247 if (ret == 0) {
248 qemu_register_reset(kvm_reset_vcpu, env);
249 kvm_arch_reset_vcpu(env);
251 err:
252 return ret;
256 * dirty pages logging control
259 static int kvm_mem_flags(KVMState *s, bool log_dirty)
261 return log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
264 static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
266 KVMState *s = kvm_state;
267 int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
268 int old_flags;
270 old_flags = mem->flags;
272 flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty);
273 mem->flags = flags;
275 /* If nothing changed effectively, no need to issue ioctl */
276 if (s->migration_log) {
277 flags |= KVM_MEM_LOG_DIRTY_PAGES;
280 if (flags == old_flags) {
281 return 0;
284 return kvm_set_user_memory_region(s, mem);
287 static int kvm_dirty_pages_log_change(target_phys_addr_t phys_addr,
288 ram_addr_t size, bool log_dirty)
290 KVMState *s = kvm_state;
291 KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
293 if (mem == NULL) {
294 fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
295 TARGET_FMT_plx "\n", __func__, phys_addr,
296 (target_phys_addr_t)(phys_addr + size - 1));
297 return -EINVAL;
299 return kvm_slot_dirty_pages_log_change(mem, log_dirty);
302 static void kvm_log_start(MemoryListener *listener,
303 MemoryRegionSection *section)
305 int r;
307 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
308 section->size, true);
309 if (r < 0) {
310 abort();
314 static void kvm_log_stop(MemoryListener *listener,
315 MemoryRegionSection *section)
317 int r;
319 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
320 section->size, false);
321 if (r < 0) {
322 abort();
326 static int kvm_set_migration_log(int enable)
328 KVMState *s = kvm_state;
329 KVMSlot *mem;
330 int i, err;
332 s->migration_log = enable;
334 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
335 mem = &s->slots[i];
337 if (!mem->memory_size) {
338 continue;
340 if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
341 continue;
343 err = kvm_set_user_memory_region(s, mem);
344 if (err) {
345 return err;
348 return 0;
351 /* get kvm's dirty pages bitmap and update qemu's */
352 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
353 unsigned long *bitmap)
355 unsigned int i, j;
356 unsigned long page_number, c;
357 target_phys_addr_t addr, addr1;
358 unsigned int len = ((section->size / TARGET_PAGE_SIZE) + HOST_LONG_BITS - 1) / HOST_LONG_BITS;
359 unsigned long hpratio = getpagesize() / TARGET_PAGE_SIZE;
362 * bitmap-traveling is faster than memory-traveling (for addr...)
363 * especially when most of the memory is not dirty.
365 for (i = 0; i < len; i++) {
366 if (bitmap[i] != 0) {
367 c = leul_to_cpu(bitmap[i]);
368 do {
369 j = ffsl(c) - 1;
370 c &= ~(1ul << j);
371 page_number = (i * HOST_LONG_BITS + j) * hpratio;
372 addr1 = page_number * TARGET_PAGE_SIZE;
373 addr = section->offset_within_region + addr1;
374 memory_region_set_dirty(section->mr, addr,
375 TARGET_PAGE_SIZE * hpratio);
376 } while (c != 0);
379 return 0;
382 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
385 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
386 * This function updates qemu's dirty bitmap using
387 * memory_region_set_dirty(). This means all bits are set
388 * to dirty.
390 * @start_add: start of logged region.
391 * @end_addr: end of logged region.
393 static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)
395 KVMState *s = kvm_state;
396 unsigned long size, allocated_size = 0;
397 KVMDirtyLog d;
398 KVMSlot *mem;
399 int ret = 0;
400 target_phys_addr_t start_addr = section->offset_within_address_space;
401 target_phys_addr_t end_addr = start_addr + section->size;
403 d.dirty_bitmap = NULL;
404 while (start_addr < end_addr) {
405 mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
406 if (mem == NULL) {
407 break;
410 /* XXX bad kernel interface alert
411 * For dirty bitmap, kernel allocates array of size aligned to
412 * bits-per-long. But for case when the kernel is 64bits and
413 * the userspace is 32bits, userspace can't align to the same
414 * bits-per-long, since sizeof(long) is different between kernel
415 * and user space. This way, userspace will provide buffer which
416 * may be 4 bytes less than the kernel will use, resulting in
417 * userspace memory corruption (which is not detectable by valgrind
418 * too, in most cases).
419 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
420 * a hope that sizeof(long) wont become >8 any time soon.
422 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
423 /*HOST_LONG_BITS*/ 64) / 8;
424 if (!d.dirty_bitmap) {
425 d.dirty_bitmap = g_malloc(size);
426 } else if (size > allocated_size) {
427 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
429 allocated_size = size;
430 memset(d.dirty_bitmap, 0, allocated_size);
432 d.slot = mem->slot;
434 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
435 DPRINTF("ioctl failed %d\n", errno);
436 ret = -1;
437 break;
440 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
441 start_addr = mem->start_addr + mem->memory_size;
443 g_free(d.dirty_bitmap);
445 return ret;
448 int kvm_coalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
450 int ret = -ENOSYS;
451 KVMState *s = kvm_state;
453 if (s->coalesced_mmio) {
454 struct kvm_coalesced_mmio_zone zone;
456 zone.addr = start;
457 zone.size = size;
458 zone.pad = 0;
460 ret = kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
463 return ret;
466 int kvm_uncoalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
468 int ret = -ENOSYS;
469 KVMState *s = kvm_state;
471 if (s->coalesced_mmio) {
472 struct kvm_coalesced_mmio_zone zone;
474 zone.addr = start;
475 zone.size = size;
476 zone.pad = 0;
478 ret = kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
481 return ret;
484 int kvm_check_extension(KVMState *s, unsigned int extension)
486 int ret;
488 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
489 if (ret < 0) {
490 ret = 0;
493 return ret;
496 static int kvm_check_many_ioeventfds(void)
498 /* Userspace can use ioeventfd for io notification. This requires a host
499 * that supports eventfd(2) and an I/O thread; since eventfd does not
500 * support SIGIO it cannot interrupt the vcpu.
502 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
503 * can avoid creating too many ioeventfds.
505 #if defined(CONFIG_EVENTFD)
506 int ioeventfds[7];
507 int i, ret = 0;
508 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
509 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
510 if (ioeventfds[i] < 0) {
511 break;
513 ret = kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, true);
514 if (ret < 0) {
515 close(ioeventfds[i]);
516 break;
520 /* Decide whether many devices are supported or not */
521 ret = i == ARRAY_SIZE(ioeventfds);
523 while (i-- > 0) {
524 kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, false);
525 close(ioeventfds[i]);
527 return ret;
528 #else
529 return 0;
530 #endif
533 static const KVMCapabilityInfo *
534 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
536 while (list->name) {
537 if (!kvm_check_extension(s, list->value)) {
538 return list;
540 list++;
542 return NULL;
545 static void kvm_set_phys_mem(MemoryRegionSection *section, bool add)
547 KVMState *s = kvm_state;
548 KVMSlot *mem, old;
549 int err;
550 MemoryRegion *mr = section->mr;
551 bool log_dirty = memory_region_is_logging(mr);
552 target_phys_addr_t start_addr = section->offset_within_address_space;
553 ram_addr_t size = section->size;
554 void *ram = NULL;
555 unsigned delta;
557 /* kvm works in page size chunks, but the function may be called
558 with sub-page size and unaligned start address. */
559 delta = TARGET_PAGE_ALIGN(size) - size;
560 if (delta > size) {
561 return;
563 start_addr += delta;
564 size -= delta;
565 size &= TARGET_PAGE_MASK;
566 if (!size || (start_addr & ~TARGET_PAGE_MASK)) {
567 return;
570 if (!memory_region_is_ram(mr)) {
571 return;
574 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
576 while (1) {
577 mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
578 if (!mem) {
579 break;
582 if (add && start_addr >= mem->start_addr &&
583 (start_addr + size <= mem->start_addr + mem->memory_size) &&
584 (ram - start_addr == mem->ram - mem->start_addr)) {
585 /* The new slot fits into the existing one and comes with
586 * identical parameters - update flags and done. */
587 kvm_slot_dirty_pages_log_change(mem, log_dirty);
588 return;
591 old = *mem;
593 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
594 kvm_physical_sync_dirty_bitmap(section);
597 /* unregister the overlapping slot */
598 mem->memory_size = 0;
599 err = kvm_set_user_memory_region(s, mem);
600 if (err) {
601 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
602 __func__, strerror(-err));
603 abort();
606 /* Workaround for older KVM versions: we can't join slots, even not by
607 * unregistering the previous ones and then registering the larger
608 * slot. We have to maintain the existing fragmentation. Sigh.
610 * This workaround assumes that the new slot starts at the same
611 * address as the first existing one. If not or if some overlapping
612 * slot comes around later, we will fail (not seen in practice so far)
613 * - and actually require a recent KVM version. */
614 if (s->broken_set_mem_region &&
615 old.start_addr == start_addr && old.memory_size < size && add) {
616 mem = kvm_alloc_slot(s);
617 mem->memory_size = old.memory_size;
618 mem->start_addr = old.start_addr;
619 mem->ram = old.ram;
620 mem->flags = kvm_mem_flags(s, log_dirty);
622 err = kvm_set_user_memory_region(s, mem);
623 if (err) {
624 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
625 strerror(-err));
626 abort();
629 start_addr += old.memory_size;
630 ram += old.memory_size;
631 size -= old.memory_size;
632 continue;
635 /* register prefix slot */
636 if (old.start_addr < start_addr) {
637 mem = kvm_alloc_slot(s);
638 mem->memory_size = start_addr - old.start_addr;
639 mem->start_addr = old.start_addr;
640 mem->ram = old.ram;
641 mem->flags = kvm_mem_flags(s, log_dirty);
643 err = kvm_set_user_memory_region(s, mem);
644 if (err) {
645 fprintf(stderr, "%s: error registering prefix slot: %s\n",
646 __func__, strerror(-err));
647 #ifdef TARGET_PPC
648 fprintf(stderr, "%s: This is probably because your kernel's " \
649 "PAGE_SIZE is too big. Please try to use 4k " \
650 "PAGE_SIZE!\n", __func__);
651 #endif
652 abort();
656 /* register suffix slot */
657 if (old.start_addr + old.memory_size > start_addr + size) {
658 ram_addr_t size_delta;
660 mem = kvm_alloc_slot(s);
661 mem->start_addr = start_addr + size;
662 size_delta = mem->start_addr - old.start_addr;
663 mem->memory_size = old.memory_size - size_delta;
664 mem->ram = old.ram + size_delta;
665 mem->flags = kvm_mem_flags(s, log_dirty);
667 err = kvm_set_user_memory_region(s, mem);
668 if (err) {
669 fprintf(stderr, "%s: error registering suffix slot: %s\n",
670 __func__, strerror(-err));
671 abort();
676 /* in case the KVM bug workaround already "consumed" the new slot */
677 if (!size) {
678 return;
680 if (!add) {
681 return;
683 mem = kvm_alloc_slot(s);
684 mem->memory_size = size;
685 mem->start_addr = start_addr;
686 mem->ram = ram;
687 mem->flags = kvm_mem_flags(s, log_dirty);
689 err = kvm_set_user_memory_region(s, mem);
690 if (err) {
691 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
692 strerror(-err));
693 abort();
697 static void kvm_begin(MemoryListener *listener)
701 static void kvm_commit(MemoryListener *listener)
705 static void kvm_region_add(MemoryListener *listener,
706 MemoryRegionSection *section)
708 kvm_set_phys_mem(section, true);
711 static void kvm_region_del(MemoryListener *listener,
712 MemoryRegionSection *section)
714 kvm_set_phys_mem(section, false);
717 static void kvm_region_nop(MemoryListener *listener,
718 MemoryRegionSection *section)
722 static void kvm_log_sync(MemoryListener *listener,
723 MemoryRegionSection *section)
725 int r;
727 r = kvm_physical_sync_dirty_bitmap(section);
728 if (r < 0) {
729 abort();
733 static void kvm_log_global_start(struct MemoryListener *listener)
735 int r;
737 r = kvm_set_migration_log(1);
738 assert(r >= 0);
741 static void kvm_log_global_stop(struct MemoryListener *listener)
743 int r;
745 r = kvm_set_migration_log(0);
746 assert(r >= 0);
749 static void kvm_mem_ioeventfd_add(MemoryRegionSection *section,
750 bool match_data, uint64_t data, int fd)
752 int r;
754 assert(match_data && section->size <= 8);
756 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
757 data, true, section->size);
758 if (r < 0) {
759 abort();
763 static void kvm_mem_ioeventfd_del(MemoryRegionSection *section,
764 bool match_data, uint64_t data, int fd)
766 int r;
768 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
769 data, false, section->size);
770 if (r < 0) {
771 abort();
775 static void kvm_io_ioeventfd_add(MemoryRegionSection *section,
776 bool match_data, uint64_t data, int fd)
778 int r;
780 assert(match_data && section->size == 2);
782 r = kvm_set_ioeventfd_pio_word(fd, section->offset_within_address_space,
783 data, true);
784 if (r < 0) {
785 abort();
789 static void kvm_io_ioeventfd_del(MemoryRegionSection *section,
790 bool match_data, uint64_t data, int fd)
793 int r;
795 r = kvm_set_ioeventfd_pio_word(fd, section->offset_within_address_space,
796 data, false);
797 if (r < 0) {
798 abort();
802 static void kvm_eventfd_add(MemoryListener *listener,
803 MemoryRegionSection *section,
804 bool match_data, uint64_t data,
805 EventNotifier *e)
807 if (section->address_space == get_system_memory()) {
808 kvm_mem_ioeventfd_add(section, match_data, data,
809 event_notifier_get_fd(e));
810 } else {
811 kvm_io_ioeventfd_add(section, match_data, data,
812 event_notifier_get_fd(e));
816 static void kvm_eventfd_del(MemoryListener *listener,
817 MemoryRegionSection *section,
818 bool match_data, uint64_t data,
819 EventNotifier *e)
821 if (section->address_space == get_system_memory()) {
822 kvm_mem_ioeventfd_del(section, match_data, data,
823 event_notifier_get_fd(e));
824 } else {
825 kvm_io_ioeventfd_del(section, match_data, data,
826 event_notifier_get_fd(e));
830 static MemoryListener kvm_memory_listener = {
831 .begin = kvm_begin,
832 .commit = kvm_commit,
833 .region_add = kvm_region_add,
834 .region_del = kvm_region_del,
835 .region_nop = kvm_region_nop,
836 .log_start = kvm_log_start,
837 .log_stop = kvm_log_stop,
838 .log_sync = kvm_log_sync,
839 .log_global_start = kvm_log_global_start,
840 .log_global_stop = kvm_log_global_stop,
841 .eventfd_add = kvm_eventfd_add,
842 .eventfd_del = kvm_eventfd_del,
843 .priority = 10,
846 static void kvm_handle_interrupt(CPUArchState *env, int mask)
848 env->interrupt_request |= mask;
850 if (!qemu_cpu_is_self(env)) {
851 qemu_cpu_kick(env);
855 int kvm_irqchip_set_irq(KVMState *s, int irq, int level)
857 struct kvm_irq_level event;
858 int ret;
860 assert(kvm_irqchip_in_kernel());
862 event.level = level;
863 event.irq = irq;
864 ret = kvm_vm_ioctl(s, s->irqchip_inject_ioctl, &event);
865 if (ret < 0) {
866 perror("kvm_set_irqchip_line");
867 abort();
870 return (s->irqchip_inject_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
873 #ifdef KVM_CAP_IRQ_ROUTING
874 typedef struct KVMMSIRoute {
875 struct kvm_irq_routing_entry kroute;
876 QTAILQ_ENTRY(KVMMSIRoute) entry;
877 } KVMMSIRoute;
879 static void set_gsi(KVMState *s, unsigned int gsi)
881 s->used_gsi_bitmap[gsi / 32] |= 1U << (gsi % 32);
884 static void clear_gsi(KVMState *s, unsigned int gsi)
886 s->used_gsi_bitmap[gsi / 32] &= ~(1U << (gsi % 32));
889 static void kvm_init_irq_routing(KVMState *s)
891 int gsi_count, i;
893 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING);
894 if (gsi_count > 0) {
895 unsigned int gsi_bits, i;
897 /* Round up so we can search ints using ffs */
898 gsi_bits = ALIGN(gsi_count, 32);
899 s->used_gsi_bitmap = g_malloc0(gsi_bits / 8);
900 s->gsi_count = gsi_count;
902 /* Mark any over-allocated bits as already in use */
903 for (i = gsi_count; i < gsi_bits; i++) {
904 set_gsi(s, i);
908 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
909 s->nr_allocated_irq_routes = 0;
911 if (!s->direct_msi) {
912 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
913 QTAILQ_INIT(&s->msi_hashtab[i]);
917 kvm_arch_init_irq_routing(s);
920 static void kvm_irqchip_commit_routes(KVMState *s)
922 int ret;
924 s->irq_routes->flags = 0;
925 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
926 assert(ret == 0);
929 static void kvm_add_routing_entry(KVMState *s,
930 struct kvm_irq_routing_entry *entry)
932 struct kvm_irq_routing_entry *new;
933 int n, size;
935 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
936 n = s->nr_allocated_irq_routes * 2;
937 if (n < 64) {
938 n = 64;
940 size = sizeof(struct kvm_irq_routing);
941 size += n * sizeof(*new);
942 s->irq_routes = g_realloc(s->irq_routes, size);
943 s->nr_allocated_irq_routes = n;
945 n = s->irq_routes->nr++;
946 new = &s->irq_routes->entries[n];
947 memset(new, 0, sizeof(*new));
948 new->gsi = entry->gsi;
949 new->type = entry->type;
950 new->flags = entry->flags;
951 new->u = entry->u;
953 set_gsi(s, entry->gsi);
955 kvm_irqchip_commit_routes(s);
958 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
960 struct kvm_irq_routing_entry e;
962 assert(pin < s->gsi_count);
964 e.gsi = irq;
965 e.type = KVM_IRQ_ROUTING_IRQCHIP;
966 e.flags = 0;
967 e.u.irqchip.irqchip = irqchip;
968 e.u.irqchip.pin = pin;
969 kvm_add_routing_entry(s, &e);
972 void kvm_irqchip_release_virq(KVMState *s, int virq)
974 struct kvm_irq_routing_entry *e;
975 int i;
977 for (i = 0; i < s->irq_routes->nr; i++) {
978 e = &s->irq_routes->entries[i];
979 if (e->gsi == virq) {
980 s->irq_routes->nr--;
981 *e = s->irq_routes->entries[s->irq_routes->nr];
984 clear_gsi(s, virq);
986 kvm_irqchip_commit_routes(s);
989 static unsigned int kvm_hash_msi(uint32_t data)
991 /* This is optimized for IA32 MSI layout. However, no other arch shall
992 * repeat the mistake of not providing a direct MSI injection API. */
993 return data & 0xff;
996 static void kvm_flush_dynamic_msi_routes(KVMState *s)
998 KVMMSIRoute *route, *next;
999 unsigned int hash;
1001 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1002 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1003 kvm_irqchip_release_virq(s, route->kroute.gsi);
1004 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1005 g_free(route);
1010 static int kvm_irqchip_get_virq(KVMState *s)
1012 uint32_t *word = s->used_gsi_bitmap;
1013 int max_words = ALIGN(s->gsi_count, 32) / 32;
1014 int i, bit;
1015 bool retry = true;
1017 again:
1018 /* Return the lowest unused GSI in the bitmap */
1019 for (i = 0; i < max_words; i++) {
1020 bit = ffs(~word[i]);
1021 if (!bit) {
1022 continue;
1025 return bit - 1 + i * 32;
1027 if (!s->direct_msi && retry) {
1028 retry = false;
1029 kvm_flush_dynamic_msi_routes(s);
1030 goto again;
1032 return -ENOSPC;
1036 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1038 unsigned int hash = kvm_hash_msi(msg.data);
1039 KVMMSIRoute *route;
1041 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1042 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1043 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1044 route->kroute.u.msi.data == msg.data) {
1045 return route;
1048 return NULL;
1051 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1053 struct kvm_msi msi;
1054 KVMMSIRoute *route;
1056 if (s->direct_msi) {
1057 msi.address_lo = (uint32_t)msg.address;
1058 msi.address_hi = msg.address >> 32;
1059 msi.data = msg.data;
1060 msi.flags = 0;
1061 memset(msi.pad, 0, sizeof(msi.pad));
1063 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1066 route = kvm_lookup_msi_route(s, msg);
1067 if (!route) {
1068 int virq;
1070 virq = kvm_irqchip_get_virq(s);
1071 if (virq < 0) {
1072 return virq;
1075 route = g_malloc(sizeof(KVMMSIRoute));
1076 route->kroute.gsi = virq;
1077 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1078 route->kroute.flags = 0;
1079 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;
1083 kvm_add_routing_entry(s, &route->kroute);
1085 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1086 entry);
1089 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1091 return kvm_irqchip_set_irq(s, route->kroute.gsi, 1);
1094 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1096 struct kvm_irq_routing_entry kroute;
1097 int virq;
1099 if (!kvm_irqchip_in_kernel()) {
1100 return -ENOSYS;
1103 virq = kvm_irqchip_get_virq(s);
1104 if (virq < 0) {
1105 return virq;
1108 kroute.gsi = virq;
1109 kroute.type = KVM_IRQ_ROUTING_MSI;
1110 kroute.flags = 0;
1111 kroute.u.msi.address_lo = (uint32_t)msg.address;
1112 kroute.u.msi.address_hi = msg.address >> 32;
1113 kroute.u.msi.data = msg.data;
1115 kvm_add_routing_entry(s, &kroute);
1117 return virq;
1120 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1122 struct kvm_irqfd irqfd = {
1123 .fd = fd,
1124 .gsi = virq,
1125 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1128 if (!kvm_irqchip_in_kernel()) {
1129 return -ENOSYS;
1132 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1135 #else /* !KVM_CAP_IRQ_ROUTING */
1137 static void kvm_init_irq_routing(KVMState *s)
1141 void kvm_irqchip_release_virq(KVMState *s, int virq)
1145 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1147 abort();
1150 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1152 return -ENOSYS;
1155 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1157 abort();
1159 #endif /* !KVM_CAP_IRQ_ROUTING */
1161 int kvm_irqchip_add_irqfd(KVMState *s, int fd, int virq)
1163 return kvm_irqchip_assign_irqfd(s, fd, virq, true);
1166 int kvm_irqchip_add_irq_notifier(KVMState *s, EventNotifier *n, int virq)
1168 return kvm_irqchip_add_irqfd(s, event_notifier_get_fd(n), virq);
1171 int kvm_irqchip_remove_irqfd(KVMState *s, int fd, int virq)
1173 return kvm_irqchip_assign_irqfd(s, fd, virq, false);
1176 int kvm_irqchip_remove_irq_notifier(KVMState *s, EventNotifier *n, int virq)
1178 return kvm_irqchip_remove_irqfd(s, event_notifier_get_fd(n), virq);
1181 static int kvm_irqchip_create(KVMState *s)
1183 QemuOptsList *list = qemu_find_opts("machine");
1184 int ret;
1186 if (QTAILQ_EMPTY(&list->head) ||
1187 !qemu_opt_get_bool(QTAILQ_FIRST(&list->head),
1188 "kernel_irqchip", true) ||
1189 !kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
1190 return 0;
1193 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1194 if (ret < 0) {
1195 fprintf(stderr, "Create kernel irqchip failed\n");
1196 return ret;
1199 s->irqchip_inject_ioctl = KVM_IRQ_LINE;
1200 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1201 s->irqchip_inject_ioctl = KVM_IRQ_LINE_STATUS;
1203 kvm_kernel_irqchip = true;
1205 kvm_init_irq_routing(s);
1207 return 0;
1210 int kvm_init(void)
1212 static const char upgrade_note[] =
1213 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1214 "(see http://sourceforge.net/projects/kvm).\n";
1215 KVMState *s;
1216 const KVMCapabilityInfo *missing_cap;
1217 int ret;
1218 int i;
1220 s = g_malloc0(sizeof(KVMState));
1223 * On systems where the kernel can support different base page
1224 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1225 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1226 * page size for the system though.
1228 assert(TARGET_PAGE_SIZE <= getpagesize());
1230 #ifdef KVM_CAP_SET_GUEST_DEBUG
1231 QTAILQ_INIT(&s->kvm_sw_breakpoints);
1232 #endif
1233 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
1234 s->slots[i].slot = i;
1236 s->vmfd = -1;
1237 s->fd = qemu_open("/dev/kvm", O_RDWR);
1238 if (s->fd == -1) {
1239 fprintf(stderr, "Could not access KVM kernel module: %m\n");
1240 ret = -errno;
1241 goto err;
1244 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1245 if (ret < KVM_API_VERSION) {
1246 if (ret > 0) {
1247 ret = -EINVAL;
1249 fprintf(stderr, "kvm version too old\n");
1250 goto err;
1253 if (ret > KVM_API_VERSION) {
1254 ret = -EINVAL;
1255 fprintf(stderr, "kvm version not supported\n");
1256 goto err;
1259 s->vmfd = kvm_ioctl(s, KVM_CREATE_VM, 0);
1260 if (s->vmfd < 0) {
1261 #ifdef TARGET_S390X
1262 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
1263 "your host kernel command line\n");
1264 #endif
1265 ret = s->vmfd;
1266 goto err;
1269 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1270 if (!missing_cap) {
1271 missing_cap =
1272 kvm_check_extension_list(s, kvm_arch_required_capabilities);
1274 if (missing_cap) {
1275 ret = -EINVAL;
1276 fprintf(stderr, "kvm does not support %s\n%s",
1277 missing_cap->name, upgrade_note);
1278 goto err;
1281 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1283 s->broken_set_mem_region = 1;
1284 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
1285 if (ret > 0) {
1286 s->broken_set_mem_region = 0;
1289 #ifdef KVM_CAP_VCPU_EVENTS
1290 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1291 #endif
1293 s->robust_singlestep =
1294 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1296 #ifdef KVM_CAP_DEBUGREGS
1297 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1298 #endif
1300 #ifdef KVM_CAP_XSAVE
1301 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1302 #endif
1304 #ifdef KVM_CAP_XCRS
1305 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1306 #endif
1308 #ifdef KVM_CAP_PIT_STATE2
1309 s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1310 #endif
1312 #ifdef KVM_CAP_IRQ_ROUTING
1313 s->direct_msi = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1314 #endif
1316 ret = kvm_arch_init(s);
1317 if (ret < 0) {
1318 goto err;
1321 ret = kvm_irqchip_create(s);
1322 if (ret < 0) {
1323 goto err;
1326 kvm_state = s;
1327 memory_listener_register(&kvm_memory_listener, NULL);
1329 s->many_ioeventfds = kvm_check_many_ioeventfds();
1331 cpu_interrupt_handler = kvm_handle_interrupt;
1333 return 0;
1335 err:
1336 if (s) {
1337 if (s->vmfd >= 0) {
1338 close(s->vmfd);
1340 if (s->fd != -1) {
1341 close(s->fd);
1344 g_free(s);
1346 return ret;
1349 static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
1350 uint32_t count)
1352 int i;
1353 uint8_t *ptr = data;
1355 for (i = 0; i < count; i++) {
1356 if (direction == KVM_EXIT_IO_IN) {
1357 switch (size) {
1358 case 1:
1359 stb_p(ptr, cpu_inb(port));
1360 break;
1361 case 2:
1362 stw_p(ptr, cpu_inw(port));
1363 break;
1364 case 4:
1365 stl_p(ptr, cpu_inl(port));
1366 break;
1368 } else {
1369 switch (size) {
1370 case 1:
1371 cpu_outb(port, ldub_p(ptr));
1372 break;
1373 case 2:
1374 cpu_outw(port, lduw_p(ptr));
1375 break;
1376 case 4:
1377 cpu_outl(port, ldl_p(ptr));
1378 break;
1382 ptr += size;
1386 static int kvm_handle_internal_error(CPUArchState *env, struct kvm_run *run)
1388 fprintf(stderr, "KVM internal error.");
1389 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1390 int i;
1392 fprintf(stderr, " Suberror: %d\n", run->internal.suberror);
1393 for (i = 0; i < run->internal.ndata; ++i) {
1394 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1395 i, (uint64_t)run->internal.data[i]);
1397 } else {
1398 fprintf(stderr, "\n");
1400 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1401 fprintf(stderr, "emulation failure\n");
1402 if (!kvm_arch_stop_on_emulation_error(env)) {
1403 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1404 return EXCP_INTERRUPT;
1407 /* FIXME: Should trigger a qmp message to let management know
1408 * something went wrong.
1410 return -1;
1413 void kvm_flush_coalesced_mmio_buffer(void)
1415 KVMState *s = kvm_state;
1417 if (s->coalesced_flush_in_progress) {
1418 return;
1421 s->coalesced_flush_in_progress = true;
1423 if (s->coalesced_mmio_ring) {
1424 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1425 while (ring->first != ring->last) {
1426 struct kvm_coalesced_mmio *ent;
1428 ent = &ring->coalesced_mmio[ring->first];
1430 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1431 smp_wmb();
1432 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1436 s->coalesced_flush_in_progress = false;
1439 static void do_kvm_cpu_synchronize_state(void *_env)
1441 CPUArchState *env = _env;
1443 if (!env->kvm_vcpu_dirty) {
1444 kvm_arch_get_registers(env);
1445 env->kvm_vcpu_dirty = 1;
1449 void kvm_cpu_synchronize_state(CPUArchState *env)
1451 if (!env->kvm_vcpu_dirty) {
1452 run_on_cpu(env, do_kvm_cpu_synchronize_state, env);
1456 void kvm_cpu_synchronize_post_reset(CPUArchState *env)
1458 kvm_arch_put_registers(env, KVM_PUT_RESET_STATE);
1459 env->kvm_vcpu_dirty = 0;
1462 void kvm_cpu_synchronize_post_init(CPUArchState *env)
1464 kvm_arch_put_registers(env, KVM_PUT_FULL_STATE);
1465 env->kvm_vcpu_dirty = 0;
1468 int kvm_cpu_exec(CPUArchState *env)
1470 struct kvm_run *run = env->kvm_run;
1471 int ret, run_ret;
1473 DPRINTF("kvm_cpu_exec()\n");
1475 if (kvm_arch_process_async_events(env)) {
1476 env->exit_request = 0;
1477 return EXCP_HLT;
1480 do {
1481 if (env->kvm_vcpu_dirty) {
1482 kvm_arch_put_registers(env, KVM_PUT_RUNTIME_STATE);
1483 env->kvm_vcpu_dirty = 0;
1486 kvm_arch_pre_run(env, run);
1487 if (env->exit_request) {
1488 DPRINTF("interrupt exit requested\n");
1490 * KVM requires us to reenter the kernel after IO exits to complete
1491 * instruction emulation. This self-signal will ensure that we
1492 * leave ASAP again.
1494 qemu_cpu_kick_self();
1496 qemu_mutex_unlock_iothread();
1498 run_ret = kvm_vcpu_ioctl(env, KVM_RUN, 0);
1500 qemu_mutex_lock_iothread();
1501 kvm_arch_post_run(env, run);
1503 kvm_flush_coalesced_mmio_buffer();
1505 if (run_ret < 0) {
1506 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1507 DPRINTF("io window exit\n");
1508 ret = EXCP_INTERRUPT;
1509 break;
1511 fprintf(stderr, "error: kvm run failed %s\n",
1512 strerror(-run_ret));
1513 abort();
1516 switch (run->exit_reason) {
1517 case KVM_EXIT_IO:
1518 DPRINTF("handle_io\n");
1519 kvm_handle_io(run->io.port,
1520 (uint8_t *)run + run->io.data_offset,
1521 run->io.direction,
1522 run->io.size,
1523 run->io.count);
1524 ret = 0;
1525 break;
1526 case KVM_EXIT_MMIO:
1527 DPRINTF("handle_mmio\n");
1528 cpu_physical_memory_rw(run->mmio.phys_addr,
1529 run->mmio.data,
1530 run->mmio.len,
1531 run->mmio.is_write);
1532 ret = 0;
1533 break;
1534 case KVM_EXIT_IRQ_WINDOW_OPEN:
1535 DPRINTF("irq_window_open\n");
1536 ret = EXCP_INTERRUPT;
1537 break;
1538 case KVM_EXIT_SHUTDOWN:
1539 DPRINTF("shutdown\n");
1540 qemu_system_reset_request();
1541 ret = EXCP_INTERRUPT;
1542 break;
1543 case KVM_EXIT_UNKNOWN:
1544 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1545 (uint64_t)run->hw.hardware_exit_reason);
1546 ret = -1;
1547 break;
1548 case KVM_EXIT_INTERNAL_ERROR:
1549 ret = kvm_handle_internal_error(env, run);
1550 break;
1551 default:
1552 DPRINTF("kvm_arch_handle_exit\n");
1553 ret = kvm_arch_handle_exit(env, run);
1554 break;
1556 } while (ret == 0);
1558 if (ret < 0) {
1559 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1560 vm_stop(RUN_STATE_INTERNAL_ERROR);
1563 env->exit_request = 0;
1564 return ret;
1567 int kvm_ioctl(KVMState *s, int type, ...)
1569 int ret;
1570 void *arg;
1571 va_list ap;
1573 va_start(ap, type);
1574 arg = va_arg(ap, void *);
1575 va_end(ap);
1577 ret = ioctl(s->fd, type, arg);
1578 if (ret == -1) {
1579 ret = -errno;
1581 return ret;
1584 int kvm_vm_ioctl(KVMState *s, int type, ...)
1586 int ret;
1587 void *arg;
1588 va_list ap;
1590 va_start(ap, type);
1591 arg = va_arg(ap, void *);
1592 va_end(ap);
1594 ret = ioctl(s->vmfd, type, arg);
1595 if (ret == -1) {
1596 ret = -errno;
1598 return ret;
1601 int kvm_vcpu_ioctl(CPUArchState *env, int type, ...)
1603 int ret;
1604 void *arg;
1605 va_list ap;
1607 va_start(ap, type);
1608 arg = va_arg(ap, void *);
1609 va_end(ap);
1611 ret = ioctl(env->kvm_fd, type, arg);
1612 if (ret == -1) {
1613 ret = -errno;
1615 return ret;
1618 int kvm_has_sync_mmu(void)
1620 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1623 int kvm_has_vcpu_events(void)
1625 return kvm_state->vcpu_events;
1628 int kvm_has_robust_singlestep(void)
1630 return kvm_state->robust_singlestep;
1633 int kvm_has_debugregs(void)
1635 return kvm_state->debugregs;
1638 int kvm_has_xsave(void)
1640 return kvm_state->xsave;
1643 int kvm_has_xcrs(void)
1645 return kvm_state->xcrs;
1648 int kvm_has_pit_state2(void)
1650 return kvm_state->pit_state2;
1653 int kvm_has_many_ioeventfds(void)
1655 if (!kvm_enabled()) {
1656 return 0;
1658 return kvm_state->many_ioeventfds;
1661 int kvm_has_gsi_routing(void)
1663 #ifdef KVM_CAP_IRQ_ROUTING
1664 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
1665 #else
1666 return false;
1667 #endif
1670 int kvm_allows_irq0_override(void)
1672 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
1675 void *kvm_vmalloc(ram_addr_t size)
1677 #ifdef TARGET_S390X
1678 void *mem;
1680 mem = kvm_arch_vmalloc(size);
1681 if (mem) {
1682 return mem;
1684 #endif
1685 return qemu_vmalloc(size);
1688 void kvm_setup_guest_memory(void *start, size_t size)
1690 if (!kvm_has_sync_mmu()) {
1691 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1693 if (ret) {
1694 perror("qemu_madvise");
1695 fprintf(stderr,
1696 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1697 exit(1);
1702 #ifdef KVM_CAP_SET_GUEST_DEBUG
1703 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUArchState *env,
1704 target_ulong pc)
1706 struct kvm_sw_breakpoint *bp;
1708 QTAILQ_FOREACH(bp, &env->kvm_state->kvm_sw_breakpoints, entry) {
1709 if (bp->pc == pc) {
1710 return bp;
1713 return NULL;
1716 int kvm_sw_breakpoints_active(CPUArchState *env)
1718 return !QTAILQ_EMPTY(&env->kvm_state->kvm_sw_breakpoints);
1721 struct kvm_set_guest_debug_data {
1722 struct kvm_guest_debug dbg;
1723 CPUArchState *env;
1724 int err;
1727 static void kvm_invoke_set_guest_debug(void *data)
1729 struct kvm_set_guest_debug_data *dbg_data = data;
1730 CPUArchState *env = dbg_data->env;
1732 dbg_data->err = kvm_vcpu_ioctl(env, KVM_SET_GUEST_DEBUG, &dbg_data->dbg);
1735 int kvm_update_guest_debug(CPUArchState *env, unsigned long reinject_trap)
1737 struct kvm_set_guest_debug_data data;
1739 data.dbg.control = reinject_trap;
1741 if (env->singlestep_enabled) {
1742 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
1744 kvm_arch_update_guest_debug(env, &data.dbg);
1745 data.env = env;
1747 run_on_cpu(env, kvm_invoke_set_guest_debug, &data);
1748 return data.err;
1751 int kvm_insert_breakpoint(CPUArchState *current_env, target_ulong addr,
1752 target_ulong len, int type)
1754 struct kvm_sw_breakpoint *bp;
1755 CPUArchState *env;
1756 int err;
1758 if (type == GDB_BREAKPOINT_SW) {
1759 bp = kvm_find_sw_breakpoint(current_env, addr);
1760 if (bp) {
1761 bp->use_count++;
1762 return 0;
1765 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
1766 if (!bp) {
1767 return -ENOMEM;
1770 bp->pc = addr;
1771 bp->use_count = 1;
1772 err = kvm_arch_insert_sw_breakpoint(current_env, bp);
1773 if (err) {
1774 g_free(bp);
1775 return err;
1778 QTAILQ_INSERT_HEAD(&current_env->kvm_state->kvm_sw_breakpoints,
1779 bp, entry);
1780 } else {
1781 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
1782 if (err) {
1783 return err;
1787 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1788 err = kvm_update_guest_debug(env, 0);
1789 if (err) {
1790 return err;
1793 return 0;
1796 int kvm_remove_breakpoint(CPUArchState *current_env, target_ulong addr,
1797 target_ulong len, int type)
1799 struct kvm_sw_breakpoint *bp;
1800 CPUArchState *env;
1801 int err;
1803 if (type == GDB_BREAKPOINT_SW) {
1804 bp = kvm_find_sw_breakpoint(current_env, addr);
1805 if (!bp) {
1806 return -ENOENT;
1809 if (bp->use_count > 1) {
1810 bp->use_count--;
1811 return 0;
1814 err = kvm_arch_remove_sw_breakpoint(current_env, bp);
1815 if (err) {
1816 return err;
1819 QTAILQ_REMOVE(&current_env->kvm_state->kvm_sw_breakpoints, bp, entry);
1820 g_free(bp);
1821 } else {
1822 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
1823 if (err) {
1824 return err;
1828 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1829 err = kvm_update_guest_debug(env, 0);
1830 if (err) {
1831 return err;
1834 return 0;
1837 void kvm_remove_all_breakpoints(CPUArchState *current_env)
1839 struct kvm_sw_breakpoint *bp, *next;
1840 KVMState *s = current_env->kvm_state;
1841 CPUArchState *env;
1843 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
1844 if (kvm_arch_remove_sw_breakpoint(current_env, bp) != 0) {
1845 /* Try harder to find a CPU that currently sees the breakpoint. */
1846 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1847 if (kvm_arch_remove_sw_breakpoint(env, bp) == 0) {
1848 break;
1853 kvm_arch_remove_all_hw_breakpoints();
1855 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1856 kvm_update_guest_debug(env, 0);
1860 #else /* !KVM_CAP_SET_GUEST_DEBUG */
1862 int kvm_update_guest_debug(CPUArchState *env, unsigned long reinject_trap)
1864 return -EINVAL;
1867 int kvm_insert_breakpoint(CPUArchState *current_env, target_ulong addr,
1868 target_ulong len, int type)
1870 return -EINVAL;
1873 int kvm_remove_breakpoint(CPUArchState *current_env, target_ulong addr,
1874 target_ulong len, int type)
1876 return -EINVAL;
1879 void kvm_remove_all_breakpoints(CPUArchState *current_env)
1882 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
1884 int kvm_set_signal_mask(CPUArchState *env, const sigset_t *sigset)
1886 struct kvm_signal_mask *sigmask;
1887 int r;
1889 if (!sigset) {
1890 return kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, NULL);
1893 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
1895 sigmask->len = 8;
1896 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
1897 r = kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, sigmask);
1898 g_free(sigmask);
1900 return r;
1903 int kvm_set_ioeventfd_mmio(int fd, uint32_t addr, uint32_t val, bool assign,
1904 uint32_t size)
1906 int ret;
1907 struct kvm_ioeventfd iofd;
1909 iofd.datamatch = val;
1910 iofd.addr = addr;
1911 iofd.len = size;
1912 iofd.flags = KVM_IOEVENTFD_FLAG_DATAMATCH;
1913 iofd.fd = fd;
1915 if (!kvm_enabled()) {
1916 return -ENOSYS;
1919 if (!assign) {
1920 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1923 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
1925 if (ret < 0) {
1926 return -errno;
1929 return 0;
1932 int kvm_set_ioeventfd_pio_word(int fd, uint16_t addr, uint16_t val, bool assign)
1934 struct kvm_ioeventfd kick = {
1935 .datamatch = val,
1936 .addr = addr,
1937 .len = 2,
1938 .flags = KVM_IOEVENTFD_FLAG_DATAMATCH | KVM_IOEVENTFD_FLAG_PIO,
1939 .fd = fd,
1941 int r;
1942 if (!kvm_enabled()) {
1943 return -ENOSYS;
1945 if (!assign) {
1946 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1948 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
1949 if (r < 0) {
1950 return r;
1952 return 0;
1955 int kvm_on_sigbus_vcpu(CPUArchState *env, int code, void *addr)
1957 return kvm_arch_on_sigbus_vcpu(env, code, addr);
1960 int kvm_on_sigbus(int code, void *addr)
1962 return kvm_arch_on_sigbus(code, addr);