target-ppc: fix nego and subf*o instructions
[qemu/ar7.git] / kvm-all.c
blob2d927217bd64aa756736d833fec08fa471aac314
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 "exec/gdbstub.h"
31 #include "sysemu/kvm.h"
32 #include "qemu/bswap.h"
33 #include "exec/memory.h"
34 #include "exec/address-spaces.h"
35 #include "qemu/event_notifier.h"
37 /* This check must be after config-host.h is included */
38 #ifdef CONFIG_EVENTFD
39 #include <sys/eventfd.h>
40 #endif
42 #ifdef CONFIG_VALGRIND_H
43 #include <valgrind/memcheck.h>
44 #endif
46 /* KVM uses PAGE_SIZE in its definition of COALESCED_MMIO_MAX */
47 #define PAGE_SIZE TARGET_PAGE_SIZE
49 //#define DEBUG_KVM
51 #ifdef DEBUG_KVM
52 #define DPRINTF(fmt, ...) \
53 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
54 #else
55 #define DPRINTF(fmt, ...) \
56 do { } while (0)
57 #endif
59 #define KVM_MSI_HASHTAB_SIZE 256
61 typedef struct KVMSlot
63 hwaddr start_addr;
64 ram_addr_t memory_size;
65 void *ram;
66 int slot;
67 int flags;
68 } KVMSlot;
70 typedef struct kvm_dirty_log KVMDirtyLog;
72 struct KVMState
74 KVMSlot slots[32];
75 int fd;
76 int vmfd;
77 int coalesced_mmio;
78 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
79 bool coalesced_flush_in_progress;
80 int broken_set_mem_region;
81 int migration_log;
82 int vcpu_events;
83 int robust_singlestep;
84 int debugregs;
85 #ifdef KVM_CAP_SET_GUEST_DEBUG
86 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
87 #endif
88 int pit_state2;
89 int xsave, xcrs;
90 int many_ioeventfds;
91 int intx_set_mask;
92 /* The man page (and posix) say ioctl numbers are signed int, but
93 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
94 * unsigned, and treating them as signed here can break things */
95 unsigned irq_set_ioctl;
96 #ifdef KVM_CAP_IRQ_ROUTING
97 struct kvm_irq_routing *irq_routes;
98 int nr_allocated_irq_routes;
99 uint32_t *used_gsi_bitmap;
100 unsigned int gsi_count;
101 QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
102 bool direct_msi;
103 #endif
106 KVMState *kvm_state;
107 bool kvm_kernel_irqchip;
108 bool kvm_async_interrupts_allowed;
109 bool kvm_irqfds_allowed;
110 bool kvm_msi_via_irqfd_allowed;
111 bool kvm_gsi_routing_allowed;
113 static const KVMCapabilityInfo kvm_required_capabilites[] = {
114 KVM_CAP_INFO(USER_MEMORY),
115 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
116 KVM_CAP_LAST_INFO
119 static KVMSlot *kvm_alloc_slot(KVMState *s)
121 int i;
123 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
124 if (s->slots[i].memory_size == 0) {
125 return &s->slots[i];
129 fprintf(stderr, "%s: no free slot available\n", __func__);
130 abort();
133 static KVMSlot *kvm_lookup_matching_slot(KVMState *s,
134 hwaddr start_addr,
135 hwaddr end_addr)
137 int i;
139 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
140 KVMSlot *mem = &s->slots[i];
142 if (start_addr == mem->start_addr &&
143 end_addr == mem->start_addr + mem->memory_size) {
144 return mem;
148 return NULL;
152 * Find overlapping slot with lowest start address
154 static KVMSlot *kvm_lookup_overlapping_slot(KVMState *s,
155 hwaddr start_addr,
156 hwaddr end_addr)
158 KVMSlot *found = NULL;
159 int i;
161 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
162 KVMSlot *mem = &s->slots[i];
164 if (mem->memory_size == 0 ||
165 (found && found->start_addr < mem->start_addr)) {
166 continue;
169 if (end_addr > mem->start_addr &&
170 start_addr < mem->start_addr + mem->memory_size) {
171 found = mem;
175 return found;
178 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
179 hwaddr *phys_addr)
181 int i;
183 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
184 KVMSlot *mem = &s->slots[i];
186 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
187 *phys_addr = mem->start_addr + (ram - mem->ram);
188 return 1;
192 return 0;
195 static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)
197 struct kvm_userspace_memory_region mem;
199 mem.slot = slot->slot;
200 mem.guest_phys_addr = slot->start_addr;
201 mem.memory_size = slot->memory_size;
202 mem.userspace_addr = (unsigned long)slot->ram;
203 mem.flags = slot->flags;
204 if (s->migration_log) {
205 mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;
207 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
210 static void kvm_reset_vcpu(void *opaque)
212 CPUState *cpu = opaque;
214 kvm_arch_reset_vcpu(cpu);
217 int kvm_init_vcpu(CPUState *cpu)
219 KVMState *s = kvm_state;
220 long mmap_size;
221 int ret;
223 DPRINTF("kvm_init_vcpu\n");
225 ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)kvm_arch_vcpu_id(cpu));
226 if (ret < 0) {
227 DPRINTF("kvm_create_vcpu failed\n");
228 goto err;
231 cpu->kvm_fd = ret;
232 cpu->kvm_state = s;
233 cpu->kvm_vcpu_dirty = true;
235 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
236 if (mmap_size < 0) {
237 ret = mmap_size;
238 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
239 goto err;
242 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
243 cpu->kvm_fd, 0);
244 if (cpu->kvm_run == MAP_FAILED) {
245 ret = -errno;
246 DPRINTF("mmap'ing vcpu state failed\n");
247 goto err;
250 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
251 s->coalesced_mmio_ring =
252 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
255 ret = kvm_arch_init_vcpu(cpu);
256 if (ret == 0) {
257 qemu_register_reset(kvm_reset_vcpu, cpu);
258 kvm_arch_reset_vcpu(cpu);
260 err:
261 return ret;
265 * dirty pages logging control
268 static int kvm_mem_flags(KVMState *s, bool log_dirty)
270 return log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
273 static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
275 KVMState *s = kvm_state;
276 int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
277 int old_flags;
279 old_flags = mem->flags;
281 flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty);
282 mem->flags = flags;
284 /* If nothing changed effectively, no need to issue ioctl */
285 if (s->migration_log) {
286 flags |= KVM_MEM_LOG_DIRTY_PAGES;
289 if (flags == old_flags) {
290 return 0;
293 return kvm_set_user_memory_region(s, mem);
296 static int kvm_dirty_pages_log_change(hwaddr phys_addr,
297 ram_addr_t size, bool log_dirty)
299 KVMState *s = kvm_state;
300 KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
302 if (mem == NULL) {
303 fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
304 TARGET_FMT_plx "\n", __func__, phys_addr,
305 (hwaddr)(phys_addr + size - 1));
306 return -EINVAL;
308 return kvm_slot_dirty_pages_log_change(mem, log_dirty);
311 static void kvm_log_start(MemoryListener *listener,
312 MemoryRegionSection *section)
314 int r;
316 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
317 section->size, true);
318 if (r < 0) {
319 abort();
323 static void kvm_log_stop(MemoryListener *listener,
324 MemoryRegionSection *section)
326 int r;
328 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
329 section->size, false);
330 if (r < 0) {
331 abort();
335 static int kvm_set_migration_log(int enable)
337 KVMState *s = kvm_state;
338 KVMSlot *mem;
339 int i, err;
341 s->migration_log = enable;
343 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
344 mem = &s->slots[i];
346 if (!mem->memory_size) {
347 continue;
349 if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
350 continue;
352 err = kvm_set_user_memory_region(s, mem);
353 if (err) {
354 return err;
357 return 0;
360 /* get kvm's dirty pages bitmap and update qemu's */
361 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
362 unsigned long *bitmap)
364 unsigned int i, j;
365 unsigned long page_number, c;
366 hwaddr addr, addr1;
367 unsigned int len = ((section->size / getpagesize()) + HOST_LONG_BITS - 1) / HOST_LONG_BITS;
368 unsigned long hpratio = getpagesize() / TARGET_PAGE_SIZE;
371 * bitmap-traveling is faster than memory-traveling (for addr...)
372 * especially when most of the memory is not dirty.
374 for (i = 0; i < len; i++) {
375 if (bitmap[i] != 0) {
376 c = leul_to_cpu(bitmap[i]);
377 do {
378 j = ffsl(c) - 1;
379 c &= ~(1ul << j);
380 page_number = (i * HOST_LONG_BITS + j) * hpratio;
381 addr1 = page_number * TARGET_PAGE_SIZE;
382 addr = section->offset_within_region + addr1;
383 memory_region_set_dirty(section->mr, addr,
384 TARGET_PAGE_SIZE * hpratio);
385 } while (c != 0);
388 return 0;
391 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
394 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
395 * This function updates qemu's dirty bitmap using
396 * memory_region_set_dirty(). This means all bits are set
397 * to dirty.
399 * @start_add: start of logged region.
400 * @end_addr: end of logged region.
402 static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)
404 KVMState *s = kvm_state;
405 unsigned long size, allocated_size = 0;
406 KVMDirtyLog d;
407 KVMSlot *mem;
408 int ret = 0;
409 hwaddr start_addr = section->offset_within_address_space;
410 hwaddr end_addr = start_addr + section->size;
412 d.dirty_bitmap = NULL;
413 while (start_addr < end_addr) {
414 mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
415 if (mem == NULL) {
416 break;
419 /* XXX bad kernel interface alert
420 * For dirty bitmap, kernel allocates array of size aligned to
421 * bits-per-long. But for case when the kernel is 64bits and
422 * the userspace is 32bits, userspace can't align to the same
423 * bits-per-long, since sizeof(long) is different between kernel
424 * and user space. This way, userspace will provide buffer which
425 * may be 4 bytes less than the kernel will use, resulting in
426 * userspace memory corruption (which is not detectable by valgrind
427 * too, in most cases).
428 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
429 * a hope that sizeof(long) wont become >8 any time soon.
431 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
432 /*HOST_LONG_BITS*/ 64) / 8;
433 if (!d.dirty_bitmap) {
434 d.dirty_bitmap = g_malloc(size);
435 } else if (size > allocated_size) {
436 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
438 allocated_size = size;
439 memset(d.dirty_bitmap, 0, allocated_size);
441 d.slot = mem->slot;
443 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
444 DPRINTF("ioctl failed %d\n", errno);
445 ret = -1;
446 break;
449 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
450 start_addr = mem->start_addr + mem->memory_size;
452 g_free(d.dirty_bitmap);
454 return ret;
457 static void kvm_coalesce_mmio_region(MemoryListener *listener,
458 MemoryRegionSection *secion,
459 hwaddr start, hwaddr size)
461 KVMState *s = kvm_state;
463 if (s->coalesced_mmio) {
464 struct kvm_coalesced_mmio_zone zone;
466 zone.addr = start;
467 zone.size = size;
468 zone.pad = 0;
470 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
474 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
475 MemoryRegionSection *secion,
476 hwaddr start, hwaddr size)
478 KVMState *s = kvm_state;
480 if (s->coalesced_mmio) {
481 struct kvm_coalesced_mmio_zone zone;
483 zone.addr = start;
484 zone.size = size;
485 zone.pad = 0;
487 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
491 int kvm_check_extension(KVMState *s, unsigned int extension)
493 int ret;
495 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
496 if (ret < 0) {
497 ret = 0;
500 return ret;
503 static int kvm_set_ioeventfd_mmio(int fd, uint32_t addr, uint32_t val,
504 bool assign, uint32_t size, bool datamatch)
506 int ret;
507 struct kvm_ioeventfd iofd;
509 iofd.datamatch = datamatch ? val : 0;
510 iofd.addr = addr;
511 iofd.len = size;
512 iofd.flags = 0;
513 iofd.fd = fd;
515 if (!kvm_enabled()) {
516 return -ENOSYS;
519 if (datamatch) {
520 iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
522 if (!assign) {
523 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
526 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
528 if (ret < 0) {
529 return -errno;
532 return 0;
535 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
536 bool assign, uint32_t size, bool datamatch)
538 struct kvm_ioeventfd kick = {
539 .datamatch = datamatch ? val : 0,
540 .addr = addr,
541 .flags = KVM_IOEVENTFD_FLAG_PIO,
542 .len = size,
543 .fd = fd,
545 int r;
546 if (!kvm_enabled()) {
547 return -ENOSYS;
549 if (datamatch) {
550 kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
552 if (!assign) {
553 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
555 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
556 if (r < 0) {
557 return r;
559 return 0;
563 static int kvm_check_many_ioeventfds(void)
565 /* Userspace can use ioeventfd for io notification. This requires a host
566 * that supports eventfd(2) and an I/O thread; since eventfd does not
567 * support SIGIO it cannot interrupt the vcpu.
569 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
570 * can avoid creating too many ioeventfds.
572 #if defined(CONFIG_EVENTFD)
573 int ioeventfds[7];
574 int i, ret = 0;
575 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
576 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
577 if (ioeventfds[i] < 0) {
578 break;
580 ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
581 if (ret < 0) {
582 close(ioeventfds[i]);
583 break;
587 /* Decide whether many devices are supported or not */
588 ret = i == ARRAY_SIZE(ioeventfds);
590 while (i-- > 0) {
591 kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
592 close(ioeventfds[i]);
594 return ret;
595 #else
596 return 0;
597 #endif
600 static const KVMCapabilityInfo *
601 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
603 while (list->name) {
604 if (!kvm_check_extension(s, list->value)) {
605 return list;
607 list++;
609 return NULL;
612 static void kvm_set_phys_mem(MemoryRegionSection *section, bool add)
614 KVMState *s = kvm_state;
615 KVMSlot *mem, old;
616 int err;
617 MemoryRegion *mr = section->mr;
618 bool log_dirty = memory_region_is_logging(mr);
619 hwaddr start_addr = section->offset_within_address_space;
620 ram_addr_t size = section->size;
621 void *ram = NULL;
622 unsigned delta;
624 /* kvm works in page size chunks, but the function may be called
625 with sub-page size and unaligned start address. */
626 delta = TARGET_PAGE_ALIGN(size) - size;
627 if (delta > size) {
628 return;
630 start_addr += delta;
631 size -= delta;
632 size &= TARGET_PAGE_MASK;
633 if (!size || (start_addr & ~TARGET_PAGE_MASK)) {
634 return;
637 if (!memory_region_is_ram(mr)) {
638 return;
641 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
643 while (1) {
644 mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
645 if (!mem) {
646 break;
649 if (add && start_addr >= mem->start_addr &&
650 (start_addr + size <= mem->start_addr + mem->memory_size) &&
651 (ram - start_addr == mem->ram - mem->start_addr)) {
652 /* The new slot fits into the existing one and comes with
653 * identical parameters - update flags and done. */
654 kvm_slot_dirty_pages_log_change(mem, log_dirty);
655 return;
658 old = *mem;
660 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
661 kvm_physical_sync_dirty_bitmap(section);
664 /* unregister the overlapping slot */
665 mem->memory_size = 0;
666 err = kvm_set_user_memory_region(s, mem);
667 if (err) {
668 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
669 __func__, strerror(-err));
670 abort();
673 /* Workaround for older KVM versions: we can't join slots, even not by
674 * unregistering the previous ones and then registering the larger
675 * slot. We have to maintain the existing fragmentation. Sigh.
677 * This workaround assumes that the new slot starts at the same
678 * address as the first existing one. If not or if some overlapping
679 * slot comes around later, we will fail (not seen in practice so far)
680 * - and actually require a recent KVM version. */
681 if (s->broken_set_mem_region &&
682 old.start_addr == start_addr && old.memory_size < size && add) {
683 mem = kvm_alloc_slot(s);
684 mem->memory_size = old.memory_size;
685 mem->start_addr = old.start_addr;
686 mem->ram = old.ram;
687 mem->flags = kvm_mem_flags(s, log_dirty);
689 err = kvm_set_user_memory_region(s, mem);
690 if (err) {
691 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
692 strerror(-err));
693 abort();
696 start_addr += old.memory_size;
697 ram += old.memory_size;
698 size -= old.memory_size;
699 continue;
702 /* register prefix slot */
703 if (old.start_addr < start_addr) {
704 mem = kvm_alloc_slot(s);
705 mem->memory_size = start_addr - old.start_addr;
706 mem->start_addr = old.start_addr;
707 mem->ram = old.ram;
708 mem->flags = kvm_mem_flags(s, log_dirty);
710 err = kvm_set_user_memory_region(s, mem);
711 if (err) {
712 fprintf(stderr, "%s: error registering prefix slot: %s\n",
713 __func__, strerror(-err));
714 #ifdef TARGET_PPC
715 fprintf(stderr, "%s: This is probably because your kernel's " \
716 "PAGE_SIZE is too big. Please try to use 4k " \
717 "PAGE_SIZE!\n", __func__);
718 #endif
719 abort();
723 /* register suffix slot */
724 if (old.start_addr + old.memory_size > start_addr + size) {
725 ram_addr_t size_delta;
727 mem = kvm_alloc_slot(s);
728 mem->start_addr = start_addr + size;
729 size_delta = mem->start_addr - old.start_addr;
730 mem->memory_size = old.memory_size - size_delta;
731 mem->ram = old.ram + size_delta;
732 mem->flags = kvm_mem_flags(s, log_dirty);
734 err = kvm_set_user_memory_region(s, mem);
735 if (err) {
736 fprintf(stderr, "%s: error registering suffix slot: %s\n",
737 __func__, strerror(-err));
738 abort();
743 /* in case the KVM bug workaround already "consumed" the new slot */
744 if (!size) {
745 return;
747 if (!add) {
748 return;
750 mem = kvm_alloc_slot(s);
751 mem->memory_size = size;
752 mem->start_addr = start_addr;
753 mem->ram = ram;
754 mem->flags = kvm_mem_flags(s, log_dirty);
756 err = kvm_set_user_memory_region(s, mem);
757 if (err) {
758 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
759 strerror(-err));
760 abort();
764 static void kvm_region_add(MemoryListener *listener,
765 MemoryRegionSection *section)
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);
776 static void kvm_log_sync(MemoryListener *listener,
777 MemoryRegionSection *section)
779 int r;
781 r = kvm_physical_sync_dirty_bitmap(section);
782 if (r < 0) {
783 abort();
787 static void kvm_log_global_start(struct MemoryListener *listener)
789 int r;
791 r = kvm_set_migration_log(1);
792 assert(r >= 0);
795 static void kvm_log_global_stop(struct MemoryListener *listener)
797 int r;
799 r = kvm_set_migration_log(0);
800 assert(r >= 0);
803 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
804 MemoryRegionSection *section,
805 bool match_data, uint64_t data,
806 EventNotifier *e)
808 int fd = event_notifier_get_fd(e);
809 int r;
811 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
812 data, true, section->size, match_data);
813 if (r < 0) {
814 abort();
818 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
819 MemoryRegionSection *section,
820 bool match_data, uint64_t data,
821 EventNotifier *e)
823 int fd = event_notifier_get_fd(e);
824 int r;
826 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
827 data, false, section->size, match_data);
828 if (r < 0) {
829 abort();
833 static void kvm_io_ioeventfd_add(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_pio(fd, section->offset_within_address_space,
842 data, true, section->size, match_data);
843 if (r < 0) {
844 abort();
848 static void kvm_io_ioeventfd_del(MemoryListener *listener,
849 MemoryRegionSection *section,
850 bool match_data, uint64_t data,
851 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, false, section->size, match_data);
859 if (r < 0) {
860 abort();
864 static MemoryListener kvm_memory_listener = {
865 .region_add = kvm_region_add,
866 .region_del = kvm_region_del,
867 .log_start = kvm_log_start,
868 .log_stop = kvm_log_stop,
869 .log_sync = kvm_log_sync,
870 .log_global_start = kvm_log_global_start,
871 .log_global_stop = kvm_log_global_stop,
872 .eventfd_add = kvm_mem_ioeventfd_add,
873 .eventfd_del = kvm_mem_ioeventfd_del,
874 .coalesced_mmio_add = kvm_coalesce_mmio_region,
875 .coalesced_mmio_del = kvm_uncoalesce_mmio_region,
876 .priority = 10,
879 static MemoryListener kvm_io_listener = {
880 .eventfd_add = kvm_io_ioeventfd_add,
881 .eventfd_del = kvm_io_ioeventfd_del,
882 .priority = 10,
885 static void kvm_handle_interrupt(CPUState *cpu, int mask)
887 cpu->interrupt_request |= mask;
889 if (!qemu_cpu_is_self(cpu)) {
890 qemu_cpu_kick(cpu);
894 int kvm_set_irq(KVMState *s, int irq, int level)
896 struct kvm_irq_level event;
897 int ret;
899 assert(kvm_async_interrupts_enabled());
901 event.level = level;
902 event.irq = irq;
903 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
904 if (ret < 0) {
905 perror("kvm_set_irq");
906 abort();
909 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
912 #ifdef KVM_CAP_IRQ_ROUTING
913 typedef struct KVMMSIRoute {
914 struct kvm_irq_routing_entry kroute;
915 QTAILQ_ENTRY(KVMMSIRoute) entry;
916 } KVMMSIRoute;
918 static void set_gsi(KVMState *s, unsigned int gsi)
920 s->used_gsi_bitmap[gsi / 32] |= 1U << (gsi % 32);
923 static void clear_gsi(KVMState *s, unsigned int gsi)
925 s->used_gsi_bitmap[gsi / 32] &= ~(1U << (gsi % 32));
928 static void kvm_init_irq_routing(KVMState *s)
930 int gsi_count, i;
932 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING);
933 if (gsi_count > 0) {
934 unsigned int gsi_bits, i;
936 /* Round up so we can search ints using ffs */
937 gsi_bits = ALIGN(gsi_count, 32);
938 s->used_gsi_bitmap = g_malloc0(gsi_bits / 8);
939 s->gsi_count = gsi_count;
941 /* Mark any over-allocated bits as already in use */
942 for (i = gsi_count; i < gsi_bits; i++) {
943 set_gsi(s, i);
947 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
948 s->nr_allocated_irq_routes = 0;
950 if (!s->direct_msi) {
951 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
952 QTAILQ_INIT(&s->msi_hashtab[i]);
956 kvm_arch_init_irq_routing(s);
959 static void kvm_irqchip_commit_routes(KVMState *s)
961 int ret;
963 s->irq_routes->flags = 0;
964 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
965 assert(ret == 0);
968 static void kvm_add_routing_entry(KVMState *s,
969 struct kvm_irq_routing_entry *entry)
971 struct kvm_irq_routing_entry *new;
972 int n, size;
974 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
975 n = s->nr_allocated_irq_routes * 2;
976 if (n < 64) {
977 n = 64;
979 size = sizeof(struct kvm_irq_routing);
980 size += n * sizeof(*new);
981 s->irq_routes = g_realloc(s->irq_routes, size);
982 s->nr_allocated_irq_routes = n;
984 n = s->irq_routes->nr++;
985 new = &s->irq_routes->entries[n];
986 memset(new, 0, sizeof(*new));
987 new->gsi = entry->gsi;
988 new->type = entry->type;
989 new->flags = entry->flags;
990 new->u = entry->u;
992 set_gsi(s, entry->gsi);
994 kvm_irqchip_commit_routes(s);
997 static int kvm_update_routing_entry(KVMState *s,
998 struct kvm_irq_routing_entry *new_entry)
1000 struct kvm_irq_routing_entry *entry;
1001 int n;
1003 for (n = 0; n < s->irq_routes->nr; n++) {
1004 entry = &s->irq_routes->entries[n];
1005 if (entry->gsi != new_entry->gsi) {
1006 continue;
1009 entry->type = new_entry->type;
1010 entry->flags = new_entry->flags;
1011 entry->u = new_entry->u;
1013 kvm_irqchip_commit_routes(s);
1015 return 0;
1018 return -ESRCH;
1021 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1023 struct kvm_irq_routing_entry e;
1025 assert(pin < s->gsi_count);
1027 e.gsi = irq;
1028 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1029 e.flags = 0;
1030 e.u.irqchip.irqchip = irqchip;
1031 e.u.irqchip.pin = pin;
1032 kvm_add_routing_entry(s, &e);
1035 void kvm_irqchip_release_virq(KVMState *s, int virq)
1037 struct kvm_irq_routing_entry *e;
1038 int i;
1040 for (i = 0; i < s->irq_routes->nr; i++) {
1041 e = &s->irq_routes->entries[i];
1042 if (e->gsi == virq) {
1043 s->irq_routes->nr--;
1044 *e = s->irq_routes->entries[s->irq_routes->nr];
1047 clear_gsi(s, virq);
1050 static unsigned int kvm_hash_msi(uint32_t data)
1052 /* This is optimized for IA32 MSI layout. However, no other arch shall
1053 * repeat the mistake of not providing a direct MSI injection API. */
1054 return data & 0xff;
1057 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1059 KVMMSIRoute *route, *next;
1060 unsigned int hash;
1062 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1063 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1064 kvm_irqchip_release_virq(s, route->kroute.gsi);
1065 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1066 g_free(route);
1071 static int kvm_irqchip_get_virq(KVMState *s)
1073 uint32_t *word = s->used_gsi_bitmap;
1074 int max_words = ALIGN(s->gsi_count, 32) / 32;
1075 int i, bit;
1076 bool retry = true;
1078 again:
1079 /* Return the lowest unused GSI in the bitmap */
1080 for (i = 0; i < max_words; i++) {
1081 bit = ffs(~word[i]);
1082 if (!bit) {
1083 continue;
1086 return bit - 1 + i * 32;
1088 if (!s->direct_msi && retry) {
1089 retry = false;
1090 kvm_flush_dynamic_msi_routes(s);
1091 goto again;
1093 return -ENOSPC;
1097 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1099 unsigned int hash = kvm_hash_msi(msg.data);
1100 KVMMSIRoute *route;
1102 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1103 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1104 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1105 route->kroute.u.msi.data == msg.data) {
1106 return route;
1109 return NULL;
1112 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1114 struct kvm_msi msi;
1115 KVMMSIRoute *route;
1117 if (s->direct_msi) {
1118 msi.address_lo = (uint32_t)msg.address;
1119 msi.address_hi = msg.address >> 32;
1120 msi.data = msg.data;
1121 msi.flags = 0;
1122 memset(msi.pad, 0, sizeof(msi.pad));
1124 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1127 route = kvm_lookup_msi_route(s, msg);
1128 if (!route) {
1129 int virq;
1131 virq = kvm_irqchip_get_virq(s);
1132 if (virq < 0) {
1133 return virq;
1136 route = g_malloc(sizeof(KVMMSIRoute));
1137 route->kroute.gsi = virq;
1138 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1139 route->kroute.flags = 0;
1140 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1141 route->kroute.u.msi.address_hi = msg.address >> 32;
1142 route->kroute.u.msi.data = msg.data;
1144 kvm_add_routing_entry(s, &route->kroute);
1146 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1147 entry);
1150 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1152 return kvm_set_irq(s, route->kroute.gsi, 1);
1155 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1157 struct kvm_irq_routing_entry kroute;
1158 int virq;
1160 if (!kvm_gsi_routing_enabled()) {
1161 return -ENOSYS;
1164 virq = kvm_irqchip_get_virq(s);
1165 if (virq < 0) {
1166 return virq;
1169 kroute.gsi = virq;
1170 kroute.type = KVM_IRQ_ROUTING_MSI;
1171 kroute.flags = 0;
1172 kroute.u.msi.address_lo = (uint32_t)msg.address;
1173 kroute.u.msi.address_hi = msg.address >> 32;
1174 kroute.u.msi.data = msg.data;
1176 kvm_add_routing_entry(s, &kroute);
1178 return virq;
1181 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1183 struct kvm_irq_routing_entry kroute;
1185 if (!kvm_irqchip_in_kernel()) {
1186 return -ENOSYS;
1189 kroute.gsi = virq;
1190 kroute.type = KVM_IRQ_ROUTING_MSI;
1191 kroute.flags = 0;
1192 kroute.u.msi.address_lo = (uint32_t)msg.address;
1193 kroute.u.msi.address_hi = msg.address >> 32;
1194 kroute.u.msi.data = msg.data;
1196 return kvm_update_routing_entry(s, &kroute);
1199 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1201 struct kvm_irqfd irqfd = {
1202 .fd = fd,
1203 .gsi = virq,
1204 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1207 if (!kvm_irqfds_enabled()) {
1208 return -ENOSYS;
1211 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1214 #else /* !KVM_CAP_IRQ_ROUTING */
1216 static void kvm_init_irq_routing(KVMState *s)
1220 void kvm_irqchip_release_virq(KVMState *s, int virq)
1224 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1226 abort();
1229 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1231 return -ENOSYS;
1234 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1236 abort();
1239 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1241 return -ENOSYS;
1243 #endif /* !KVM_CAP_IRQ_ROUTING */
1245 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n, int virq)
1247 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), virq, true);
1250 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n, int virq)
1252 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), virq, false);
1255 static int kvm_irqchip_create(KVMState *s)
1257 QemuOptsList *list = qemu_find_opts("machine");
1258 int ret;
1260 if (QTAILQ_EMPTY(&list->head) ||
1261 !qemu_opt_get_bool(QTAILQ_FIRST(&list->head),
1262 "kernel_irqchip", true) ||
1263 !kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
1264 return 0;
1267 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1268 if (ret < 0) {
1269 fprintf(stderr, "Create kernel irqchip failed\n");
1270 return ret;
1273 kvm_kernel_irqchip = true;
1274 /* If we have an in-kernel IRQ chip then we must have asynchronous
1275 * interrupt delivery (though the reverse is not necessarily true)
1277 kvm_async_interrupts_allowed = true;
1279 kvm_init_irq_routing(s);
1281 return 0;
1284 static int kvm_max_vcpus(KVMState *s)
1286 int ret;
1288 /* Find number of supported CPUs using the recommended
1289 * procedure from the kernel API documentation to cope with
1290 * older kernels that may be missing capabilities.
1292 ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1293 if (ret) {
1294 return ret;
1296 ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
1297 if (ret) {
1298 return ret;
1301 return 4;
1304 int kvm_init(void)
1306 static const char upgrade_note[] =
1307 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1308 "(see http://sourceforge.net/projects/kvm).\n";
1309 KVMState *s;
1310 const KVMCapabilityInfo *missing_cap;
1311 int ret;
1312 int i;
1313 int max_vcpus;
1315 s = g_malloc0(sizeof(KVMState));
1318 * On systems where the kernel can support different base page
1319 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1320 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1321 * page size for the system though.
1323 assert(TARGET_PAGE_SIZE <= getpagesize());
1325 #ifdef KVM_CAP_SET_GUEST_DEBUG
1326 QTAILQ_INIT(&s->kvm_sw_breakpoints);
1327 #endif
1328 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
1329 s->slots[i].slot = i;
1331 s->vmfd = -1;
1332 s->fd = qemu_open("/dev/kvm", O_RDWR);
1333 if (s->fd == -1) {
1334 fprintf(stderr, "Could not access KVM kernel module: %m\n");
1335 ret = -errno;
1336 goto err;
1339 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1340 if (ret < KVM_API_VERSION) {
1341 if (ret > 0) {
1342 ret = -EINVAL;
1344 fprintf(stderr, "kvm version too old\n");
1345 goto err;
1348 if (ret > KVM_API_VERSION) {
1349 ret = -EINVAL;
1350 fprintf(stderr, "kvm version not supported\n");
1351 goto err;
1354 max_vcpus = kvm_max_vcpus(s);
1355 if (smp_cpus > max_vcpus) {
1356 ret = -EINVAL;
1357 fprintf(stderr, "Number of SMP cpus requested (%d) exceeds max cpus "
1358 "supported by KVM (%d)\n", smp_cpus, max_vcpus);
1359 goto err;
1362 s->vmfd = kvm_ioctl(s, KVM_CREATE_VM, 0);
1363 if (s->vmfd < 0) {
1364 #ifdef TARGET_S390X
1365 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
1366 "your host kernel command line\n");
1367 #endif
1368 ret = s->vmfd;
1369 goto err;
1372 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1373 if (!missing_cap) {
1374 missing_cap =
1375 kvm_check_extension_list(s, kvm_arch_required_capabilities);
1377 if (missing_cap) {
1378 ret = -EINVAL;
1379 fprintf(stderr, "kvm does not support %s\n%s",
1380 missing_cap->name, upgrade_note);
1381 goto err;
1384 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1386 s->broken_set_mem_region = 1;
1387 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
1388 if (ret > 0) {
1389 s->broken_set_mem_region = 0;
1392 #ifdef KVM_CAP_VCPU_EVENTS
1393 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1394 #endif
1396 s->robust_singlestep =
1397 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1399 #ifdef KVM_CAP_DEBUGREGS
1400 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1401 #endif
1403 #ifdef KVM_CAP_XSAVE
1404 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1405 #endif
1407 #ifdef KVM_CAP_XCRS
1408 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1409 #endif
1411 #ifdef KVM_CAP_PIT_STATE2
1412 s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1413 #endif
1415 #ifdef KVM_CAP_IRQ_ROUTING
1416 s->direct_msi = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1417 #endif
1419 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1421 s->irq_set_ioctl = KVM_IRQ_LINE;
1422 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1423 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1426 ret = kvm_arch_init(s);
1427 if (ret < 0) {
1428 goto err;
1431 ret = kvm_irqchip_create(s);
1432 if (ret < 0) {
1433 goto err;
1436 kvm_state = s;
1437 memory_listener_register(&kvm_memory_listener, &address_space_memory);
1438 memory_listener_register(&kvm_io_listener, &address_space_io);
1440 s->many_ioeventfds = kvm_check_many_ioeventfds();
1442 cpu_interrupt_handler = kvm_handle_interrupt;
1444 return 0;
1446 err:
1447 if (s->vmfd >= 0) {
1448 close(s->vmfd);
1450 if (s->fd != -1) {
1451 close(s->fd);
1453 g_free(s);
1455 return ret;
1458 static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
1459 uint32_t count)
1461 int i;
1462 uint8_t *ptr = data;
1464 for (i = 0; i < count; i++) {
1465 if (direction == KVM_EXIT_IO_IN) {
1466 switch (size) {
1467 case 1:
1468 stb_p(ptr, cpu_inb(port));
1469 break;
1470 case 2:
1471 stw_p(ptr, cpu_inw(port));
1472 break;
1473 case 4:
1474 stl_p(ptr, cpu_inl(port));
1475 break;
1477 } else {
1478 switch (size) {
1479 case 1:
1480 cpu_outb(port, ldub_p(ptr));
1481 break;
1482 case 2:
1483 cpu_outw(port, lduw_p(ptr));
1484 break;
1485 case 4:
1486 cpu_outl(port, ldl_p(ptr));
1487 break;
1491 ptr += size;
1495 static int kvm_handle_internal_error(CPUArchState *env, struct kvm_run *run)
1497 CPUState *cpu = ENV_GET_CPU(env);
1499 fprintf(stderr, "KVM internal error.");
1500 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1501 int i;
1503 fprintf(stderr, " Suberror: %d\n", run->internal.suberror);
1504 for (i = 0; i < run->internal.ndata; ++i) {
1505 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1506 i, (uint64_t)run->internal.data[i]);
1508 } else {
1509 fprintf(stderr, "\n");
1511 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1512 fprintf(stderr, "emulation failure\n");
1513 if (!kvm_arch_stop_on_emulation_error(cpu)) {
1514 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1515 return EXCP_INTERRUPT;
1518 /* FIXME: Should trigger a qmp message to let management know
1519 * something went wrong.
1521 return -1;
1524 void kvm_flush_coalesced_mmio_buffer(void)
1526 KVMState *s = kvm_state;
1528 if (s->coalesced_flush_in_progress) {
1529 return;
1532 s->coalesced_flush_in_progress = true;
1534 if (s->coalesced_mmio_ring) {
1535 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1536 while (ring->first != ring->last) {
1537 struct kvm_coalesced_mmio *ent;
1539 ent = &ring->coalesced_mmio[ring->first];
1541 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1542 smp_wmb();
1543 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1547 s->coalesced_flush_in_progress = false;
1550 static void do_kvm_cpu_synchronize_state(void *arg)
1552 CPUState *cpu = arg;
1554 if (!cpu->kvm_vcpu_dirty) {
1555 kvm_arch_get_registers(cpu);
1556 cpu->kvm_vcpu_dirty = true;
1560 void kvm_cpu_synchronize_state(CPUArchState *env)
1562 CPUState *cpu = ENV_GET_CPU(env);
1564 if (!cpu->kvm_vcpu_dirty) {
1565 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, cpu);
1569 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
1571 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1572 cpu->kvm_vcpu_dirty = false;
1575 void kvm_cpu_synchronize_post_init(CPUState *cpu)
1577 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1578 cpu->kvm_vcpu_dirty = false;
1581 int kvm_cpu_exec(CPUArchState *env)
1583 CPUState *cpu = ENV_GET_CPU(env);
1584 struct kvm_run *run = cpu->kvm_run;
1585 int ret, run_ret;
1587 DPRINTF("kvm_cpu_exec()\n");
1589 if (kvm_arch_process_async_events(cpu)) {
1590 cpu->exit_request = 0;
1591 return EXCP_HLT;
1594 do {
1595 if (cpu->kvm_vcpu_dirty) {
1596 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1597 cpu->kvm_vcpu_dirty = false;
1600 kvm_arch_pre_run(cpu, run);
1601 if (cpu->exit_request) {
1602 DPRINTF("interrupt exit requested\n");
1604 * KVM requires us to reenter the kernel after IO exits to complete
1605 * instruction emulation. This self-signal will ensure that we
1606 * leave ASAP again.
1608 qemu_cpu_kick_self();
1610 qemu_mutex_unlock_iothread();
1612 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
1614 qemu_mutex_lock_iothread();
1615 kvm_arch_post_run(cpu, run);
1617 if (run_ret < 0) {
1618 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1619 DPRINTF("io window exit\n");
1620 ret = EXCP_INTERRUPT;
1621 break;
1623 fprintf(stderr, "error: kvm run failed %s\n",
1624 strerror(-run_ret));
1625 abort();
1628 switch (run->exit_reason) {
1629 case KVM_EXIT_IO:
1630 DPRINTF("handle_io\n");
1631 kvm_handle_io(run->io.port,
1632 (uint8_t *)run + run->io.data_offset,
1633 run->io.direction,
1634 run->io.size,
1635 run->io.count);
1636 ret = 0;
1637 break;
1638 case KVM_EXIT_MMIO:
1639 DPRINTF("handle_mmio\n");
1640 cpu_physical_memory_rw(run->mmio.phys_addr,
1641 run->mmio.data,
1642 run->mmio.len,
1643 run->mmio.is_write);
1644 ret = 0;
1645 break;
1646 case KVM_EXIT_IRQ_WINDOW_OPEN:
1647 DPRINTF("irq_window_open\n");
1648 ret = EXCP_INTERRUPT;
1649 break;
1650 case KVM_EXIT_SHUTDOWN:
1651 DPRINTF("shutdown\n");
1652 qemu_system_reset_request();
1653 ret = EXCP_INTERRUPT;
1654 break;
1655 case KVM_EXIT_UNKNOWN:
1656 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1657 (uint64_t)run->hw.hardware_exit_reason);
1658 ret = -1;
1659 break;
1660 case KVM_EXIT_INTERNAL_ERROR:
1661 ret = kvm_handle_internal_error(env, run);
1662 break;
1663 default:
1664 DPRINTF("kvm_arch_handle_exit\n");
1665 ret = kvm_arch_handle_exit(cpu, run);
1666 break;
1668 } while (ret == 0);
1670 if (ret < 0) {
1671 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1672 vm_stop(RUN_STATE_INTERNAL_ERROR);
1675 cpu->exit_request = 0;
1676 return ret;
1679 int kvm_ioctl(KVMState *s, int type, ...)
1681 int ret;
1682 void *arg;
1683 va_list ap;
1685 va_start(ap, type);
1686 arg = va_arg(ap, void *);
1687 va_end(ap);
1689 ret = ioctl(s->fd, type, arg);
1690 if (ret == -1) {
1691 ret = -errno;
1693 return ret;
1696 int kvm_vm_ioctl(KVMState *s, int type, ...)
1698 int ret;
1699 void *arg;
1700 va_list ap;
1702 va_start(ap, type);
1703 arg = va_arg(ap, void *);
1704 va_end(ap);
1706 ret = ioctl(s->vmfd, type, arg);
1707 if (ret == -1) {
1708 ret = -errno;
1710 return ret;
1713 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
1715 int ret;
1716 void *arg;
1717 va_list ap;
1719 va_start(ap, type);
1720 arg = va_arg(ap, void *);
1721 va_end(ap);
1723 ret = ioctl(cpu->kvm_fd, type, arg);
1724 if (ret == -1) {
1725 ret = -errno;
1727 return ret;
1730 int kvm_has_sync_mmu(void)
1732 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1735 int kvm_has_vcpu_events(void)
1737 return kvm_state->vcpu_events;
1740 int kvm_has_robust_singlestep(void)
1742 return kvm_state->robust_singlestep;
1745 int kvm_has_debugregs(void)
1747 return kvm_state->debugregs;
1750 int kvm_has_xsave(void)
1752 return kvm_state->xsave;
1755 int kvm_has_xcrs(void)
1757 return kvm_state->xcrs;
1760 int kvm_has_pit_state2(void)
1762 return kvm_state->pit_state2;
1765 int kvm_has_many_ioeventfds(void)
1767 if (!kvm_enabled()) {
1768 return 0;
1770 return kvm_state->many_ioeventfds;
1773 int kvm_has_gsi_routing(void)
1775 #ifdef KVM_CAP_IRQ_ROUTING
1776 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
1777 #else
1778 return false;
1779 #endif
1782 int kvm_has_intx_set_mask(void)
1784 return kvm_state->intx_set_mask;
1787 void *kvm_vmalloc(ram_addr_t size)
1789 #ifdef TARGET_S390X
1790 void *mem;
1792 mem = kvm_arch_vmalloc(size);
1793 if (mem) {
1794 return mem;
1796 #endif
1797 return qemu_vmalloc(size);
1800 void kvm_setup_guest_memory(void *start, size_t size)
1802 #ifdef CONFIG_VALGRIND_H
1803 VALGRIND_MAKE_MEM_DEFINED(start, size);
1804 #endif
1805 if (!kvm_has_sync_mmu()) {
1806 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1808 if (ret) {
1809 perror("qemu_madvise");
1810 fprintf(stderr,
1811 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1812 exit(1);
1817 #ifdef KVM_CAP_SET_GUEST_DEBUG
1818 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
1819 target_ulong pc)
1821 struct kvm_sw_breakpoint *bp;
1823 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
1824 if (bp->pc == pc) {
1825 return bp;
1828 return NULL;
1831 int kvm_sw_breakpoints_active(CPUState *cpu)
1833 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
1836 struct kvm_set_guest_debug_data {
1837 struct kvm_guest_debug dbg;
1838 CPUState *cpu;
1839 int err;
1842 static void kvm_invoke_set_guest_debug(void *data)
1844 struct kvm_set_guest_debug_data *dbg_data = data;
1846 dbg_data->err = kvm_vcpu_ioctl(dbg_data->cpu, KVM_SET_GUEST_DEBUG,
1847 &dbg_data->dbg);
1850 int kvm_update_guest_debug(CPUArchState *env, unsigned long reinject_trap)
1852 CPUState *cpu = ENV_GET_CPU(env);
1853 struct kvm_set_guest_debug_data data;
1855 data.dbg.control = reinject_trap;
1857 if (env->singlestep_enabled) {
1858 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
1860 kvm_arch_update_guest_debug(cpu, &data.dbg);
1861 data.cpu = cpu;
1863 run_on_cpu(cpu, kvm_invoke_set_guest_debug, &data);
1864 return data.err;
1867 int kvm_insert_breakpoint(CPUArchState *current_env, target_ulong addr,
1868 target_ulong len, int type)
1870 CPUState *current_cpu = ENV_GET_CPU(current_env);
1871 struct kvm_sw_breakpoint *bp;
1872 CPUArchState *env;
1873 int err;
1875 if (type == GDB_BREAKPOINT_SW) {
1876 bp = kvm_find_sw_breakpoint(current_cpu, addr);
1877 if (bp) {
1878 bp->use_count++;
1879 return 0;
1882 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
1883 if (!bp) {
1884 return -ENOMEM;
1887 bp->pc = addr;
1888 bp->use_count = 1;
1889 err = kvm_arch_insert_sw_breakpoint(current_cpu, bp);
1890 if (err) {
1891 g_free(bp);
1892 return err;
1895 QTAILQ_INSERT_HEAD(&current_cpu->kvm_state->kvm_sw_breakpoints,
1896 bp, entry);
1897 } else {
1898 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
1899 if (err) {
1900 return err;
1904 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1905 err = kvm_update_guest_debug(env, 0);
1906 if (err) {
1907 return err;
1910 return 0;
1913 int kvm_remove_breakpoint(CPUArchState *current_env, target_ulong addr,
1914 target_ulong len, int type)
1916 CPUState *current_cpu = ENV_GET_CPU(current_env);
1917 struct kvm_sw_breakpoint *bp;
1918 CPUArchState *env;
1919 int err;
1921 if (type == GDB_BREAKPOINT_SW) {
1922 bp = kvm_find_sw_breakpoint(current_cpu, addr);
1923 if (!bp) {
1924 return -ENOENT;
1927 if (bp->use_count > 1) {
1928 bp->use_count--;
1929 return 0;
1932 err = kvm_arch_remove_sw_breakpoint(current_cpu, bp);
1933 if (err) {
1934 return err;
1937 QTAILQ_REMOVE(&current_cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
1938 g_free(bp);
1939 } else {
1940 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
1941 if (err) {
1942 return err;
1946 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1947 err = kvm_update_guest_debug(env, 0);
1948 if (err) {
1949 return err;
1952 return 0;
1955 void kvm_remove_all_breakpoints(CPUArchState *current_env)
1957 CPUState *current_cpu = ENV_GET_CPU(current_env);
1958 struct kvm_sw_breakpoint *bp, *next;
1959 KVMState *s = current_cpu->kvm_state;
1960 CPUArchState *env;
1961 CPUState *cpu;
1963 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
1964 if (kvm_arch_remove_sw_breakpoint(current_cpu, bp) != 0) {
1965 /* Try harder to find a CPU that currently sees the breakpoint. */
1966 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1967 cpu = ENV_GET_CPU(env);
1968 if (kvm_arch_remove_sw_breakpoint(cpu, bp) == 0) {
1969 break;
1973 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
1974 g_free(bp);
1976 kvm_arch_remove_all_hw_breakpoints();
1978 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1979 kvm_update_guest_debug(env, 0);
1983 #else /* !KVM_CAP_SET_GUEST_DEBUG */
1985 int kvm_update_guest_debug(CPUArchState *env, unsigned long reinject_trap)
1987 return -EINVAL;
1990 int kvm_insert_breakpoint(CPUArchState *current_env, target_ulong addr,
1991 target_ulong len, int type)
1993 return -EINVAL;
1996 int kvm_remove_breakpoint(CPUArchState *current_env, target_ulong addr,
1997 target_ulong len, int type)
1999 return -EINVAL;
2002 void kvm_remove_all_breakpoints(CPUArchState *current_env)
2005 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2007 int kvm_set_signal_mask(CPUArchState *env, const sigset_t *sigset)
2009 CPUState *cpu = ENV_GET_CPU(env);
2010 struct kvm_signal_mask *sigmask;
2011 int r;
2013 if (!sigset) {
2014 return kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, NULL);
2017 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2019 sigmask->len = 8;
2020 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2021 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2022 g_free(sigmask);
2024 return r;
2026 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2028 return kvm_arch_on_sigbus_vcpu(cpu, code, addr);
2031 int kvm_on_sigbus(int code, void *addr)
2033 return kvm_arch_on_sigbus(code, addr);