spapr_pci: Introduce a finish_realize() callback
[qemu/cris-port.git] / kvm-all.c
blob4e19eff0efeea85a47ab8b76b64601a2b6c73bf7
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/atomic.h"
25 #include "qemu/option.h"
26 #include "qemu/config-file.h"
27 #include "sysemu/sysemu.h"
28 #include "hw/hw.h"
29 #include "hw/pci/msi.h"
30 #include "hw/s390x/adapter.h"
31 #include "exec/gdbstub.h"
32 #include "sysemu/kvm.h"
33 #include "qemu/bswap.h"
34 #include "exec/memory.h"
35 #include "exec/ram_addr.h"
36 #include "exec/address-spaces.h"
37 #include "qemu/event_notifier.h"
38 #include "trace.h"
40 #include "hw/boards.h"
42 /* This check must be after config-host.h is included */
43 #ifdef CONFIG_EVENTFD
44 #include <sys/eventfd.h>
45 #endif
47 #ifdef CONFIG_VALGRIND_H
48 #include <valgrind/memcheck.h>
49 #endif
51 /* KVM uses PAGE_SIZE in its definition of COALESCED_MMIO_MAX */
52 #define PAGE_SIZE TARGET_PAGE_SIZE
54 //#define DEBUG_KVM
56 #ifdef DEBUG_KVM
57 #define DPRINTF(fmt, ...) \
58 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
59 #else
60 #define DPRINTF(fmt, ...) \
61 do { } while (0)
62 #endif
64 #define KVM_MSI_HASHTAB_SIZE 256
66 typedef struct KVMSlot
68 hwaddr start_addr;
69 ram_addr_t memory_size;
70 void *ram;
71 int slot;
72 int flags;
73 } KVMSlot;
75 typedef struct kvm_dirty_log KVMDirtyLog;
77 struct KVMState
79 KVMSlot *slots;
80 int nr_slots;
81 int fd;
82 int vmfd;
83 int coalesced_mmio;
84 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
85 bool coalesced_flush_in_progress;
86 int broken_set_mem_region;
87 int migration_log;
88 int vcpu_events;
89 int robust_singlestep;
90 int debugregs;
91 #ifdef KVM_CAP_SET_GUEST_DEBUG
92 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
93 #endif
94 int pit_state2;
95 int xsave, xcrs;
96 int many_ioeventfds;
97 int intx_set_mask;
98 /* The man page (and posix) say ioctl numbers are signed int, but
99 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
100 * unsigned, and treating them as signed here can break things */
101 unsigned irq_set_ioctl;
102 #ifdef KVM_CAP_IRQ_ROUTING
103 struct kvm_irq_routing *irq_routes;
104 int nr_allocated_irq_routes;
105 uint32_t *used_gsi_bitmap;
106 unsigned int gsi_count;
107 QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
108 bool direct_msi;
109 #endif
112 KVMState *kvm_state;
113 bool kvm_kernel_irqchip;
114 bool kvm_async_interrupts_allowed;
115 bool kvm_halt_in_kernel_allowed;
116 bool kvm_irqfds_allowed;
117 bool kvm_msi_via_irqfd_allowed;
118 bool kvm_gsi_routing_allowed;
119 bool kvm_gsi_direct_mapping;
120 bool kvm_allowed;
121 bool kvm_readonly_mem_allowed;
123 static const KVMCapabilityInfo kvm_required_capabilites[] = {
124 KVM_CAP_INFO(USER_MEMORY),
125 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
126 KVM_CAP_LAST_INFO
129 static KVMSlot *kvm_alloc_slot(KVMState *s)
131 int i;
133 for (i = 0; i < s->nr_slots; i++) {
134 if (s->slots[i].memory_size == 0) {
135 return &s->slots[i];
139 fprintf(stderr, "%s: no free slot available\n", __func__);
140 abort();
143 static KVMSlot *kvm_lookup_matching_slot(KVMState *s,
144 hwaddr start_addr,
145 hwaddr end_addr)
147 int i;
149 for (i = 0; i < s->nr_slots; i++) {
150 KVMSlot *mem = &s->slots[i];
152 if (start_addr == mem->start_addr &&
153 end_addr == mem->start_addr + mem->memory_size) {
154 return mem;
158 return NULL;
162 * Find overlapping slot with lowest start address
164 static KVMSlot *kvm_lookup_overlapping_slot(KVMState *s,
165 hwaddr start_addr,
166 hwaddr end_addr)
168 KVMSlot *found = NULL;
169 int i;
171 for (i = 0; i < s->nr_slots; i++) {
172 KVMSlot *mem = &s->slots[i];
174 if (mem->memory_size == 0 ||
175 (found && found->start_addr < mem->start_addr)) {
176 continue;
179 if (end_addr > mem->start_addr &&
180 start_addr < mem->start_addr + mem->memory_size) {
181 found = mem;
185 return found;
188 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
189 hwaddr *phys_addr)
191 int i;
193 for (i = 0; i < s->nr_slots; i++) {
194 KVMSlot *mem = &s->slots[i];
196 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
197 *phys_addr = mem->start_addr + (ram - mem->ram);
198 return 1;
202 return 0;
205 static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)
207 struct kvm_userspace_memory_region mem;
209 mem.slot = slot->slot;
210 mem.guest_phys_addr = slot->start_addr;
211 mem.userspace_addr = (unsigned long)slot->ram;
212 mem.flags = slot->flags;
213 if (s->migration_log) {
214 mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;
217 if (slot->memory_size && mem.flags & KVM_MEM_READONLY) {
218 /* Set the slot size to 0 before setting the slot to the desired
219 * value. This is needed based on KVM commit 75d61fbc. */
220 mem.memory_size = 0;
221 kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
223 mem.memory_size = slot->memory_size;
224 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
227 int kvm_init_vcpu(CPUState *cpu)
229 KVMState *s = kvm_state;
230 long mmap_size;
231 int ret;
233 DPRINTF("kvm_init_vcpu\n");
235 ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)kvm_arch_vcpu_id(cpu));
236 if (ret < 0) {
237 DPRINTF("kvm_create_vcpu failed\n");
238 goto err;
241 cpu->kvm_fd = ret;
242 cpu->kvm_state = s;
243 cpu->kvm_vcpu_dirty = true;
245 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
246 if (mmap_size < 0) {
247 ret = mmap_size;
248 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
249 goto err;
252 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
253 cpu->kvm_fd, 0);
254 if (cpu->kvm_run == MAP_FAILED) {
255 ret = -errno;
256 DPRINTF("mmap'ing vcpu state failed\n");
257 goto err;
260 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
261 s->coalesced_mmio_ring =
262 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
265 ret = kvm_arch_init_vcpu(cpu);
266 err:
267 return ret;
271 * dirty pages logging control
274 static int kvm_mem_flags(KVMState *s, bool log_dirty, bool readonly)
276 int flags = 0;
277 flags = log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
278 if (readonly && kvm_readonly_mem_allowed) {
279 flags |= KVM_MEM_READONLY;
281 return flags;
284 static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
286 KVMState *s = kvm_state;
287 int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
288 int old_flags;
290 old_flags = mem->flags;
292 flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty, false);
293 mem->flags = flags;
295 /* If nothing changed effectively, no need to issue ioctl */
296 if (s->migration_log) {
297 flags |= KVM_MEM_LOG_DIRTY_PAGES;
300 if (flags == old_flags) {
301 return 0;
304 return kvm_set_user_memory_region(s, mem);
307 static int kvm_dirty_pages_log_change(hwaddr phys_addr,
308 ram_addr_t size, bool log_dirty)
310 KVMState *s = kvm_state;
311 KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
313 if (mem == NULL) {
314 fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
315 TARGET_FMT_plx "\n", __func__, phys_addr,
316 (hwaddr)(phys_addr + size - 1));
317 return -EINVAL;
319 return kvm_slot_dirty_pages_log_change(mem, log_dirty);
322 static void kvm_log_start(MemoryListener *listener,
323 MemoryRegionSection *section)
325 int r;
327 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
328 int128_get64(section->size), true);
329 if (r < 0) {
330 abort();
334 static void kvm_log_stop(MemoryListener *listener,
335 MemoryRegionSection *section)
337 int r;
339 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
340 int128_get64(section->size), false);
341 if (r < 0) {
342 abort();
346 static int kvm_set_migration_log(int enable)
348 KVMState *s = kvm_state;
349 KVMSlot *mem;
350 int i, err;
352 s->migration_log = enable;
354 for (i = 0; i < s->nr_slots; i++) {
355 mem = &s->slots[i];
357 if (!mem->memory_size) {
358 continue;
360 if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
361 continue;
363 err = kvm_set_user_memory_region(s, mem);
364 if (err) {
365 return err;
368 return 0;
371 /* get kvm's dirty pages bitmap and update qemu's */
372 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
373 unsigned long *bitmap)
375 ram_addr_t start = section->offset_within_region + section->mr->ram_addr;
376 ram_addr_t pages = int128_get64(section->size) / getpagesize();
378 cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
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 hwaddr start_addr = section->offset_within_address_space;
401 hwaddr end_addr = start_addr + int128_get64(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 static void kvm_coalesce_mmio_region(MemoryListener *listener,
449 MemoryRegionSection *secion,
450 hwaddr start, hwaddr size)
452 KVMState *s = kvm_state;
454 if (s->coalesced_mmio) {
455 struct kvm_coalesced_mmio_zone zone;
457 zone.addr = start;
458 zone.size = size;
459 zone.pad = 0;
461 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
465 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
466 MemoryRegionSection *secion,
467 hwaddr start, hwaddr size)
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 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
482 int kvm_check_extension(KVMState *s, unsigned int extension)
484 int ret;
486 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
487 if (ret < 0) {
488 ret = 0;
491 return ret;
494 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
495 bool assign, uint32_t size, bool datamatch)
497 int ret;
498 struct kvm_ioeventfd iofd;
500 iofd.datamatch = datamatch ? val : 0;
501 iofd.addr = addr;
502 iofd.len = size;
503 iofd.flags = 0;
504 iofd.fd = fd;
506 if (!kvm_enabled()) {
507 return -ENOSYS;
510 if (datamatch) {
511 iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
513 if (!assign) {
514 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
517 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
519 if (ret < 0) {
520 return -errno;
523 return 0;
526 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
527 bool assign, uint32_t size, bool datamatch)
529 struct kvm_ioeventfd kick = {
530 .datamatch = datamatch ? val : 0,
531 .addr = addr,
532 .flags = KVM_IOEVENTFD_FLAG_PIO,
533 .len = size,
534 .fd = fd,
536 int r;
537 if (!kvm_enabled()) {
538 return -ENOSYS;
540 if (datamatch) {
541 kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
543 if (!assign) {
544 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
546 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
547 if (r < 0) {
548 return r;
550 return 0;
554 static int kvm_check_many_ioeventfds(void)
556 /* Userspace can use ioeventfd for io notification. This requires a host
557 * that supports eventfd(2) and an I/O thread; since eventfd does not
558 * support SIGIO it cannot interrupt the vcpu.
560 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
561 * can avoid creating too many ioeventfds.
563 #if defined(CONFIG_EVENTFD)
564 int ioeventfds[7];
565 int i, ret = 0;
566 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
567 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
568 if (ioeventfds[i] < 0) {
569 break;
571 ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
572 if (ret < 0) {
573 close(ioeventfds[i]);
574 break;
578 /* Decide whether many devices are supported or not */
579 ret = i == ARRAY_SIZE(ioeventfds);
581 while (i-- > 0) {
582 kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
583 close(ioeventfds[i]);
585 return ret;
586 #else
587 return 0;
588 #endif
591 static const KVMCapabilityInfo *
592 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
594 while (list->name) {
595 if (!kvm_check_extension(s, list->value)) {
596 return list;
598 list++;
600 return NULL;
603 static void kvm_set_phys_mem(MemoryRegionSection *section, bool add)
605 KVMState *s = kvm_state;
606 KVMSlot *mem, old;
607 int err;
608 MemoryRegion *mr = section->mr;
609 bool log_dirty = memory_region_is_logging(mr);
610 bool writeable = !mr->readonly && !mr->rom_device;
611 bool readonly_flag = mr->readonly || memory_region_is_romd(mr);
612 hwaddr start_addr = section->offset_within_address_space;
613 ram_addr_t size = int128_get64(section->size);
614 void *ram = NULL;
615 unsigned delta;
617 /* kvm works in page size chunks, but the function may be called
618 with sub-page size and unaligned start address. */
619 delta = TARGET_PAGE_ALIGN(size) - size;
620 if (delta > size) {
621 return;
623 start_addr += delta;
624 size -= delta;
625 size &= TARGET_PAGE_MASK;
626 if (!size || (start_addr & ~TARGET_PAGE_MASK)) {
627 return;
630 if (!memory_region_is_ram(mr)) {
631 if (writeable || !kvm_readonly_mem_allowed) {
632 return;
633 } else if (!mr->romd_mode) {
634 /* If the memory device is not in romd_mode, then we actually want
635 * to remove the kvm memory slot so all accesses will trap. */
636 add = false;
640 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
642 while (1) {
643 mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
644 if (!mem) {
645 break;
648 if (add && start_addr >= mem->start_addr &&
649 (start_addr + size <= mem->start_addr + mem->memory_size) &&
650 (ram - start_addr == mem->ram - mem->start_addr)) {
651 /* The new slot fits into the existing one and comes with
652 * identical parameters - update flags and done. */
653 kvm_slot_dirty_pages_log_change(mem, log_dirty);
654 return;
657 old = *mem;
659 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
660 kvm_physical_sync_dirty_bitmap(section);
663 /* unregister the overlapping slot */
664 mem->memory_size = 0;
665 err = kvm_set_user_memory_region(s, mem);
666 if (err) {
667 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
668 __func__, strerror(-err));
669 abort();
672 /* Workaround for older KVM versions: we can't join slots, even not by
673 * unregistering the previous ones and then registering the larger
674 * slot. We have to maintain the existing fragmentation. Sigh.
676 * This workaround assumes that the new slot starts at the same
677 * address as the first existing one. If not or if some overlapping
678 * slot comes around later, we will fail (not seen in practice so far)
679 * - and actually require a recent KVM version. */
680 if (s->broken_set_mem_region &&
681 old.start_addr == start_addr && old.memory_size < size && add) {
682 mem = kvm_alloc_slot(s);
683 mem->memory_size = old.memory_size;
684 mem->start_addr = old.start_addr;
685 mem->ram = old.ram;
686 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
688 err = kvm_set_user_memory_region(s, mem);
689 if (err) {
690 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
691 strerror(-err));
692 abort();
695 start_addr += old.memory_size;
696 ram += old.memory_size;
697 size -= old.memory_size;
698 continue;
701 /* register prefix slot */
702 if (old.start_addr < start_addr) {
703 mem = kvm_alloc_slot(s);
704 mem->memory_size = start_addr - old.start_addr;
705 mem->start_addr = old.start_addr;
706 mem->ram = old.ram;
707 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
709 err = kvm_set_user_memory_region(s, mem);
710 if (err) {
711 fprintf(stderr, "%s: error registering prefix slot: %s\n",
712 __func__, strerror(-err));
713 #ifdef TARGET_PPC
714 fprintf(stderr, "%s: This is probably because your kernel's " \
715 "PAGE_SIZE is too big. Please try to use 4k " \
716 "PAGE_SIZE!\n", __func__);
717 #endif
718 abort();
722 /* register suffix slot */
723 if (old.start_addr + old.memory_size > start_addr + size) {
724 ram_addr_t size_delta;
726 mem = kvm_alloc_slot(s);
727 mem->start_addr = start_addr + size;
728 size_delta = mem->start_addr - old.start_addr;
729 mem->memory_size = old.memory_size - size_delta;
730 mem->ram = old.ram + size_delta;
731 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
733 err = kvm_set_user_memory_region(s, mem);
734 if (err) {
735 fprintf(stderr, "%s: error registering suffix slot: %s\n",
736 __func__, strerror(-err));
737 abort();
742 /* in case the KVM bug workaround already "consumed" the new slot */
743 if (!size) {
744 return;
746 if (!add) {
747 return;
749 mem = kvm_alloc_slot(s);
750 mem->memory_size = size;
751 mem->start_addr = start_addr;
752 mem->ram = ram;
753 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
755 err = kvm_set_user_memory_region(s, mem);
756 if (err) {
757 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
758 strerror(-err));
759 abort();
763 static void kvm_region_add(MemoryListener *listener,
764 MemoryRegionSection *section)
766 memory_region_ref(section->mr);
767 kvm_set_phys_mem(section, true);
770 static void kvm_region_del(MemoryListener *listener,
771 MemoryRegionSection *section)
773 kvm_set_phys_mem(section, false);
774 memory_region_unref(section->mr);
777 static void kvm_log_sync(MemoryListener *listener,
778 MemoryRegionSection *section)
780 int r;
782 r = kvm_physical_sync_dirty_bitmap(section);
783 if (r < 0) {
784 abort();
788 static void kvm_log_global_start(struct MemoryListener *listener)
790 int r;
792 r = kvm_set_migration_log(1);
793 assert(r >= 0);
796 static void kvm_log_global_stop(struct MemoryListener *listener)
798 int r;
800 r = kvm_set_migration_log(0);
801 assert(r >= 0);
804 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
805 MemoryRegionSection *section,
806 bool match_data, uint64_t data,
807 EventNotifier *e)
809 int fd = event_notifier_get_fd(e);
810 int r;
812 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
813 data, true, int128_get64(section->size),
814 match_data);
815 if (r < 0) {
816 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
817 __func__, strerror(-r));
818 abort();
822 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
823 MemoryRegionSection *section,
824 bool match_data, uint64_t data,
825 EventNotifier *e)
827 int fd = event_notifier_get_fd(e);
828 int r;
830 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
831 data, false, int128_get64(section->size),
832 match_data);
833 if (r < 0) {
834 abort();
838 static void kvm_io_ioeventfd_add(MemoryListener *listener,
839 MemoryRegionSection *section,
840 bool match_data, uint64_t data,
841 EventNotifier *e)
843 int fd = event_notifier_get_fd(e);
844 int r;
846 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
847 data, true, int128_get64(section->size),
848 match_data);
849 if (r < 0) {
850 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
851 __func__, strerror(-r));
852 abort();
856 static void kvm_io_ioeventfd_del(MemoryListener *listener,
857 MemoryRegionSection *section,
858 bool match_data, uint64_t data,
859 EventNotifier *e)
862 int fd = event_notifier_get_fd(e);
863 int r;
865 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
866 data, false, int128_get64(section->size),
867 match_data);
868 if (r < 0) {
869 abort();
873 static MemoryListener kvm_memory_listener = {
874 .region_add = kvm_region_add,
875 .region_del = kvm_region_del,
876 .log_start = kvm_log_start,
877 .log_stop = kvm_log_stop,
878 .log_sync = kvm_log_sync,
879 .log_global_start = kvm_log_global_start,
880 .log_global_stop = kvm_log_global_stop,
881 .eventfd_add = kvm_mem_ioeventfd_add,
882 .eventfd_del = kvm_mem_ioeventfd_del,
883 .coalesced_mmio_add = kvm_coalesce_mmio_region,
884 .coalesced_mmio_del = kvm_uncoalesce_mmio_region,
885 .priority = 10,
888 static MemoryListener kvm_io_listener = {
889 .eventfd_add = kvm_io_ioeventfd_add,
890 .eventfd_del = kvm_io_ioeventfd_del,
891 .priority = 10,
894 static void kvm_handle_interrupt(CPUState *cpu, int mask)
896 cpu->interrupt_request |= mask;
898 if (!qemu_cpu_is_self(cpu)) {
899 qemu_cpu_kick(cpu);
903 int kvm_set_irq(KVMState *s, int irq, int level)
905 struct kvm_irq_level event;
906 int ret;
908 assert(kvm_async_interrupts_enabled());
910 event.level = level;
911 event.irq = irq;
912 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
913 if (ret < 0) {
914 perror("kvm_set_irq");
915 abort();
918 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
921 #ifdef KVM_CAP_IRQ_ROUTING
922 typedef struct KVMMSIRoute {
923 struct kvm_irq_routing_entry kroute;
924 QTAILQ_ENTRY(KVMMSIRoute) entry;
925 } KVMMSIRoute;
927 static void set_gsi(KVMState *s, unsigned int gsi)
929 s->used_gsi_bitmap[gsi / 32] |= 1U << (gsi % 32);
932 static void clear_gsi(KVMState *s, unsigned int gsi)
934 s->used_gsi_bitmap[gsi / 32] &= ~(1U << (gsi % 32));
937 void kvm_init_irq_routing(KVMState *s)
939 int gsi_count, i;
941 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING);
942 if (gsi_count > 0) {
943 unsigned int gsi_bits, i;
945 /* Round up so we can search ints using ffs */
946 gsi_bits = ALIGN(gsi_count, 32);
947 s->used_gsi_bitmap = g_malloc0(gsi_bits / 8);
948 s->gsi_count = gsi_count;
950 /* Mark any over-allocated bits as already in use */
951 for (i = gsi_count; i < gsi_bits; i++) {
952 set_gsi(s, i);
956 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
957 s->nr_allocated_irq_routes = 0;
959 if (!s->direct_msi) {
960 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
961 QTAILQ_INIT(&s->msi_hashtab[i]);
965 kvm_arch_init_irq_routing(s);
968 void kvm_irqchip_commit_routes(KVMState *s)
970 int ret;
972 s->irq_routes->flags = 0;
973 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
974 assert(ret == 0);
977 static void kvm_add_routing_entry(KVMState *s,
978 struct kvm_irq_routing_entry *entry)
980 struct kvm_irq_routing_entry *new;
981 int n, size;
983 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
984 n = s->nr_allocated_irq_routes * 2;
985 if (n < 64) {
986 n = 64;
988 size = sizeof(struct kvm_irq_routing);
989 size += n * sizeof(*new);
990 s->irq_routes = g_realloc(s->irq_routes, size);
991 s->nr_allocated_irq_routes = n;
993 n = s->irq_routes->nr++;
994 new = &s->irq_routes->entries[n];
996 *new = *entry;
998 set_gsi(s, entry->gsi);
1001 static int kvm_update_routing_entry(KVMState *s,
1002 struct kvm_irq_routing_entry *new_entry)
1004 struct kvm_irq_routing_entry *entry;
1005 int n;
1007 for (n = 0; n < s->irq_routes->nr; n++) {
1008 entry = &s->irq_routes->entries[n];
1009 if (entry->gsi != new_entry->gsi) {
1010 continue;
1013 if(!memcmp(entry, new_entry, sizeof *entry)) {
1014 return 0;
1017 *entry = *new_entry;
1019 kvm_irqchip_commit_routes(s);
1021 return 0;
1024 return -ESRCH;
1027 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1029 struct kvm_irq_routing_entry e = {};
1031 assert(pin < s->gsi_count);
1033 e.gsi = irq;
1034 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1035 e.flags = 0;
1036 e.u.irqchip.irqchip = irqchip;
1037 e.u.irqchip.pin = pin;
1038 kvm_add_routing_entry(s, &e);
1041 void kvm_irqchip_release_virq(KVMState *s, int virq)
1043 struct kvm_irq_routing_entry *e;
1044 int i;
1046 if (kvm_gsi_direct_mapping()) {
1047 return;
1050 for (i = 0; i < s->irq_routes->nr; i++) {
1051 e = &s->irq_routes->entries[i];
1052 if (e->gsi == virq) {
1053 s->irq_routes->nr--;
1054 *e = s->irq_routes->entries[s->irq_routes->nr];
1057 clear_gsi(s, virq);
1060 static unsigned int kvm_hash_msi(uint32_t data)
1062 /* This is optimized for IA32 MSI layout. However, no other arch shall
1063 * repeat the mistake of not providing a direct MSI injection API. */
1064 return data & 0xff;
1067 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1069 KVMMSIRoute *route, *next;
1070 unsigned int hash;
1072 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1073 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1074 kvm_irqchip_release_virq(s, route->kroute.gsi);
1075 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1076 g_free(route);
1081 static int kvm_irqchip_get_virq(KVMState *s)
1083 uint32_t *word = s->used_gsi_bitmap;
1084 int max_words = ALIGN(s->gsi_count, 32) / 32;
1085 int i, bit;
1086 bool retry = true;
1088 again:
1089 /* Return the lowest unused GSI in the bitmap */
1090 for (i = 0; i < max_words; i++) {
1091 bit = ffs(~word[i]);
1092 if (!bit) {
1093 continue;
1096 return bit - 1 + i * 32;
1098 if (!s->direct_msi && retry) {
1099 retry = false;
1100 kvm_flush_dynamic_msi_routes(s);
1101 goto again;
1103 return -ENOSPC;
1107 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1109 unsigned int hash = kvm_hash_msi(msg.data);
1110 KVMMSIRoute *route;
1112 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1113 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1114 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1115 route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1116 return route;
1119 return NULL;
1122 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1124 struct kvm_msi msi;
1125 KVMMSIRoute *route;
1127 if (s->direct_msi) {
1128 msi.address_lo = (uint32_t)msg.address;
1129 msi.address_hi = msg.address >> 32;
1130 msi.data = le32_to_cpu(msg.data);
1131 msi.flags = 0;
1132 memset(msi.pad, 0, sizeof(msi.pad));
1134 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1137 route = kvm_lookup_msi_route(s, msg);
1138 if (!route) {
1139 int virq;
1141 virq = kvm_irqchip_get_virq(s);
1142 if (virq < 0) {
1143 return virq;
1146 route = g_malloc0(sizeof(KVMMSIRoute));
1147 route->kroute.gsi = virq;
1148 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1149 route->kroute.flags = 0;
1150 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1151 route->kroute.u.msi.address_hi = msg.address >> 32;
1152 route->kroute.u.msi.data = le32_to_cpu(msg.data);
1154 kvm_add_routing_entry(s, &route->kroute);
1155 kvm_irqchip_commit_routes(s);
1157 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1158 entry);
1161 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1163 return kvm_set_irq(s, route->kroute.gsi, 1);
1166 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1168 struct kvm_irq_routing_entry kroute = {};
1169 int virq;
1171 if (kvm_gsi_direct_mapping()) {
1172 return msg.data & 0xffff;
1175 if (!kvm_gsi_routing_enabled()) {
1176 return -ENOSYS;
1179 virq = kvm_irqchip_get_virq(s);
1180 if (virq < 0) {
1181 return virq;
1184 kroute.gsi = virq;
1185 kroute.type = KVM_IRQ_ROUTING_MSI;
1186 kroute.flags = 0;
1187 kroute.u.msi.address_lo = (uint32_t)msg.address;
1188 kroute.u.msi.address_hi = msg.address >> 32;
1189 kroute.u.msi.data = le32_to_cpu(msg.data);
1191 kvm_add_routing_entry(s, &kroute);
1192 kvm_irqchip_commit_routes(s);
1194 return virq;
1197 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1199 struct kvm_irq_routing_entry kroute = {};
1201 if (kvm_gsi_direct_mapping()) {
1202 return 0;
1205 if (!kvm_irqchip_in_kernel()) {
1206 return -ENOSYS;
1209 kroute.gsi = virq;
1210 kroute.type = KVM_IRQ_ROUTING_MSI;
1211 kroute.flags = 0;
1212 kroute.u.msi.address_lo = (uint32_t)msg.address;
1213 kroute.u.msi.address_hi = msg.address >> 32;
1214 kroute.u.msi.data = le32_to_cpu(msg.data);
1216 return kvm_update_routing_entry(s, &kroute);
1219 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int rfd, int virq,
1220 bool assign)
1222 struct kvm_irqfd irqfd = {
1223 .fd = fd,
1224 .gsi = virq,
1225 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1228 if (rfd != -1) {
1229 irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1230 irqfd.resamplefd = rfd;
1233 if (!kvm_irqfds_enabled()) {
1234 return -ENOSYS;
1237 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1240 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1242 struct kvm_irq_routing_entry kroute;
1243 int virq;
1245 if (!kvm_gsi_routing_enabled()) {
1246 return -ENOSYS;
1249 virq = kvm_irqchip_get_virq(s);
1250 if (virq < 0) {
1251 return virq;
1254 kroute.gsi = virq;
1255 kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1256 kroute.flags = 0;
1257 kroute.u.adapter.summary_addr = adapter->summary_addr;
1258 kroute.u.adapter.ind_addr = adapter->ind_addr;
1259 kroute.u.adapter.summary_offset = adapter->summary_offset;
1260 kroute.u.adapter.ind_offset = adapter->ind_offset;
1261 kroute.u.adapter.adapter_id = adapter->adapter_id;
1263 kvm_add_routing_entry(s, &kroute);
1264 kvm_irqchip_commit_routes(s);
1266 return virq;
1269 #else /* !KVM_CAP_IRQ_ROUTING */
1271 void kvm_init_irq_routing(KVMState *s)
1275 void kvm_irqchip_release_virq(KVMState *s, int virq)
1279 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1281 abort();
1284 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1286 return -ENOSYS;
1289 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1291 return -ENOSYS;
1294 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1296 abort();
1299 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1301 return -ENOSYS;
1303 #endif /* !KVM_CAP_IRQ_ROUTING */
1305 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1306 EventNotifier *rn, int virq)
1308 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n),
1309 rn ? event_notifier_get_fd(rn) : -1, virq, true);
1312 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n, int virq)
1314 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), -1, virq,
1315 false);
1318 static int kvm_irqchip_create(KVMState *s)
1320 int ret;
1322 if (!qemu_opt_get_bool(qemu_get_machine_opts(), "kernel_irqchip", true) ||
1323 (!kvm_check_extension(s, KVM_CAP_IRQCHIP) &&
1324 (kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0) < 0))) {
1325 return 0;
1328 /* First probe and see if there's a arch-specific hook to create the
1329 * in-kernel irqchip for us */
1330 ret = kvm_arch_irqchip_create(s);
1331 if (ret < 0) {
1332 return ret;
1333 } else if (ret == 0) {
1334 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1335 if (ret < 0) {
1336 fprintf(stderr, "Create kernel irqchip failed\n");
1337 return ret;
1341 kvm_kernel_irqchip = true;
1342 /* If we have an in-kernel IRQ chip then we must have asynchronous
1343 * interrupt delivery (though the reverse is not necessarily true)
1345 kvm_async_interrupts_allowed = true;
1346 kvm_halt_in_kernel_allowed = true;
1348 kvm_init_irq_routing(s);
1350 return 0;
1353 /* Find number of supported CPUs using the recommended
1354 * procedure from the kernel API documentation to cope with
1355 * older kernels that may be missing capabilities.
1357 static int kvm_recommended_vcpus(KVMState *s)
1359 int ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
1360 return (ret) ? ret : 4;
1363 static int kvm_max_vcpus(KVMState *s)
1365 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1366 return (ret) ? ret : kvm_recommended_vcpus(s);
1369 int kvm_init(MachineClass *mc)
1371 static const char upgrade_note[] =
1372 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1373 "(see http://sourceforge.net/projects/kvm).\n";
1374 struct {
1375 const char *name;
1376 int num;
1377 } num_cpus[] = {
1378 { "SMP", smp_cpus },
1379 { "hotpluggable", max_cpus },
1380 { NULL, }
1381 }, *nc = num_cpus;
1382 int soft_vcpus_limit, hard_vcpus_limit;
1383 KVMState *s;
1384 const KVMCapabilityInfo *missing_cap;
1385 int ret;
1386 int i, type = 0;
1387 const char *kvm_type;
1389 s = g_malloc0(sizeof(KVMState));
1392 * On systems where the kernel can support different base page
1393 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1394 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1395 * page size for the system though.
1397 assert(TARGET_PAGE_SIZE <= getpagesize());
1398 page_size_init();
1400 #ifdef KVM_CAP_SET_GUEST_DEBUG
1401 QTAILQ_INIT(&s->kvm_sw_breakpoints);
1402 #endif
1403 s->vmfd = -1;
1404 s->fd = qemu_open("/dev/kvm", O_RDWR);
1405 if (s->fd == -1) {
1406 fprintf(stderr, "Could not access KVM kernel module: %m\n");
1407 ret = -errno;
1408 goto err;
1411 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1412 if (ret < KVM_API_VERSION) {
1413 if (ret >= 0) {
1414 ret = -EINVAL;
1416 fprintf(stderr, "kvm version too old\n");
1417 goto err;
1420 if (ret > KVM_API_VERSION) {
1421 ret = -EINVAL;
1422 fprintf(stderr, "kvm version not supported\n");
1423 goto err;
1426 s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
1428 /* If unspecified, use the default value */
1429 if (!s->nr_slots) {
1430 s->nr_slots = 32;
1433 s->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
1435 for (i = 0; i < s->nr_slots; i++) {
1436 s->slots[i].slot = i;
1439 /* check the vcpu limits */
1440 soft_vcpus_limit = kvm_recommended_vcpus(s);
1441 hard_vcpus_limit = kvm_max_vcpus(s);
1443 while (nc->name) {
1444 if (nc->num > soft_vcpus_limit) {
1445 fprintf(stderr,
1446 "Warning: Number of %s cpus requested (%d) exceeds "
1447 "the recommended cpus supported by KVM (%d)\n",
1448 nc->name, nc->num, soft_vcpus_limit);
1450 if (nc->num > hard_vcpus_limit) {
1451 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
1452 "the maximum cpus supported by KVM (%d)\n",
1453 nc->name, nc->num, hard_vcpus_limit);
1454 exit(1);
1457 nc++;
1460 kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1461 if (mc->kvm_type) {
1462 type = mc->kvm_type(kvm_type);
1463 } else if (kvm_type) {
1464 ret = -EINVAL;
1465 fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1466 goto err;
1469 do {
1470 ret = kvm_ioctl(s, KVM_CREATE_VM, type);
1471 } while (ret == -EINTR);
1473 if (ret < 0) {
1474 fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
1475 strerror(-ret));
1477 #ifdef TARGET_S390X
1478 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
1479 "your host kernel command line\n");
1480 #endif
1481 goto err;
1484 s->vmfd = ret;
1485 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1486 if (!missing_cap) {
1487 missing_cap =
1488 kvm_check_extension_list(s, kvm_arch_required_capabilities);
1490 if (missing_cap) {
1491 ret = -EINVAL;
1492 fprintf(stderr, "kvm does not support %s\n%s",
1493 missing_cap->name, upgrade_note);
1494 goto err;
1497 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1499 s->broken_set_mem_region = 1;
1500 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
1501 if (ret > 0) {
1502 s->broken_set_mem_region = 0;
1505 #ifdef KVM_CAP_VCPU_EVENTS
1506 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1507 #endif
1509 s->robust_singlestep =
1510 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1512 #ifdef KVM_CAP_DEBUGREGS
1513 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1514 #endif
1516 #ifdef KVM_CAP_XSAVE
1517 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1518 #endif
1520 #ifdef KVM_CAP_XCRS
1521 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1522 #endif
1524 #ifdef KVM_CAP_PIT_STATE2
1525 s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1526 #endif
1528 #ifdef KVM_CAP_IRQ_ROUTING
1529 s->direct_msi = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1530 #endif
1532 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1534 s->irq_set_ioctl = KVM_IRQ_LINE;
1535 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1536 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1539 #ifdef KVM_CAP_READONLY_MEM
1540 kvm_readonly_mem_allowed =
1541 (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1542 #endif
1544 ret = kvm_arch_init(s);
1545 if (ret < 0) {
1546 goto err;
1549 ret = kvm_irqchip_create(s);
1550 if (ret < 0) {
1551 goto err;
1554 kvm_state = s;
1555 memory_listener_register(&kvm_memory_listener, &address_space_memory);
1556 memory_listener_register(&kvm_io_listener, &address_space_io);
1558 s->many_ioeventfds = kvm_check_many_ioeventfds();
1560 cpu_interrupt_handler = kvm_handle_interrupt;
1562 return 0;
1564 err:
1565 assert(ret < 0);
1566 if (s->vmfd >= 0) {
1567 close(s->vmfd);
1569 if (s->fd != -1) {
1570 close(s->fd);
1572 g_free(s->slots);
1573 g_free(s);
1575 return ret;
1578 static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
1579 uint32_t count)
1581 int i;
1582 uint8_t *ptr = data;
1584 for (i = 0; i < count; i++) {
1585 address_space_rw(&address_space_io, port, ptr, size,
1586 direction == KVM_EXIT_IO_OUT);
1587 ptr += size;
1591 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
1593 fprintf(stderr, "KVM internal error. Suberror: %d\n",
1594 run->internal.suberror);
1596 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1597 int i;
1599 for (i = 0; i < run->internal.ndata; ++i) {
1600 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1601 i, (uint64_t)run->internal.data[i]);
1604 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1605 fprintf(stderr, "emulation failure\n");
1606 if (!kvm_arch_stop_on_emulation_error(cpu)) {
1607 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1608 return EXCP_INTERRUPT;
1611 /* FIXME: Should trigger a qmp message to let management know
1612 * something went wrong.
1614 return -1;
1617 void kvm_flush_coalesced_mmio_buffer(void)
1619 KVMState *s = kvm_state;
1621 if (s->coalesced_flush_in_progress) {
1622 return;
1625 s->coalesced_flush_in_progress = true;
1627 if (s->coalesced_mmio_ring) {
1628 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1629 while (ring->first != ring->last) {
1630 struct kvm_coalesced_mmio *ent;
1632 ent = &ring->coalesced_mmio[ring->first];
1634 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1635 smp_wmb();
1636 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1640 s->coalesced_flush_in_progress = false;
1643 static void do_kvm_cpu_synchronize_state(void *arg)
1645 CPUState *cpu = arg;
1647 if (!cpu->kvm_vcpu_dirty) {
1648 kvm_arch_get_registers(cpu);
1649 cpu->kvm_vcpu_dirty = true;
1653 void kvm_cpu_synchronize_state(CPUState *cpu)
1655 if (!cpu->kvm_vcpu_dirty) {
1656 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, cpu);
1660 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
1662 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1663 cpu->kvm_vcpu_dirty = false;
1666 void kvm_cpu_synchronize_post_init(CPUState *cpu)
1668 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1669 cpu->kvm_vcpu_dirty = false;
1672 int kvm_cpu_exec(CPUState *cpu)
1674 struct kvm_run *run = cpu->kvm_run;
1675 int ret, run_ret;
1677 DPRINTF("kvm_cpu_exec()\n");
1679 if (kvm_arch_process_async_events(cpu)) {
1680 cpu->exit_request = 0;
1681 return EXCP_HLT;
1684 do {
1685 if (cpu->kvm_vcpu_dirty) {
1686 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1687 cpu->kvm_vcpu_dirty = false;
1690 kvm_arch_pre_run(cpu, run);
1691 if (cpu->exit_request) {
1692 DPRINTF("interrupt exit requested\n");
1694 * KVM requires us to reenter the kernel after IO exits to complete
1695 * instruction emulation. This self-signal will ensure that we
1696 * leave ASAP again.
1698 qemu_cpu_kick_self();
1700 qemu_mutex_unlock_iothread();
1702 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
1704 qemu_mutex_lock_iothread();
1705 kvm_arch_post_run(cpu, run);
1707 if (run_ret < 0) {
1708 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1709 DPRINTF("io window exit\n");
1710 ret = EXCP_INTERRUPT;
1711 break;
1713 fprintf(stderr, "error: kvm run failed %s\n",
1714 strerror(-run_ret));
1715 abort();
1718 trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
1719 switch (run->exit_reason) {
1720 case KVM_EXIT_IO:
1721 DPRINTF("handle_io\n");
1722 kvm_handle_io(run->io.port,
1723 (uint8_t *)run + run->io.data_offset,
1724 run->io.direction,
1725 run->io.size,
1726 run->io.count);
1727 ret = 0;
1728 break;
1729 case KVM_EXIT_MMIO:
1730 DPRINTF("handle_mmio\n");
1731 cpu_physical_memory_rw(run->mmio.phys_addr,
1732 run->mmio.data,
1733 run->mmio.len,
1734 run->mmio.is_write);
1735 ret = 0;
1736 break;
1737 case KVM_EXIT_IRQ_WINDOW_OPEN:
1738 DPRINTF("irq_window_open\n");
1739 ret = EXCP_INTERRUPT;
1740 break;
1741 case KVM_EXIT_SHUTDOWN:
1742 DPRINTF("shutdown\n");
1743 qemu_system_reset_request();
1744 ret = EXCP_INTERRUPT;
1745 break;
1746 case KVM_EXIT_UNKNOWN:
1747 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1748 (uint64_t)run->hw.hardware_exit_reason);
1749 ret = -1;
1750 break;
1751 case KVM_EXIT_INTERNAL_ERROR:
1752 ret = kvm_handle_internal_error(cpu, run);
1753 break;
1754 default:
1755 DPRINTF("kvm_arch_handle_exit\n");
1756 ret = kvm_arch_handle_exit(cpu, run);
1757 break;
1759 } while (ret == 0);
1761 if (ret < 0) {
1762 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1763 vm_stop(RUN_STATE_INTERNAL_ERROR);
1766 cpu->exit_request = 0;
1767 return ret;
1770 int kvm_ioctl(KVMState *s, int type, ...)
1772 int ret;
1773 void *arg;
1774 va_list ap;
1776 va_start(ap, type);
1777 arg = va_arg(ap, void *);
1778 va_end(ap);
1780 trace_kvm_ioctl(type, arg);
1781 ret = ioctl(s->fd, type, arg);
1782 if (ret == -1) {
1783 ret = -errno;
1785 return ret;
1788 int kvm_vm_ioctl(KVMState *s, int type, ...)
1790 int ret;
1791 void *arg;
1792 va_list ap;
1794 va_start(ap, type);
1795 arg = va_arg(ap, void *);
1796 va_end(ap);
1798 trace_kvm_vm_ioctl(type, arg);
1799 ret = ioctl(s->vmfd, type, arg);
1800 if (ret == -1) {
1801 ret = -errno;
1803 return ret;
1806 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
1808 int ret;
1809 void *arg;
1810 va_list ap;
1812 va_start(ap, type);
1813 arg = va_arg(ap, void *);
1814 va_end(ap);
1816 trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
1817 ret = ioctl(cpu->kvm_fd, type, arg);
1818 if (ret == -1) {
1819 ret = -errno;
1821 return ret;
1824 int kvm_device_ioctl(int fd, int type, ...)
1826 int ret;
1827 void *arg;
1828 va_list ap;
1830 va_start(ap, type);
1831 arg = va_arg(ap, void *);
1832 va_end(ap);
1834 trace_kvm_device_ioctl(fd, type, arg);
1835 ret = ioctl(fd, type, arg);
1836 if (ret == -1) {
1837 ret = -errno;
1839 return ret;
1842 int kvm_has_sync_mmu(void)
1844 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1847 int kvm_has_vcpu_events(void)
1849 return kvm_state->vcpu_events;
1852 int kvm_has_robust_singlestep(void)
1854 return kvm_state->robust_singlestep;
1857 int kvm_has_debugregs(void)
1859 return kvm_state->debugregs;
1862 int kvm_has_xsave(void)
1864 return kvm_state->xsave;
1867 int kvm_has_xcrs(void)
1869 return kvm_state->xcrs;
1872 int kvm_has_pit_state2(void)
1874 return kvm_state->pit_state2;
1877 int kvm_has_many_ioeventfds(void)
1879 if (!kvm_enabled()) {
1880 return 0;
1882 return kvm_state->many_ioeventfds;
1885 int kvm_has_gsi_routing(void)
1887 #ifdef KVM_CAP_IRQ_ROUTING
1888 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
1889 #else
1890 return false;
1891 #endif
1894 int kvm_has_intx_set_mask(void)
1896 return kvm_state->intx_set_mask;
1899 void kvm_setup_guest_memory(void *start, size_t size)
1901 #ifdef CONFIG_VALGRIND_H
1902 VALGRIND_MAKE_MEM_DEFINED(start, size);
1903 #endif
1904 if (!kvm_has_sync_mmu()) {
1905 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1907 if (ret) {
1908 perror("qemu_madvise");
1909 fprintf(stderr,
1910 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1911 exit(1);
1916 #ifdef KVM_CAP_SET_GUEST_DEBUG
1917 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
1918 target_ulong pc)
1920 struct kvm_sw_breakpoint *bp;
1922 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
1923 if (bp->pc == pc) {
1924 return bp;
1927 return NULL;
1930 int kvm_sw_breakpoints_active(CPUState *cpu)
1932 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
1935 struct kvm_set_guest_debug_data {
1936 struct kvm_guest_debug dbg;
1937 CPUState *cpu;
1938 int err;
1941 static void kvm_invoke_set_guest_debug(void *data)
1943 struct kvm_set_guest_debug_data *dbg_data = data;
1945 dbg_data->err = kvm_vcpu_ioctl(dbg_data->cpu, KVM_SET_GUEST_DEBUG,
1946 &dbg_data->dbg);
1949 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
1951 struct kvm_set_guest_debug_data data;
1953 data.dbg.control = reinject_trap;
1955 if (cpu->singlestep_enabled) {
1956 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
1958 kvm_arch_update_guest_debug(cpu, &data.dbg);
1959 data.cpu = cpu;
1961 run_on_cpu(cpu, kvm_invoke_set_guest_debug, &data);
1962 return data.err;
1965 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
1966 target_ulong len, int type)
1968 struct kvm_sw_breakpoint *bp;
1969 int err;
1971 if (type == GDB_BREAKPOINT_SW) {
1972 bp = kvm_find_sw_breakpoint(cpu, addr);
1973 if (bp) {
1974 bp->use_count++;
1975 return 0;
1978 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
1979 if (!bp) {
1980 return -ENOMEM;
1983 bp->pc = addr;
1984 bp->use_count = 1;
1985 err = kvm_arch_insert_sw_breakpoint(cpu, bp);
1986 if (err) {
1987 g_free(bp);
1988 return err;
1991 QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
1992 } else {
1993 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
1994 if (err) {
1995 return err;
1999 CPU_FOREACH(cpu) {
2000 err = kvm_update_guest_debug(cpu, 0);
2001 if (err) {
2002 return err;
2005 return 0;
2008 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2009 target_ulong len, int type)
2011 struct kvm_sw_breakpoint *bp;
2012 int err;
2014 if (type == GDB_BREAKPOINT_SW) {
2015 bp = kvm_find_sw_breakpoint(cpu, addr);
2016 if (!bp) {
2017 return -ENOENT;
2020 if (bp->use_count > 1) {
2021 bp->use_count--;
2022 return 0;
2025 err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2026 if (err) {
2027 return err;
2030 QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2031 g_free(bp);
2032 } else {
2033 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2034 if (err) {
2035 return err;
2039 CPU_FOREACH(cpu) {
2040 err = kvm_update_guest_debug(cpu, 0);
2041 if (err) {
2042 return err;
2045 return 0;
2048 void kvm_remove_all_breakpoints(CPUState *cpu)
2050 struct kvm_sw_breakpoint *bp, *next;
2051 KVMState *s = cpu->kvm_state;
2053 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2054 if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2055 /* Try harder to find a CPU that currently sees the breakpoint. */
2056 CPU_FOREACH(cpu) {
2057 if (kvm_arch_remove_sw_breakpoint(cpu, bp) == 0) {
2058 break;
2062 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2063 g_free(bp);
2065 kvm_arch_remove_all_hw_breakpoints();
2067 CPU_FOREACH(cpu) {
2068 kvm_update_guest_debug(cpu, 0);
2072 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2074 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2076 return -EINVAL;
2079 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2080 target_ulong len, int type)
2082 return -EINVAL;
2085 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2086 target_ulong len, int type)
2088 return -EINVAL;
2091 void kvm_remove_all_breakpoints(CPUState *cpu)
2094 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2096 int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2098 struct kvm_signal_mask *sigmask;
2099 int r;
2101 if (!sigset) {
2102 return kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, NULL);
2105 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2107 sigmask->len = 8;
2108 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2109 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2110 g_free(sigmask);
2112 return r;
2114 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2116 return kvm_arch_on_sigbus_vcpu(cpu, code, addr);
2119 int kvm_on_sigbus(int code, void *addr)
2121 return kvm_arch_on_sigbus(code, addr);
2124 int kvm_create_device(KVMState *s, uint64_t type, bool test)
2126 int ret;
2127 struct kvm_create_device create_dev;
2129 create_dev.type = type;
2130 create_dev.fd = -1;
2131 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2133 if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2134 return -ENOTSUP;
2137 ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2138 if (ret) {
2139 return ret;
2142 return test ? 0 : create_dev.fd;
2145 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2147 struct kvm_one_reg reg;
2148 int r;
2150 reg.id = id;
2151 reg.addr = (uintptr_t) source;
2152 r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
2153 if (r) {
2154 trace_kvm_failed_reg_set(id, strerror(r));
2156 return r;
2159 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2161 struct kvm_one_reg reg;
2162 int r;
2164 reg.id = id;
2165 reg.addr = (uintptr_t) target;
2166 r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
2167 if (r) {
2168 trace_kvm_failed_reg_get(id, strerror(r));
2170 return r;