pc-dimm: Don't check dimm->node when there is non-NUMA config
[qemu/rayw.git] / kvm-all.c
blob4afcd0551bb2dfba2a418cea41c36deb6708e4da
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 /* KVM uses PAGE_SIZE in its definition of COALESCED_MMIO_MAX */
48 #define PAGE_SIZE TARGET_PAGE_SIZE
50 //#define DEBUG_KVM
52 #ifdef DEBUG_KVM
53 #define DPRINTF(fmt, ...) \
54 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
55 #else
56 #define DPRINTF(fmt, ...) \
57 do { } while (0)
58 #endif
60 #define KVM_MSI_HASHTAB_SIZE 256
62 typedef struct KVMSlot
64 hwaddr start_addr;
65 ram_addr_t memory_size;
66 void *ram;
67 int slot;
68 int flags;
69 } KVMSlot;
71 typedef struct kvm_dirty_log KVMDirtyLog;
73 struct KVMState
75 KVMSlot *slots;
76 int nr_slots;
77 int fd;
78 int vmfd;
79 int coalesced_mmio;
80 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
81 bool coalesced_flush_in_progress;
82 int broken_set_mem_region;
83 int migration_log;
84 int vcpu_events;
85 int robust_singlestep;
86 int debugregs;
87 #ifdef KVM_CAP_SET_GUEST_DEBUG
88 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
89 #endif
90 int pit_state2;
91 int xsave, xcrs;
92 int many_ioeventfds;
93 int intx_set_mask;
94 /* The man page (and posix) say ioctl numbers are signed int, but
95 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
96 * unsigned, and treating them as signed here can break things */
97 unsigned irq_set_ioctl;
98 unsigned int sigmask_len;
99 #ifdef KVM_CAP_IRQ_ROUTING
100 struct kvm_irq_routing *irq_routes;
101 int nr_allocated_irq_routes;
102 uint32_t *used_gsi_bitmap;
103 unsigned int gsi_count;
104 QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
105 bool direct_msi;
106 #endif
109 KVMState *kvm_state;
110 bool kvm_kernel_irqchip;
111 bool kvm_async_interrupts_allowed;
112 bool kvm_halt_in_kernel_allowed;
113 bool kvm_eventfds_allowed;
114 bool kvm_irqfds_allowed;
115 bool kvm_msi_via_irqfd_allowed;
116 bool kvm_gsi_routing_allowed;
117 bool kvm_gsi_direct_mapping;
118 bool kvm_allowed;
119 bool kvm_readonly_mem_allowed;
121 static const KVMCapabilityInfo kvm_required_capabilites[] = {
122 KVM_CAP_INFO(USER_MEMORY),
123 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
124 KVM_CAP_LAST_INFO
127 static KVMSlot *kvm_alloc_slot(KVMState *s)
129 int i;
131 for (i = 0; i < s->nr_slots; i++) {
132 if (s->slots[i].memory_size == 0) {
133 return &s->slots[i];
137 fprintf(stderr, "%s: no free slot available\n", __func__);
138 abort();
141 static KVMSlot *kvm_lookup_matching_slot(KVMState *s,
142 hwaddr start_addr,
143 hwaddr end_addr)
145 int i;
147 for (i = 0; i < s->nr_slots; i++) {
148 KVMSlot *mem = &s->slots[i];
150 if (start_addr == mem->start_addr &&
151 end_addr == mem->start_addr + mem->memory_size) {
152 return mem;
156 return NULL;
160 * Find overlapping slot with lowest start address
162 static KVMSlot *kvm_lookup_overlapping_slot(KVMState *s,
163 hwaddr start_addr,
164 hwaddr end_addr)
166 KVMSlot *found = NULL;
167 int i;
169 for (i = 0; i < s->nr_slots; i++) {
170 KVMSlot *mem = &s->slots[i];
172 if (mem->memory_size == 0 ||
173 (found && found->start_addr < mem->start_addr)) {
174 continue;
177 if (end_addr > mem->start_addr &&
178 start_addr < mem->start_addr + mem->memory_size) {
179 found = mem;
183 return found;
186 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
187 hwaddr *phys_addr)
189 int i;
191 for (i = 0; i < s->nr_slots; i++) {
192 KVMSlot *mem = &s->slots[i];
194 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
195 *phys_addr = mem->start_addr + (ram - mem->ram);
196 return 1;
200 return 0;
203 static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)
205 struct kvm_userspace_memory_region mem;
207 mem.slot = slot->slot;
208 mem.guest_phys_addr = slot->start_addr;
209 mem.userspace_addr = (unsigned long)slot->ram;
210 mem.flags = slot->flags;
211 if (s->migration_log) {
212 mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;
215 if (slot->memory_size && mem.flags & KVM_MEM_READONLY) {
216 /* Set the slot size to 0 before setting the slot to the desired
217 * value. This is needed based on KVM commit 75d61fbc. */
218 mem.memory_size = 0;
219 kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
221 mem.memory_size = slot->memory_size;
222 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
225 int kvm_init_vcpu(CPUState *cpu)
227 KVMState *s = kvm_state;
228 long mmap_size;
229 int ret;
231 DPRINTF("kvm_init_vcpu\n");
233 ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)kvm_arch_vcpu_id(cpu));
234 if (ret < 0) {
235 DPRINTF("kvm_create_vcpu failed\n");
236 goto err;
239 cpu->kvm_fd = ret;
240 cpu->kvm_state = s;
241 cpu->kvm_vcpu_dirty = true;
243 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
244 if (mmap_size < 0) {
245 ret = mmap_size;
246 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
247 goto err;
250 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
251 cpu->kvm_fd, 0);
252 if (cpu->kvm_run == MAP_FAILED) {
253 ret = -errno;
254 DPRINTF("mmap'ing vcpu state failed\n");
255 goto err;
258 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
259 s->coalesced_mmio_ring =
260 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
263 ret = kvm_arch_init_vcpu(cpu);
264 err:
265 return ret;
269 * dirty pages logging control
272 static int kvm_mem_flags(KVMState *s, bool log_dirty, bool readonly)
274 int flags = 0;
275 flags = log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
276 if (readonly && kvm_readonly_mem_allowed) {
277 flags |= KVM_MEM_READONLY;
279 return flags;
282 static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
284 KVMState *s = kvm_state;
285 int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
286 int old_flags;
288 old_flags = mem->flags;
290 flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty, false);
291 mem->flags = flags;
293 /* If nothing changed effectively, no need to issue ioctl */
294 if (s->migration_log) {
295 flags |= KVM_MEM_LOG_DIRTY_PAGES;
298 if (flags == old_flags) {
299 return 0;
302 return kvm_set_user_memory_region(s, mem);
305 static int kvm_dirty_pages_log_change(hwaddr phys_addr,
306 ram_addr_t size, bool log_dirty)
308 KVMState *s = kvm_state;
309 KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
311 if (mem == NULL) {
312 fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
313 TARGET_FMT_plx "\n", __func__, phys_addr,
314 (hwaddr)(phys_addr + size - 1));
315 return -EINVAL;
317 return kvm_slot_dirty_pages_log_change(mem, log_dirty);
320 static void kvm_log_start(MemoryListener *listener,
321 MemoryRegionSection *section)
323 int r;
325 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
326 int128_get64(section->size), true);
327 if (r < 0) {
328 abort();
332 static void kvm_log_stop(MemoryListener *listener,
333 MemoryRegionSection *section)
335 int r;
337 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
338 int128_get64(section->size), false);
339 if (r < 0) {
340 abort();
344 static int kvm_set_migration_log(int enable)
346 KVMState *s = kvm_state;
347 KVMSlot *mem;
348 int i, err;
350 s->migration_log = enable;
352 for (i = 0; i < s->nr_slots; i++) {
353 mem = &s->slots[i];
355 if (!mem->memory_size) {
356 continue;
358 if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
359 continue;
361 err = kvm_set_user_memory_region(s, mem);
362 if (err) {
363 return err;
366 return 0;
369 /* get kvm's dirty pages bitmap and update qemu's */
370 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
371 unsigned long *bitmap)
373 ram_addr_t start = section->offset_within_region + section->mr->ram_addr;
374 ram_addr_t pages = int128_get64(section->size) / getpagesize();
376 cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
377 return 0;
380 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
383 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
384 * This function updates qemu's dirty bitmap using
385 * memory_region_set_dirty(). This means all bits are set
386 * to dirty.
388 * @start_add: start of logged region.
389 * @end_addr: end of logged region.
391 static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)
393 KVMState *s = kvm_state;
394 unsigned long size, allocated_size = 0;
395 KVMDirtyLog d;
396 KVMSlot *mem;
397 int ret = 0;
398 hwaddr start_addr = section->offset_within_address_space;
399 hwaddr end_addr = start_addr + int128_get64(section->size);
401 d.dirty_bitmap = NULL;
402 while (start_addr < end_addr) {
403 mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
404 if (mem == NULL) {
405 break;
408 /* XXX bad kernel interface alert
409 * For dirty bitmap, kernel allocates array of size aligned to
410 * bits-per-long. But for case when the kernel is 64bits and
411 * the userspace is 32bits, userspace can't align to the same
412 * bits-per-long, since sizeof(long) is different between kernel
413 * and user space. This way, userspace will provide buffer which
414 * may be 4 bytes less than the kernel will use, resulting in
415 * userspace memory corruption (which is not detectable by valgrind
416 * too, in most cases).
417 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
418 * a hope that sizeof(long) wont become >8 any time soon.
420 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
421 /*HOST_LONG_BITS*/ 64) / 8;
422 if (!d.dirty_bitmap) {
423 d.dirty_bitmap = g_malloc(size);
424 } else if (size > allocated_size) {
425 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
427 allocated_size = size;
428 memset(d.dirty_bitmap, 0, allocated_size);
430 d.slot = mem->slot;
432 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
433 DPRINTF("ioctl failed %d\n", errno);
434 ret = -1;
435 break;
438 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
439 start_addr = mem->start_addr + mem->memory_size;
441 g_free(d.dirty_bitmap);
443 return ret;
446 static void kvm_coalesce_mmio_region(MemoryListener *listener,
447 MemoryRegionSection *secion,
448 hwaddr start, hwaddr size)
450 KVMState *s = kvm_state;
452 if (s->coalesced_mmio) {
453 struct kvm_coalesced_mmio_zone zone;
455 zone.addr = start;
456 zone.size = size;
457 zone.pad = 0;
459 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
463 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
464 MemoryRegionSection *secion,
465 hwaddr start, hwaddr size)
467 KVMState *s = kvm_state;
469 if (s->coalesced_mmio) {
470 struct kvm_coalesced_mmio_zone zone;
472 zone.addr = start;
473 zone.size = size;
474 zone.pad = 0;
476 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
480 int kvm_check_extension(KVMState *s, unsigned int extension)
482 int ret;
484 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
485 if (ret < 0) {
486 ret = 0;
489 return ret;
492 int kvm_vm_check_extension(KVMState *s, unsigned int extension)
494 int ret;
496 ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
497 if (ret < 0) {
498 /* VM wide version not implemented, use global one instead */
499 ret = kvm_check_extension(s, extension);
502 return ret;
505 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
506 bool assign, uint32_t size, bool datamatch)
508 int ret;
509 struct kvm_ioeventfd iofd;
511 iofd.datamatch = datamatch ? val : 0;
512 iofd.addr = addr;
513 iofd.len = size;
514 iofd.flags = 0;
515 iofd.fd = fd;
517 if (!kvm_enabled()) {
518 return -ENOSYS;
521 if (datamatch) {
522 iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
524 if (!assign) {
525 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
528 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
530 if (ret < 0) {
531 return -errno;
534 return 0;
537 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
538 bool assign, uint32_t size, bool datamatch)
540 struct kvm_ioeventfd kick = {
541 .datamatch = datamatch ? val : 0,
542 .addr = addr,
543 .flags = KVM_IOEVENTFD_FLAG_PIO,
544 .len = size,
545 .fd = fd,
547 int r;
548 if (!kvm_enabled()) {
549 return -ENOSYS;
551 if (datamatch) {
552 kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
554 if (!assign) {
555 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
557 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
558 if (r < 0) {
559 return r;
561 return 0;
565 static int kvm_check_many_ioeventfds(void)
567 /* Userspace can use ioeventfd for io notification. This requires a host
568 * that supports eventfd(2) and an I/O thread; since eventfd does not
569 * support SIGIO it cannot interrupt the vcpu.
571 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
572 * can avoid creating too many ioeventfds.
574 #if defined(CONFIG_EVENTFD)
575 int ioeventfds[7];
576 int i, ret = 0;
577 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
578 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
579 if (ioeventfds[i] < 0) {
580 break;
582 ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
583 if (ret < 0) {
584 close(ioeventfds[i]);
585 break;
589 /* Decide whether many devices are supported or not */
590 ret = i == ARRAY_SIZE(ioeventfds);
592 while (i-- > 0) {
593 kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
594 close(ioeventfds[i]);
596 return ret;
597 #else
598 return 0;
599 #endif
602 static const KVMCapabilityInfo *
603 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
605 while (list->name) {
606 if (!kvm_check_extension(s, list->value)) {
607 return list;
609 list++;
611 return NULL;
614 static void kvm_set_phys_mem(MemoryRegionSection *section, bool add)
616 KVMState *s = kvm_state;
617 KVMSlot *mem, old;
618 int err;
619 MemoryRegion *mr = section->mr;
620 bool log_dirty = memory_region_is_logging(mr);
621 bool writeable = !mr->readonly && !mr->rom_device;
622 bool readonly_flag = mr->readonly || memory_region_is_romd(mr);
623 hwaddr start_addr = section->offset_within_address_space;
624 ram_addr_t size = int128_get64(section->size);
625 void *ram = NULL;
626 unsigned delta;
628 /* kvm works in page size chunks, but the function may be called
629 with sub-page size and unaligned start address. */
630 delta = TARGET_PAGE_ALIGN(size) - size;
631 if (delta > size) {
632 return;
634 start_addr += delta;
635 size -= delta;
636 size &= TARGET_PAGE_MASK;
637 if (!size || (start_addr & ~TARGET_PAGE_MASK)) {
638 return;
641 if (!memory_region_is_ram(mr)) {
642 if (writeable || !kvm_readonly_mem_allowed) {
643 return;
644 } else if (!mr->romd_mode) {
645 /* If the memory device is not in romd_mode, then we actually want
646 * to remove the kvm memory slot so all accesses will trap. */
647 add = false;
651 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
653 while (1) {
654 mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
655 if (!mem) {
656 break;
659 if (add && start_addr >= mem->start_addr &&
660 (start_addr + size <= mem->start_addr + mem->memory_size) &&
661 (ram - start_addr == mem->ram - mem->start_addr)) {
662 /* The new slot fits into the existing one and comes with
663 * identical parameters - update flags and done. */
664 kvm_slot_dirty_pages_log_change(mem, log_dirty);
665 return;
668 old = *mem;
670 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
671 kvm_physical_sync_dirty_bitmap(section);
674 /* unregister the overlapping slot */
675 mem->memory_size = 0;
676 err = kvm_set_user_memory_region(s, mem);
677 if (err) {
678 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
679 __func__, strerror(-err));
680 abort();
683 /* Workaround for older KVM versions: we can't join slots, even not by
684 * unregistering the previous ones and then registering the larger
685 * slot. We have to maintain the existing fragmentation. Sigh.
687 * This workaround assumes that the new slot starts at the same
688 * address as the first existing one. If not or if some overlapping
689 * slot comes around later, we will fail (not seen in practice so far)
690 * - and actually require a recent KVM version. */
691 if (s->broken_set_mem_region &&
692 old.start_addr == start_addr && old.memory_size < size && add) {
693 mem = kvm_alloc_slot(s);
694 mem->memory_size = old.memory_size;
695 mem->start_addr = old.start_addr;
696 mem->ram = old.ram;
697 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
699 err = kvm_set_user_memory_region(s, mem);
700 if (err) {
701 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
702 strerror(-err));
703 abort();
706 start_addr += old.memory_size;
707 ram += old.memory_size;
708 size -= old.memory_size;
709 continue;
712 /* register prefix slot */
713 if (old.start_addr < start_addr) {
714 mem = kvm_alloc_slot(s);
715 mem->memory_size = start_addr - old.start_addr;
716 mem->start_addr = old.start_addr;
717 mem->ram = old.ram;
718 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
720 err = kvm_set_user_memory_region(s, mem);
721 if (err) {
722 fprintf(stderr, "%s: error registering prefix slot: %s\n",
723 __func__, strerror(-err));
724 #ifdef TARGET_PPC
725 fprintf(stderr, "%s: This is probably because your kernel's " \
726 "PAGE_SIZE is too big. Please try to use 4k " \
727 "PAGE_SIZE!\n", __func__);
728 #endif
729 abort();
733 /* register suffix slot */
734 if (old.start_addr + old.memory_size > start_addr + size) {
735 ram_addr_t size_delta;
737 mem = kvm_alloc_slot(s);
738 mem->start_addr = start_addr + size;
739 size_delta = mem->start_addr - old.start_addr;
740 mem->memory_size = old.memory_size - size_delta;
741 mem->ram = old.ram + size_delta;
742 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
744 err = kvm_set_user_memory_region(s, mem);
745 if (err) {
746 fprintf(stderr, "%s: error registering suffix slot: %s\n",
747 __func__, strerror(-err));
748 abort();
753 /* in case the KVM bug workaround already "consumed" the new slot */
754 if (!size) {
755 return;
757 if (!add) {
758 return;
760 mem = kvm_alloc_slot(s);
761 mem->memory_size = size;
762 mem->start_addr = start_addr;
763 mem->ram = ram;
764 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
766 err = kvm_set_user_memory_region(s, mem);
767 if (err) {
768 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
769 strerror(-err));
770 abort();
774 static void kvm_region_add(MemoryListener *listener,
775 MemoryRegionSection *section)
777 memory_region_ref(section->mr);
778 kvm_set_phys_mem(section, true);
781 static void kvm_region_del(MemoryListener *listener,
782 MemoryRegionSection *section)
784 kvm_set_phys_mem(section, false);
785 memory_region_unref(section->mr);
788 static void kvm_log_sync(MemoryListener *listener,
789 MemoryRegionSection *section)
791 int r;
793 r = kvm_physical_sync_dirty_bitmap(section);
794 if (r < 0) {
795 abort();
799 static void kvm_log_global_start(struct MemoryListener *listener)
801 int r;
803 r = kvm_set_migration_log(1);
804 assert(r >= 0);
807 static void kvm_log_global_stop(struct MemoryListener *listener)
809 int r;
811 r = kvm_set_migration_log(0);
812 assert(r >= 0);
815 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
816 MemoryRegionSection *section,
817 bool match_data, uint64_t data,
818 EventNotifier *e)
820 int fd = event_notifier_get_fd(e);
821 int r;
823 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
824 data, true, int128_get64(section->size),
825 match_data);
826 if (r < 0) {
827 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
828 __func__, strerror(-r));
829 abort();
833 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
834 MemoryRegionSection *section,
835 bool match_data, uint64_t data,
836 EventNotifier *e)
838 int fd = event_notifier_get_fd(e);
839 int r;
841 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
842 data, false, int128_get64(section->size),
843 match_data);
844 if (r < 0) {
845 abort();
849 static void kvm_io_ioeventfd_add(MemoryListener *listener,
850 MemoryRegionSection *section,
851 bool match_data, uint64_t data,
852 EventNotifier *e)
854 int fd = event_notifier_get_fd(e);
855 int r;
857 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
858 data, true, int128_get64(section->size),
859 match_data);
860 if (r < 0) {
861 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
862 __func__, strerror(-r));
863 abort();
867 static void kvm_io_ioeventfd_del(MemoryListener *listener,
868 MemoryRegionSection *section,
869 bool match_data, uint64_t data,
870 EventNotifier *e)
873 int fd = event_notifier_get_fd(e);
874 int r;
876 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
877 data, false, int128_get64(section->size),
878 match_data);
879 if (r < 0) {
880 abort();
884 static MemoryListener kvm_memory_listener = {
885 .region_add = kvm_region_add,
886 .region_del = kvm_region_del,
887 .log_start = kvm_log_start,
888 .log_stop = kvm_log_stop,
889 .log_sync = kvm_log_sync,
890 .log_global_start = kvm_log_global_start,
891 .log_global_stop = kvm_log_global_stop,
892 .eventfd_add = kvm_mem_ioeventfd_add,
893 .eventfd_del = kvm_mem_ioeventfd_del,
894 .coalesced_mmio_add = kvm_coalesce_mmio_region,
895 .coalesced_mmio_del = kvm_uncoalesce_mmio_region,
896 .priority = 10,
899 static MemoryListener kvm_io_listener = {
900 .eventfd_add = kvm_io_ioeventfd_add,
901 .eventfd_del = kvm_io_ioeventfd_del,
902 .priority = 10,
905 static void kvm_handle_interrupt(CPUState *cpu, int mask)
907 cpu->interrupt_request |= mask;
909 if (!qemu_cpu_is_self(cpu)) {
910 qemu_cpu_kick(cpu);
914 int kvm_set_irq(KVMState *s, int irq, int level)
916 struct kvm_irq_level event;
917 int ret;
919 assert(kvm_async_interrupts_enabled());
921 event.level = level;
922 event.irq = irq;
923 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
924 if (ret < 0) {
925 perror("kvm_set_irq");
926 abort();
929 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
932 #ifdef KVM_CAP_IRQ_ROUTING
933 typedef struct KVMMSIRoute {
934 struct kvm_irq_routing_entry kroute;
935 QTAILQ_ENTRY(KVMMSIRoute) entry;
936 } KVMMSIRoute;
938 static void set_gsi(KVMState *s, unsigned int gsi)
940 s->used_gsi_bitmap[gsi / 32] |= 1U << (gsi % 32);
943 static void clear_gsi(KVMState *s, unsigned int gsi)
945 s->used_gsi_bitmap[gsi / 32] &= ~(1U << (gsi % 32));
948 void kvm_init_irq_routing(KVMState *s)
950 int gsi_count, i;
952 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
953 if (gsi_count > 0) {
954 unsigned int gsi_bits, i;
956 /* Round up so we can search ints using ffs */
957 gsi_bits = ALIGN(gsi_count, 32);
958 s->used_gsi_bitmap = g_malloc0(gsi_bits / 8);
959 s->gsi_count = gsi_count;
961 /* Mark any over-allocated bits as already in use */
962 for (i = gsi_count; i < gsi_bits; i++) {
963 set_gsi(s, i);
967 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
968 s->nr_allocated_irq_routes = 0;
970 if (!s->direct_msi) {
971 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
972 QTAILQ_INIT(&s->msi_hashtab[i]);
976 kvm_arch_init_irq_routing(s);
979 void kvm_irqchip_commit_routes(KVMState *s)
981 int ret;
983 s->irq_routes->flags = 0;
984 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
985 assert(ret == 0);
988 static void kvm_add_routing_entry(KVMState *s,
989 struct kvm_irq_routing_entry *entry)
991 struct kvm_irq_routing_entry *new;
992 int n, size;
994 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
995 n = s->nr_allocated_irq_routes * 2;
996 if (n < 64) {
997 n = 64;
999 size = sizeof(struct kvm_irq_routing);
1000 size += n * sizeof(*new);
1001 s->irq_routes = g_realloc(s->irq_routes, size);
1002 s->nr_allocated_irq_routes = n;
1004 n = s->irq_routes->nr++;
1005 new = &s->irq_routes->entries[n];
1007 *new = *entry;
1009 set_gsi(s, entry->gsi);
1012 static int kvm_update_routing_entry(KVMState *s,
1013 struct kvm_irq_routing_entry *new_entry)
1015 struct kvm_irq_routing_entry *entry;
1016 int n;
1018 for (n = 0; n < s->irq_routes->nr; n++) {
1019 entry = &s->irq_routes->entries[n];
1020 if (entry->gsi != new_entry->gsi) {
1021 continue;
1024 if(!memcmp(entry, new_entry, sizeof *entry)) {
1025 return 0;
1028 *entry = *new_entry;
1030 kvm_irqchip_commit_routes(s);
1032 return 0;
1035 return -ESRCH;
1038 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1040 struct kvm_irq_routing_entry e = {};
1042 assert(pin < s->gsi_count);
1044 e.gsi = irq;
1045 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1046 e.flags = 0;
1047 e.u.irqchip.irqchip = irqchip;
1048 e.u.irqchip.pin = pin;
1049 kvm_add_routing_entry(s, &e);
1052 void kvm_irqchip_release_virq(KVMState *s, int virq)
1054 struct kvm_irq_routing_entry *e;
1055 int i;
1057 if (kvm_gsi_direct_mapping()) {
1058 return;
1061 for (i = 0; i < s->irq_routes->nr; i++) {
1062 e = &s->irq_routes->entries[i];
1063 if (e->gsi == virq) {
1064 s->irq_routes->nr--;
1065 *e = s->irq_routes->entries[s->irq_routes->nr];
1068 clear_gsi(s, virq);
1071 static unsigned int kvm_hash_msi(uint32_t data)
1073 /* This is optimized for IA32 MSI layout. However, no other arch shall
1074 * repeat the mistake of not providing a direct MSI injection API. */
1075 return data & 0xff;
1078 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1080 KVMMSIRoute *route, *next;
1081 unsigned int hash;
1083 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1084 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1085 kvm_irqchip_release_virq(s, route->kroute.gsi);
1086 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1087 g_free(route);
1092 static int kvm_irqchip_get_virq(KVMState *s)
1094 uint32_t *word = s->used_gsi_bitmap;
1095 int max_words = ALIGN(s->gsi_count, 32) / 32;
1096 int i, bit;
1097 bool retry = true;
1099 again:
1100 /* Return the lowest unused GSI in the bitmap */
1101 for (i = 0; i < max_words; i++) {
1102 bit = ffs(~word[i]);
1103 if (!bit) {
1104 continue;
1107 return bit - 1 + i * 32;
1109 if (!s->direct_msi && retry) {
1110 retry = false;
1111 kvm_flush_dynamic_msi_routes(s);
1112 goto again;
1114 return -ENOSPC;
1118 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1120 unsigned int hash = kvm_hash_msi(msg.data);
1121 KVMMSIRoute *route;
1123 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1124 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1125 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1126 route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1127 return route;
1130 return NULL;
1133 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1135 struct kvm_msi msi;
1136 KVMMSIRoute *route;
1138 if (s->direct_msi) {
1139 msi.address_lo = (uint32_t)msg.address;
1140 msi.address_hi = msg.address >> 32;
1141 msi.data = le32_to_cpu(msg.data);
1142 msi.flags = 0;
1143 memset(msi.pad, 0, sizeof(msi.pad));
1145 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1148 route = kvm_lookup_msi_route(s, msg);
1149 if (!route) {
1150 int virq;
1152 virq = kvm_irqchip_get_virq(s);
1153 if (virq < 0) {
1154 return virq;
1157 route = g_malloc0(sizeof(KVMMSIRoute));
1158 route->kroute.gsi = virq;
1159 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1160 route->kroute.flags = 0;
1161 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1162 route->kroute.u.msi.address_hi = msg.address >> 32;
1163 route->kroute.u.msi.data = le32_to_cpu(msg.data);
1165 kvm_add_routing_entry(s, &route->kroute);
1166 kvm_irqchip_commit_routes(s);
1168 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1169 entry);
1172 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1174 return kvm_set_irq(s, route->kroute.gsi, 1);
1177 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1179 struct kvm_irq_routing_entry kroute = {};
1180 int virq;
1182 if (kvm_gsi_direct_mapping()) {
1183 return msg.data & 0xffff;
1186 if (!kvm_gsi_routing_enabled()) {
1187 return -ENOSYS;
1190 virq = kvm_irqchip_get_virq(s);
1191 if (virq < 0) {
1192 return virq;
1195 kroute.gsi = virq;
1196 kroute.type = KVM_IRQ_ROUTING_MSI;
1197 kroute.flags = 0;
1198 kroute.u.msi.address_lo = (uint32_t)msg.address;
1199 kroute.u.msi.address_hi = msg.address >> 32;
1200 kroute.u.msi.data = le32_to_cpu(msg.data);
1202 kvm_add_routing_entry(s, &kroute);
1203 kvm_irqchip_commit_routes(s);
1205 return virq;
1208 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1210 struct kvm_irq_routing_entry kroute = {};
1212 if (kvm_gsi_direct_mapping()) {
1213 return 0;
1216 if (!kvm_irqchip_in_kernel()) {
1217 return -ENOSYS;
1220 kroute.gsi = virq;
1221 kroute.type = KVM_IRQ_ROUTING_MSI;
1222 kroute.flags = 0;
1223 kroute.u.msi.address_lo = (uint32_t)msg.address;
1224 kroute.u.msi.address_hi = msg.address >> 32;
1225 kroute.u.msi.data = le32_to_cpu(msg.data);
1227 return kvm_update_routing_entry(s, &kroute);
1230 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int rfd, int virq,
1231 bool assign)
1233 struct kvm_irqfd irqfd = {
1234 .fd = fd,
1235 .gsi = virq,
1236 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1239 if (rfd != -1) {
1240 irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1241 irqfd.resamplefd = rfd;
1244 if (!kvm_irqfds_enabled()) {
1245 return -ENOSYS;
1248 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1251 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1253 struct kvm_irq_routing_entry kroute;
1254 int virq;
1256 if (!kvm_gsi_routing_enabled()) {
1257 return -ENOSYS;
1260 virq = kvm_irqchip_get_virq(s);
1261 if (virq < 0) {
1262 return virq;
1265 kroute.gsi = virq;
1266 kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1267 kroute.flags = 0;
1268 kroute.u.adapter.summary_addr = adapter->summary_addr;
1269 kroute.u.adapter.ind_addr = adapter->ind_addr;
1270 kroute.u.adapter.summary_offset = adapter->summary_offset;
1271 kroute.u.adapter.ind_offset = adapter->ind_offset;
1272 kroute.u.adapter.adapter_id = adapter->adapter_id;
1274 kvm_add_routing_entry(s, &kroute);
1275 kvm_irqchip_commit_routes(s);
1277 return virq;
1280 #else /* !KVM_CAP_IRQ_ROUTING */
1282 void kvm_init_irq_routing(KVMState *s)
1286 void kvm_irqchip_release_virq(KVMState *s, int virq)
1290 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1292 abort();
1295 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1297 return -ENOSYS;
1300 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1302 return -ENOSYS;
1305 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1307 abort();
1310 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1312 return -ENOSYS;
1314 #endif /* !KVM_CAP_IRQ_ROUTING */
1316 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1317 EventNotifier *rn, int virq)
1319 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n),
1320 rn ? event_notifier_get_fd(rn) : -1, virq, true);
1323 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n, int virq)
1325 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), -1, virq,
1326 false);
1329 static int kvm_irqchip_create(KVMState *s)
1331 int ret;
1333 if (!qemu_opt_get_bool(qemu_get_machine_opts(), "kernel_irqchip", true) ||
1334 (!kvm_check_extension(s, KVM_CAP_IRQCHIP) &&
1335 (kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0) < 0))) {
1336 return 0;
1339 /* First probe and see if there's a arch-specific hook to create the
1340 * in-kernel irqchip for us */
1341 ret = kvm_arch_irqchip_create(s);
1342 if (ret < 0) {
1343 return ret;
1344 } else if (ret == 0) {
1345 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1346 if (ret < 0) {
1347 fprintf(stderr, "Create kernel irqchip failed\n");
1348 return ret;
1352 kvm_kernel_irqchip = true;
1353 /* If we have an in-kernel IRQ chip then we must have asynchronous
1354 * interrupt delivery (though the reverse is not necessarily true)
1356 kvm_async_interrupts_allowed = true;
1357 kvm_halt_in_kernel_allowed = true;
1359 kvm_init_irq_routing(s);
1361 return 0;
1364 /* Find number of supported CPUs using the recommended
1365 * procedure from the kernel API documentation to cope with
1366 * older kernels that may be missing capabilities.
1368 static int kvm_recommended_vcpus(KVMState *s)
1370 int ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
1371 return (ret) ? ret : 4;
1374 static int kvm_max_vcpus(KVMState *s)
1376 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1377 return (ret) ? ret : kvm_recommended_vcpus(s);
1380 int kvm_init(MachineClass *mc)
1382 static const char upgrade_note[] =
1383 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1384 "(see http://sourceforge.net/projects/kvm).\n";
1385 struct {
1386 const char *name;
1387 int num;
1388 } num_cpus[] = {
1389 { "SMP", smp_cpus },
1390 { "hotpluggable", max_cpus },
1391 { NULL, }
1392 }, *nc = num_cpus;
1393 int soft_vcpus_limit, hard_vcpus_limit;
1394 KVMState *s;
1395 const KVMCapabilityInfo *missing_cap;
1396 int ret;
1397 int i, type = 0;
1398 const char *kvm_type;
1400 s = g_malloc0(sizeof(KVMState));
1403 * On systems where the kernel can support different base page
1404 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1405 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1406 * page size for the system though.
1408 assert(TARGET_PAGE_SIZE <= getpagesize());
1409 page_size_init();
1411 s->sigmask_len = 8;
1413 #ifdef KVM_CAP_SET_GUEST_DEBUG
1414 QTAILQ_INIT(&s->kvm_sw_breakpoints);
1415 #endif
1416 s->vmfd = -1;
1417 s->fd = qemu_open("/dev/kvm", O_RDWR);
1418 if (s->fd == -1) {
1419 fprintf(stderr, "Could not access KVM kernel module: %m\n");
1420 ret = -errno;
1421 goto err;
1424 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1425 if (ret < KVM_API_VERSION) {
1426 if (ret >= 0) {
1427 ret = -EINVAL;
1429 fprintf(stderr, "kvm version too old\n");
1430 goto err;
1433 if (ret > KVM_API_VERSION) {
1434 ret = -EINVAL;
1435 fprintf(stderr, "kvm version not supported\n");
1436 goto err;
1439 s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
1441 /* If unspecified, use the default value */
1442 if (!s->nr_slots) {
1443 s->nr_slots = 32;
1446 s->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
1448 for (i = 0; i < s->nr_slots; i++) {
1449 s->slots[i].slot = i;
1452 /* check the vcpu limits */
1453 soft_vcpus_limit = kvm_recommended_vcpus(s);
1454 hard_vcpus_limit = kvm_max_vcpus(s);
1456 while (nc->name) {
1457 if (nc->num > soft_vcpus_limit) {
1458 fprintf(stderr,
1459 "Warning: Number of %s cpus requested (%d) exceeds "
1460 "the recommended cpus supported by KVM (%d)\n",
1461 nc->name, nc->num, soft_vcpus_limit);
1463 if (nc->num > hard_vcpus_limit) {
1464 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
1465 "the maximum cpus supported by KVM (%d)\n",
1466 nc->name, nc->num, hard_vcpus_limit);
1467 exit(1);
1470 nc++;
1473 kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1474 if (mc->kvm_type) {
1475 type = mc->kvm_type(kvm_type);
1476 } else if (kvm_type) {
1477 ret = -EINVAL;
1478 fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1479 goto err;
1482 do {
1483 ret = kvm_ioctl(s, KVM_CREATE_VM, type);
1484 } while (ret == -EINTR);
1486 if (ret < 0) {
1487 fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
1488 strerror(-ret));
1490 #ifdef TARGET_S390X
1491 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
1492 "your host kernel command line\n");
1493 #endif
1494 goto err;
1497 s->vmfd = ret;
1498 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1499 if (!missing_cap) {
1500 missing_cap =
1501 kvm_check_extension_list(s, kvm_arch_required_capabilities);
1503 if (missing_cap) {
1504 ret = -EINVAL;
1505 fprintf(stderr, "kvm does not support %s\n%s",
1506 missing_cap->name, upgrade_note);
1507 goto err;
1510 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1512 s->broken_set_mem_region = 1;
1513 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
1514 if (ret > 0) {
1515 s->broken_set_mem_region = 0;
1518 #ifdef KVM_CAP_VCPU_EVENTS
1519 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1520 #endif
1522 s->robust_singlestep =
1523 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1525 #ifdef KVM_CAP_DEBUGREGS
1526 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1527 #endif
1529 #ifdef KVM_CAP_XSAVE
1530 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1531 #endif
1533 #ifdef KVM_CAP_XCRS
1534 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1535 #endif
1537 #ifdef KVM_CAP_PIT_STATE2
1538 s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1539 #endif
1541 #ifdef KVM_CAP_IRQ_ROUTING
1542 s->direct_msi = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1543 #endif
1545 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1547 s->irq_set_ioctl = KVM_IRQ_LINE;
1548 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1549 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1552 #ifdef KVM_CAP_READONLY_MEM
1553 kvm_readonly_mem_allowed =
1554 (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1555 #endif
1557 kvm_eventfds_allowed =
1558 (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
1560 ret = kvm_arch_init(s);
1561 if (ret < 0) {
1562 goto err;
1565 ret = kvm_irqchip_create(s);
1566 if (ret < 0) {
1567 goto err;
1570 kvm_state = s;
1571 memory_listener_register(&kvm_memory_listener, &address_space_memory);
1572 memory_listener_register(&kvm_io_listener, &address_space_io);
1574 s->many_ioeventfds = kvm_check_many_ioeventfds();
1576 cpu_interrupt_handler = kvm_handle_interrupt;
1578 return 0;
1580 err:
1581 assert(ret < 0);
1582 if (s->vmfd >= 0) {
1583 close(s->vmfd);
1585 if (s->fd != -1) {
1586 close(s->fd);
1588 g_free(s->slots);
1589 g_free(s);
1591 return ret;
1594 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
1596 s->sigmask_len = sigmask_len;
1599 static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
1600 uint32_t count)
1602 int i;
1603 uint8_t *ptr = data;
1605 for (i = 0; i < count; i++) {
1606 address_space_rw(&address_space_io, port, ptr, size,
1607 direction == KVM_EXIT_IO_OUT);
1608 ptr += size;
1612 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
1614 fprintf(stderr, "KVM internal error. Suberror: %d\n",
1615 run->internal.suberror);
1617 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1618 int i;
1620 for (i = 0; i < run->internal.ndata; ++i) {
1621 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1622 i, (uint64_t)run->internal.data[i]);
1625 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1626 fprintf(stderr, "emulation failure\n");
1627 if (!kvm_arch_stop_on_emulation_error(cpu)) {
1628 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1629 return EXCP_INTERRUPT;
1632 /* FIXME: Should trigger a qmp message to let management know
1633 * something went wrong.
1635 return -1;
1638 void kvm_flush_coalesced_mmio_buffer(void)
1640 KVMState *s = kvm_state;
1642 if (s->coalesced_flush_in_progress) {
1643 return;
1646 s->coalesced_flush_in_progress = true;
1648 if (s->coalesced_mmio_ring) {
1649 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1650 while (ring->first != ring->last) {
1651 struct kvm_coalesced_mmio *ent;
1653 ent = &ring->coalesced_mmio[ring->first];
1655 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1656 smp_wmb();
1657 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1661 s->coalesced_flush_in_progress = false;
1664 static void do_kvm_cpu_synchronize_state(void *arg)
1666 CPUState *cpu = arg;
1668 if (!cpu->kvm_vcpu_dirty) {
1669 kvm_arch_get_registers(cpu);
1670 cpu->kvm_vcpu_dirty = true;
1674 void kvm_cpu_synchronize_state(CPUState *cpu)
1676 if (!cpu->kvm_vcpu_dirty) {
1677 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, cpu);
1681 static void do_kvm_cpu_synchronize_post_reset(void *arg)
1683 CPUState *cpu = arg;
1685 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1686 cpu->kvm_vcpu_dirty = false;
1689 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
1691 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, cpu);
1694 static void do_kvm_cpu_synchronize_post_init(void *arg)
1696 CPUState *cpu = arg;
1698 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1699 cpu->kvm_vcpu_dirty = false;
1702 void kvm_cpu_synchronize_post_init(CPUState *cpu)
1704 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, cpu);
1707 void kvm_cpu_clean_state(CPUState *cpu)
1709 cpu->kvm_vcpu_dirty = false;
1712 int kvm_cpu_exec(CPUState *cpu)
1714 struct kvm_run *run = cpu->kvm_run;
1715 int ret, run_ret;
1717 DPRINTF("kvm_cpu_exec()\n");
1719 if (kvm_arch_process_async_events(cpu)) {
1720 cpu->exit_request = 0;
1721 return EXCP_HLT;
1724 do {
1725 if (cpu->kvm_vcpu_dirty) {
1726 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1727 cpu->kvm_vcpu_dirty = false;
1730 kvm_arch_pre_run(cpu, run);
1731 if (cpu->exit_request) {
1732 DPRINTF("interrupt exit requested\n");
1734 * KVM requires us to reenter the kernel after IO exits to complete
1735 * instruction emulation. This self-signal will ensure that we
1736 * leave ASAP again.
1738 qemu_cpu_kick_self();
1740 qemu_mutex_unlock_iothread();
1742 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
1744 qemu_mutex_lock_iothread();
1745 kvm_arch_post_run(cpu, run);
1747 if (run_ret < 0) {
1748 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1749 DPRINTF("io window exit\n");
1750 ret = EXCP_INTERRUPT;
1751 break;
1753 fprintf(stderr, "error: kvm run failed %s\n",
1754 strerror(-run_ret));
1755 ret = -1;
1756 break;
1759 trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
1760 switch (run->exit_reason) {
1761 case KVM_EXIT_IO:
1762 DPRINTF("handle_io\n");
1763 kvm_handle_io(run->io.port,
1764 (uint8_t *)run + run->io.data_offset,
1765 run->io.direction,
1766 run->io.size,
1767 run->io.count);
1768 ret = 0;
1769 break;
1770 case KVM_EXIT_MMIO:
1771 DPRINTF("handle_mmio\n");
1772 cpu_physical_memory_rw(run->mmio.phys_addr,
1773 run->mmio.data,
1774 run->mmio.len,
1775 run->mmio.is_write);
1776 ret = 0;
1777 break;
1778 case KVM_EXIT_IRQ_WINDOW_OPEN:
1779 DPRINTF("irq_window_open\n");
1780 ret = EXCP_INTERRUPT;
1781 break;
1782 case KVM_EXIT_SHUTDOWN:
1783 DPRINTF("shutdown\n");
1784 qemu_system_reset_request();
1785 ret = EXCP_INTERRUPT;
1786 break;
1787 case KVM_EXIT_UNKNOWN:
1788 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1789 (uint64_t)run->hw.hardware_exit_reason);
1790 ret = -1;
1791 break;
1792 case KVM_EXIT_INTERNAL_ERROR:
1793 ret = kvm_handle_internal_error(cpu, run);
1794 break;
1795 case KVM_EXIT_SYSTEM_EVENT:
1796 switch (run->system_event.type) {
1797 case KVM_SYSTEM_EVENT_SHUTDOWN:
1798 qemu_system_shutdown_request();
1799 ret = EXCP_INTERRUPT;
1800 break;
1801 case KVM_SYSTEM_EVENT_RESET:
1802 qemu_system_reset_request();
1803 ret = EXCP_INTERRUPT;
1804 break;
1805 default:
1806 DPRINTF("kvm_arch_handle_exit\n");
1807 ret = kvm_arch_handle_exit(cpu, run);
1808 break;
1810 break;
1811 default:
1812 DPRINTF("kvm_arch_handle_exit\n");
1813 ret = kvm_arch_handle_exit(cpu, run);
1814 break;
1816 } while (ret == 0);
1818 if (ret < 0) {
1819 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1820 vm_stop(RUN_STATE_INTERNAL_ERROR);
1823 cpu->exit_request = 0;
1824 return ret;
1827 int kvm_ioctl(KVMState *s, int type, ...)
1829 int ret;
1830 void *arg;
1831 va_list ap;
1833 va_start(ap, type);
1834 arg = va_arg(ap, void *);
1835 va_end(ap);
1837 trace_kvm_ioctl(type, arg);
1838 ret = ioctl(s->fd, type, arg);
1839 if (ret == -1) {
1840 ret = -errno;
1842 return ret;
1845 int kvm_vm_ioctl(KVMState *s, int type, ...)
1847 int ret;
1848 void *arg;
1849 va_list ap;
1851 va_start(ap, type);
1852 arg = va_arg(ap, void *);
1853 va_end(ap);
1855 trace_kvm_vm_ioctl(type, arg);
1856 ret = ioctl(s->vmfd, type, arg);
1857 if (ret == -1) {
1858 ret = -errno;
1860 return ret;
1863 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
1865 int ret;
1866 void *arg;
1867 va_list ap;
1869 va_start(ap, type);
1870 arg = va_arg(ap, void *);
1871 va_end(ap);
1873 trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
1874 ret = ioctl(cpu->kvm_fd, type, arg);
1875 if (ret == -1) {
1876 ret = -errno;
1878 return ret;
1881 int kvm_device_ioctl(int fd, int type, ...)
1883 int ret;
1884 void *arg;
1885 va_list ap;
1887 va_start(ap, type);
1888 arg = va_arg(ap, void *);
1889 va_end(ap);
1891 trace_kvm_device_ioctl(fd, type, arg);
1892 ret = ioctl(fd, type, arg);
1893 if (ret == -1) {
1894 ret = -errno;
1896 return ret;
1899 int kvm_has_sync_mmu(void)
1901 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1904 int kvm_has_vcpu_events(void)
1906 return kvm_state->vcpu_events;
1909 int kvm_has_robust_singlestep(void)
1911 return kvm_state->robust_singlestep;
1914 int kvm_has_debugregs(void)
1916 return kvm_state->debugregs;
1919 int kvm_has_xsave(void)
1921 return kvm_state->xsave;
1924 int kvm_has_xcrs(void)
1926 return kvm_state->xcrs;
1929 int kvm_has_pit_state2(void)
1931 return kvm_state->pit_state2;
1934 int kvm_has_many_ioeventfds(void)
1936 if (!kvm_enabled()) {
1937 return 0;
1939 return kvm_state->many_ioeventfds;
1942 int kvm_has_gsi_routing(void)
1944 #ifdef KVM_CAP_IRQ_ROUTING
1945 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
1946 #else
1947 return false;
1948 #endif
1951 int kvm_has_intx_set_mask(void)
1953 return kvm_state->intx_set_mask;
1956 void kvm_setup_guest_memory(void *start, size_t size)
1958 if (!kvm_has_sync_mmu()) {
1959 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1961 if (ret) {
1962 perror("qemu_madvise");
1963 fprintf(stderr,
1964 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1965 exit(1);
1970 #ifdef KVM_CAP_SET_GUEST_DEBUG
1971 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
1972 target_ulong pc)
1974 struct kvm_sw_breakpoint *bp;
1976 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
1977 if (bp->pc == pc) {
1978 return bp;
1981 return NULL;
1984 int kvm_sw_breakpoints_active(CPUState *cpu)
1986 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
1989 struct kvm_set_guest_debug_data {
1990 struct kvm_guest_debug dbg;
1991 CPUState *cpu;
1992 int err;
1995 static void kvm_invoke_set_guest_debug(void *data)
1997 struct kvm_set_guest_debug_data *dbg_data = data;
1999 dbg_data->err = kvm_vcpu_ioctl(dbg_data->cpu, KVM_SET_GUEST_DEBUG,
2000 &dbg_data->dbg);
2003 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2005 struct kvm_set_guest_debug_data data;
2007 data.dbg.control = reinject_trap;
2009 if (cpu->singlestep_enabled) {
2010 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2012 kvm_arch_update_guest_debug(cpu, &data.dbg);
2013 data.cpu = cpu;
2015 run_on_cpu(cpu, kvm_invoke_set_guest_debug, &data);
2016 return data.err;
2019 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2020 target_ulong len, int type)
2022 struct kvm_sw_breakpoint *bp;
2023 int err;
2025 if (type == GDB_BREAKPOINT_SW) {
2026 bp = kvm_find_sw_breakpoint(cpu, addr);
2027 if (bp) {
2028 bp->use_count++;
2029 return 0;
2032 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2033 if (!bp) {
2034 return -ENOMEM;
2037 bp->pc = addr;
2038 bp->use_count = 1;
2039 err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2040 if (err) {
2041 g_free(bp);
2042 return err;
2045 QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2046 } else {
2047 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2048 if (err) {
2049 return err;
2053 CPU_FOREACH(cpu) {
2054 err = kvm_update_guest_debug(cpu, 0);
2055 if (err) {
2056 return err;
2059 return 0;
2062 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2063 target_ulong len, int type)
2065 struct kvm_sw_breakpoint *bp;
2066 int err;
2068 if (type == GDB_BREAKPOINT_SW) {
2069 bp = kvm_find_sw_breakpoint(cpu, addr);
2070 if (!bp) {
2071 return -ENOENT;
2074 if (bp->use_count > 1) {
2075 bp->use_count--;
2076 return 0;
2079 err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2080 if (err) {
2081 return err;
2084 QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2085 g_free(bp);
2086 } else {
2087 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2088 if (err) {
2089 return err;
2093 CPU_FOREACH(cpu) {
2094 err = kvm_update_guest_debug(cpu, 0);
2095 if (err) {
2096 return err;
2099 return 0;
2102 void kvm_remove_all_breakpoints(CPUState *cpu)
2104 struct kvm_sw_breakpoint *bp, *next;
2105 KVMState *s = cpu->kvm_state;
2106 CPUState *tmpcpu;
2108 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2109 if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2110 /* Try harder to find a CPU that currently sees the breakpoint. */
2111 CPU_FOREACH(tmpcpu) {
2112 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2113 break;
2117 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2118 g_free(bp);
2120 kvm_arch_remove_all_hw_breakpoints();
2122 CPU_FOREACH(cpu) {
2123 kvm_update_guest_debug(cpu, 0);
2127 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2129 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2131 return -EINVAL;
2134 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2135 target_ulong len, int type)
2137 return -EINVAL;
2140 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2141 target_ulong len, int type)
2143 return -EINVAL;
2146 void kvm_remove_all_breakpoints(CPUState *cpu)
2149 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2151 int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2153 KVMState *s = kvm_state;
2154 struct kvm_signal_mask *sigmask;
2155 int r;
2157 if (!sigset) {
2158 return kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, NULL);
2161 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2163 sigmask->len = s->sigmask_len;
2164 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2165 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2166 g_free(sigmask);
2168 return r;
2170 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2172 return kvm_arch_on_sigbus_vcpu(cpu, code, addr);
2175 int kvm_on_sigbus(int code, void *addr)
2177 return kvm_arch_on_sigbus(code, addr);
2180 int kvm_create_device(KVMState *s, uint64_t type, bool test)
2182 int ret;
2183 struct kvm_create_device create_dev;
2185 create_dev.type = type;
2186 create_dev.fd = -1;
2187 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2189 if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2190 return -ENOTSUP;
2193 ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2194 if (ret) {
2195 return ret;
2198 return test ? 0 : create_dev.fd;
2201 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2203 struct kvm_one_reg reg;
2204 int r;
2206 reg.id = id;
2207 reg.addr = (uintptr_t) source;
2208 r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
2209 if (r) {
2210 trace_kvm_failed_reg_set(id, strerror(r));
2212 return r;
2215 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2217 struct kvm_one_reg reg;
2218 int r;
2220 reg.id = id;
2221 reg.addr = (uintptr_t) target;
2222 r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
2223 if (r) {
2224 trace_kvm_failed_reg_get(id, strerror(r));
2226 return r;