qemu-io: Support multiple -o in open command
[qemu/qmp-unstable.git] / kvm-all.c
blob721a3904a9bd278b6bc52d23c8c2e6b82615d291
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 fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1465 goto err;
1468 do {
1469 ret = kvm_ioctl(s, KVM_CREATE_VM, type);
1470 } while (ret == -EINTR);
1472 if (ret < 0) {
1473 fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
1474 strerror(-ret));
1476 #ifdef TARGET_S390X
1477 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
1478 "your host kernel command line\n");
1479 #endif
1480 goto err;
1483 s->vmfd = ret;
1484 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1485 if (!missing_cap) {
1486 missing_cap =
1487 kvm_check_extension_list(s, kvm_arch_required_capabilities);
1489 if (missing_cap) {
1490 ret = -EINVAL;
1491 fprintf(stderr, "kvm does not support %s\n%s",
1492 missing_cap->name, upgrade_note);
1493 goto err;
1496 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1498 s->broken_set_mem_region = 1;
1499 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
1500 if (ret > 0) {
1501 s->broken_set_mem_region = 0;
1504 #ifdef KVM_CAP_VCPU_EVENTS
1505 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1506 #endif
1508 s->robust_singlestep =
1509 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1511 #ifdef KVM_CAP_DEBUGREGS
1512 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1513 #endif
1515 #ifdef KVM_CAP_XSAVE
1516 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1517 #endif
1519 #ifdef KVM_CAP_XCRS
1520 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1521 #endif
1523 #ifdef KVM_CAP_PIT_STATE2
1524 s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1525 #endif
1527 #ifdef KVM_CAP_IRQ_ROUTING
1528 s->direct_msi = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1529 #endif
1531 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1533 s->irq_set_ioctl = KVM_IRQ_LINE;
1534 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1535 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1538 #ifdef KVM_CAP_READONLY_MEM
1539 kvm_readonly_mem_allowed =
1540 (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1541 #endif
1543 ret = kvm_arch_init(s);
1544 if (ret < 0) {
1545 goto err;
1548 ret = kvm_irqchip_create(s);
1549 if (ret < 0) {
1550 goto err;
1553 kvm_state = s;
1554 memory_listener_register(&kvm_memory_listener, &address_space_memory);
1555 memory_listener_register(&kvm_io_listener, &address_space_io);
1557 s->many_ioeventfds = kvm_check_many_ioeventfds();
1559 cpu_interrupt_handler = kvm_handle_interrupt;
1561 return 0;
1563 err:
1564 if (s->vmfd >= 0) {
1565 close(s->vmfd);
1567 if (s->fd != -1) {
1568 close(s->fd);
1570 g_free(s->slots);
1571 g_free(s);
1573 return ret;
1576 static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
1577 uint32_t count)
1579 int i;
1580 uint8_t *ptr = data;
1582 for (i = 0; i < count; i++) {
1583 address_space_rw(&address_space_io, port, ptr, size,
1584 direction == KVM_EXIT_IO_OUT);
1585 ptr += size;
1589 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
1591 fprintf(stderr, "KVM internal error. Suberror: %d\n",
1592 run->internal.suberror);
1594 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1595 int i;
1597 for (i = 0; i < run->internal.ndata; ++i) {
1598 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1599 i, (uint64_t)run->internal.data[i]);
1602 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1603 fprintf(stderr, "emulation failure\n");
1604 if (!kvm_arch_stop_on_emulation_error(cpu)) {
1605 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1606 return EXCP_INTERRUPT;
1609 /* FIXME: Should trigger a qmp message to let management know
1610 * something went wrong.
1612 return -1;
1615 void kvm_flush_coalesced_mmio_buffer(void)
1617 KVMState *s = kvm_state;
1619 if (s->coalesced_flush_in_progress) {
1620 return;
1623 s->coalesced_flush_in_progress = true;
1625 if (s->coalesced_mmio_ring) {
1626 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1627 while (ring->first != ring->last) {
1628 struct kvm_coalesced_mmio *ent;
1630 ent = &ring->coalesced_mmio[ring->first];
1632 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1633 smp_wmb();
1634 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1638 s->coalesced_flush_in_progress = false;
1641 static void do_kvm_cpu_synchronize_state(void *arg)
1643 CPUState *cpu = arg;
1645 if (!cpu->kvm_vcpu_dirty) {
1646 kvm_arch_get_registers(cpu);
1647 cpu->kvm_vcpu_dirty = true;
1651 void kvm_cpu_synchronize_state(CPUState *cpu)
1653 if (!cpu->kvm_vcpu_dirty) {
1654 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, cpu);
1658 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
1660 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1661 cpu->kvm_vcpu_dirty = false;
1664 void kvm_cpu_synchronize_post_init(CPUState *cpu)
1666 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1667 cpu->kvm_vcpu_dirty = false;
1670 int kvm_cpu_exec(CPUState *cpu)
1672 struct kvm_run *run = cpu->kvm_run;
1673 int ret, run_ret;
1675 DPRINTF("kvm_cpu_exec()\n");
1677 if (kvm_arch_process_async_events(cpu)) {
1678 cpu->exit_request = 0;
1679 return EXCP_HLT;
1682 do {
1683 if (cpu->kvm_vcpu_dirty) {
1684 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1685 cpu->kvm_vcpu_dirty = false;
1688 kvm_arch_pre_run(cpu, run);
1689 if (cpu->exit_request) {
1690 DPRINTF("interrupt exit requested\n");
1692 * KVM requires us to reenter the kernel after IO exits to complete
1693 * instruction emulation. This self-signal will ensure that we
1694 * leave ASAP again.
1696 qemu_cpu_kick_self();
1698 qemu_mutex_unlock_iothread();
1700 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
1702 qemu_mutex_lock_iothread();
1703 kvm_arch_post_run(cpu, run);
1705 if (run_ret < 0) {
1706 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1707 DPRINTF("io window exit\n");
1708 ret = EXCP_INTERRUPT;
1709 break;
1711 fprintf(stderr, "error: kvm run failed %s\n",
1712 strerror(-run_ret));
1713 abort();
1716 trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
1717 switch (run->exit_reason) {
1718 case KVM_EXIT_IO:
1719 DPRINTF("handle_io\n");
1720 kvm_handle_io(run->io.port,
1721 (uint8_t *)run + run->io.data_offset,
1722 run->io.direction,
1723 run->io.size,
1724 run->io.count);
1725 ret = 0;
1726 break;
1727 case KVM_EXIT_MMIO:
1728 DPRINTF("handle_mmio\n");
1729 cpu_physical_memory_rw(run->mmio.phys_addr,
1730 run->mmio.data,
1731 run->mmio.len,
1732 run->mmio.is_write);
1733 ret = 0;
1734 break;
1735 case KVM_EXIT_IRQ_WINDOW_OPEN:
1736 DPRINTF("irq_window_open\n");
1737 ret = EXCP_INTERRUPT;
1738 break;
1739 case KVM_EXIT_SHUTDOWN:
1740 DPRINTF("shutdown\n");
1741 qemu_system_reset_request();
1742 ret = EXCP_INTERRUPT;
1743 break;
1744 case KVM_EXIT_UNKNOWN:
1745 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1746 (uint64_t)run->hw.hardware_exit_reason);
1747 ret = -1;
1748 break;
1749 case KVM_EXIT_INTERNAL_ERROR:
1750 ret = kvm_handle_internal_error(cpu, run);
1751 break;
1752 default:
1753 DPRINTF("kvm_arch_handle_exit\n");
1754 ret = kvm_arch_handle_exit(cpu, run);
1755 break;
1757 } while (ret == 0);
1759 if (ret < 0) {
1760 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1761 vm_stop(RUN_STATE_INTERNAL_ERROR);
1764 cpu->exit_request = 0;
1765 return ret;
1768 int kvm_ioctl(KVMState *s, int type, ...)
1770 int ret;
1771 void *arg;
1772 va_list ap;
1774 va_start(ap, type);
1775 arg = va_arg(ap, void *);
1776 va_end(ap);
1778 trace_kvm_ioctl(type, arg);
1779 ret = ioctl(s->fd, type, arg);
1780 if (ret == -1) {
1781 ret = -errno;
1783 return ret;
1786 int kvm_vm_ioctl(KVMState *s, int type, ...)
1788 int ret;
1789 void *arg;
1790 va_list ap;
1792 va_start(ap, type);
1793 arg = va_arg(ap, void *);
1794 va_end(ap);
1796 trace_kvm_vm_ioctl(type, arg);
1797 ret = ioctl(s->vmfd, type, arg);
1798 if (ret == -1) {
1799 ret = -errno;
1801 return ret;
1804 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
1806 int ret;
1807 void *arg;
1808 va_list ap;
1810 va_start(ap, type);
1811 arg = va_arg(ap, void *);
1812 va_end(ap);
1814 trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
1815 ret = ioctl(cpu->kvm_fd, type, arg);
1816 if (ret == -1) {
1817 ret = -errno;
1819 return ret;
1822 int kvm_device_ioctl(int fd, int type, ...)
1824 int ret;
1825 void *arg;
1826 va_list ap;
1828 va_start(ap, type);
1829 arg = va_arg(ap, void *);
1830 va_end(ap);
1832 trace_kvm_device_ioctl(fd, type, arg);
1833 ret = ioctl(fd, type, arg);
1834 if (ret == -1) {
1835 ret = -errno;
1837 return ret;
1840 int kvm_has_sync_mmu(void)
1842 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1845 int kvm_has_vcpu_events(void)
1847 return kvm_state->vcpu_events;
1850 int kvm_has_robust_singlestep(void)
1852 return kvm_state->robust_singlestep;
1855 int kvm_has_debugregs(void)
1857 return kvm_state->debugregs;
1860 int kvm_has_xsave(void)
1862 return kvm_state->xsave;
1865 int kvm_has_xcrs(void)
1867 return kvm_state->xcrs;
1870 int kvm_has_pit_state2(void)
1872 return kvm_state->pit_state2;
1875 int kvm_has_many_ioeventfds(void)
1877 if (!kvm_enabled()) {
1878 return 0;
1880 return kvm_state->many_ioeventfds;
1883 int kvm_has_gsi_routing(void)
1885 #ifdef KVM_CAP_IRQ_ROUTING
1886 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
1887 #else
1888 return false;
1889 #endif
1892 int kvm_has_intx_set_mask(void)
1894 return kvm_state->intx_set_mask;
1897 void kvm_setup_guest_memory(void *start, size_t size)
1899 #ifdef CONFIG_VALGRIND_H
1900 VALGRIND_MAKE_MEM_DEFINED(start, size);
1901 #endif
1902 if (!kvm_has_sync_mmu()) {
1903 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1905 if (ret) {
1906 perror("qemu_madvise");
1907 fprintf(stderr,
1908 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1909 exit(1);
1914 #ifdef KVM_CAP_SET_GUEST_DEBUG
1915 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
1916 target_ulong pc)
1918 struct kvm_sw_breakpoint *bp;
1920 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
1921 if (bp->pc == pc) {
1922 return bp;
1925 return NULL;
1928 int kvm_sw_breakpoints_active(CPUState *cpu)
1930 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
1933 struct kvm_set_guest_debug_data {
1934 struct kvm_guest_debug dbg;
1935 CPUState *cpu;
1936 int err;
1939 static void kvm_invoke_set_guest_debug(void *data)
1941 struct kvm_set_guest_debug_data *dbg_data = data;
1943 dbg_data->err = kvm_vcpu_ioctl(dbg_data->cpu, KVM_SET_GUEST_DEBUG,
1944 &dbg_data->dbg);
1947 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
1949 struct kvm_set_guest_debug_data data;
1951 data.dbg.control = reinject_trap;
1953 if (cpu->singlestep_enabled) {
1954 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
1956 kvm_arch_update_guest_debug(cpu, &data.dbg);
1957 data.cpu = cpu;
1959 run_on_cpu(cpu, kvm_invoke_set_guest_debug, &data);
1960 return data.err;
1963 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
1964 target_ulong len, int type)
1966 struct kvm_sw_breakpoint *bp;
1967 int err;
1969 if (type == GDB_BREAKPOINT_SW) {
1970 bp = kvm_find_sw_breakpoint(cpu, addr);
1971 if (bp) {
1972 bp->use_count++;
1973 return 0;
1976 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
1977 if (!bp) {
1978 return -ENOMEM;
1981 bp->pc = addr;
1982 bp->use_count = 1;
1983 err = kvm_arch_insert_sw_breakpoint(cpu, bp);
1984 if (err) {
1985 g_free(bp);
1986 return err;
1989 QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
1990 } else {
1991 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
1992 if (err) {
1993 return err;
1997 CPU_FOREACH(cpu) {
1998 err = kvm_update_guest_debug(cpu, 0);
1999 if (err) {
2000 return err;
2003 return 0;
2006 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2007 target_ulong len, int type)
2009 struct kvm_sw_breakpoint *bp;
2010 int err;
2012 if (type == GDB_BREAKPOINT_SW) {
2013 bp = kvm_find_sw_breakpoint(cpu, addr);
2014 if (!bp) {
2015 return -ENOENT;
2018 if (bp->use_count > 1) {
2019 bp->use_count--;
2020 return 0;
2023 err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2024 if (err) {
2025 return err;
2028 QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2029 g_free(bp);
2030 } else {
2031 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2032 if (err) {
2033 return err;
2037 CPU_FOREACH(cpu) {
2038 err = kvm_update_guest_debug(cpu, 0);
2039 if (err) {
2040 return err;
2043 return 0;
2046 void kvm_remove_all_breakpoints(CPUState *cpu)
2048 struct kvm_sw_breakpoint *bp, *next;
2049 KVMState *s = cpu->kvm_state;
2051 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2052 if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2053 /* Try harder to find a CPU that currently sees the breakpoint. */
2054 CPU_FOREACH(cpu) {
2055 if (kvm_arch_remove_sw_breakpoint(cpu, bp) == 0) {
2056 break;
2060 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2061 g_free(bp);
2063 kvm_arch_remove_all_hw_breakpoints();
2065 CPU_FOREACH(cpu) {
2066 kvm_update_guest_debug(cpu, 0);
2070 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2072 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2074 return -EINVAL;
2077 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2078 target_ulong len, int type)
2080 return -EINVAL;
2083 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2084 target_ulong len, int type)
2086 return -EINVAL;
2089 void kvm_remove_all_breakpoints(CPUState *cpu)
2092 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2094 int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2096 struct kvm_signal_mask *sigmask;
2097 int r;
2099 if (!sigset) {
2100 return kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, NULL);
2103 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2105 sigmask->len = 8;
2106 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2107 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2108 g_free(sigmask);
2110 return r;
2112 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2114 return kvm_arch_on_sigbus_vcpu(cpu, code, addr);
2117 int kvm_on_sigbus(int code, void *addr)
2119 return kvm_arch_on_sigbus(code, addr);
2122 int kvm_create_device(KVMState *s, uint64_t type, bool test)
2124 int ret;
2125 struct kvm_create_device create_dev;
2127 create_dev.type = type;
2128 create_dev.fd = -1;
2129 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2131 if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2132 return -ENOTSUP;
2135 ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2136 if (ret) {
2137 return ret;
2140 return test ? 0 : create_dev.fd;
2143 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2145 struct kvm_one_reg reg;
2146 int r;
2148 reg.id = id;
2149 reg.addr = (uintptr_t) source;
2150 r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
2151 if (r) {
2152 trace_kvm_failed_reg_set(id, strerror(r));
2154 return r;
2157 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2159 struct kvm_one_reg reg;
2160 int r;
2162 reg.id = id;
2163 reg.addr = (uintptr_t) target;
2164 r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
2165 if (r) {
2166 trace_kvm_failed_reg_get(id, strerror(r));
2168 return r;