qemu-ga: Plug file descriptor leak on ga_open_pidfile() error path
[qemu.git] / kvm-all.c
blobfc0c6e7798c4c8b3c4460a546f3165c3bce9a31c
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(CPUArchState *env)
219 CPUState *cpu = ENV_GET_CPU(env);
220 KVMState *s = kvm_state;
221 long mmap_size;
222 int ret;
224 DPRINTF("kvm_init_vcpu\n");
226 ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, env->cpu_index);
227 if (ret < 0) {
228 DPRINTF("kvm_create_vcpu failed\n");
229 goto err;
232 cpu->kvm_fd = ret;
233 cpu->kvm_state = s;
234 cpu->kvm_vcpu_dirty = true;
236 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
237 if (mmap_size < 0) {
238 ret = mmap_size;
239 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
240 goto err;
243 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
244 cpu->kvm_fd, 0);
245 if (cpu->kvm_run == MAP_FAILED) {
246 ret = -errno;
247 DPRINTF("mmap'ing vcpu state failed\n");
248 goto err;
251 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
252 s->coalesced_mmio_ring =
253 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
256 ret = kvm_arch_init_vcpu(cpu);
257 if (ret == 0) {
258 qemu_register_reset(kvm_reset_vcpu, cpu);
259 kvm_arch_reset_vcpu(cpu);
261 err:
262 return ret;
266 * dirty pages logging control
269 static int kvm_mem_flags(KVMState *s, bool log_dirty)
271 return log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
274 static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
276 KVMState *s = kvm_state;
277 int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
278 int old_flags;
280 old_flags = mem->flags;
282 flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty);
283 mem->flags = flags;
285 /* If nothing changed effectively, no need to issue ioctl */
286 if (s->migration_log) {
287 flags |= KVM_MEM_LOG_DIRTY_PAGES;
290 if (flags == old_flags) {
291 return 0;
294 return kvm_set_user_memory_region(s, mem);
297 static int kvm_dirty_pages_log_change(hwaddr phys_addr,
298 ram_addr_t size, bool log_dirty)
300 KVMState *s = kvm_state;
301 KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
303 if (mem == NULL) {
304 fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
305 TARGET_FMT_plx "\n", __func__, phys_addr,
306 (hwaddr)(phys_addr + size - 1));
307 return -EINVAL;
309 return kvm_slot_dirty_pages_log_change(mem, log_dirty);
312 static void kvm_log_start(MemoryListener *listener,
313 MemoryRegionSection *section)
315 int r;
317 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
318 section->size, true);
319 if (r < 0) {
320 abort();
324 static void kvm_log_stop(MemoryListener *listener,
325 MemoryRegionSection *section)
327 int r;
329 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
330 section->size, false);
331 if (r < 0) {
332 abort();
336 static int kvm_set_migration_log(int enable)
338 KVMState *s = kvm_state;
339 KVMSlot *mem;
340 int i, err;
342 s->migration_log = enable;
344 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
345 mem = &s->slots[i];
347 if (!mem->memory_size) {
348 continue;
350 if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
351 continue;
353 err = kvm_set_user_memory_region(s, mem);
354 if (err) {
355 return err;
358 return 0;
361 /* get kvm's dirty pages bitmap and update qemu's */
362 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
363 unsigned long *bitmap)
365 unsigned int i, j;
366 unsigned long page_number, c;
367 hwaddr addr, addr1;
368 unsigned int len = ((section->size / getpagesize()) + HOST_LONG_BITS - 1) / HOST_LONG_BITS;
369 unsigned long hpratio = getpagesize() / TARGET_PAGE_SIZE;
372 * bitmap-traveling is faster than memory-traveling (for addr...)
373 * especially when most of the memory is not dirty.
375 for (i = 0; i < len; i++) {
376 if (bitmap[i] != 0) {
377 c = leul_to_cpu(bitmap[i]);
378 do {
379 j = ffsl(c) - 1;
380 c &= ~(1ul << j);
381 page_number = (i * HOST_LONG_BITS + j) * hpratio;
382 addr1 = page_number * TARGET_PAGE_SIZE;
383 addr = section->offset_within_region + addr1;
384 memory_region_set_dirty(section->mr, addr,
385 TARGET_PAGE_SIZE * hpratio);
386 } while (c != 0);
389 return 0;
392 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
395 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
396 * This function updates qemu's dirty bitmap using
397 * memory_region_set_dirty(). This means all bits are set
398 * to dirty.
400 * @start_add: start of logged region.
401 * @end_addr: end of logged region.
403 static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)
405 KVMState *s = kvm_state;
406 unsigned long size, allocated_size = 0;
407 KVMDirtyLog d;
408 KVMSlot *mem;
409 int ret = 0;
410 hwaddr start_addr = section->offset_within_address_space;
411 hwaddr end_addr = start_addr + section->size;
413 d.dirty_bitmap = NULL;
414 while (start_addr < end_addr) {
415 mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
416 if (mem == NULL) {
417 break;
420 /* XXX bad kernel interface alert
421 * For dirty bitmap, kernel allocates array of size aligned to
422 * bits-per-long. But for case when the kernel is 64bits and
423 * the userspace is 32bits, userspace can't align to the same
424 * bits-per-long, since sizeof(long) is different between kernel
425 * and user space. This way, userspace will provide buffer which
426 * may be 4 bytes less than the kernel will use, resulting in
427 * userspace memory corruption (which is not detectable by valgrind
428 * too, in most cases).
429 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
430 * a hope that sizeof(long) wont become >8 any time soon.
432 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
433 /*HOST_LONG_BITS*/ 64) / 8;
434 if (!d.dirty_bitmap) {
435 d.dirty_bitmap = g_malloc(size);
436 } else if (size > allocated_size) {
437 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
439 allocated_size = size;
440 memset(d.dirty_bitmap, 0, allocated_size);
442 d.slot = mem->slot;
444 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
445 DPRINTF("ioctl failed %d\n", errno);
446 ret = -1;
447 break;
450 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
451 start_addr = mem->start_addr + mem->memory_size;
453 g_free(d.dirty_bitmap);
455 return ret;
458 static void kvm_coalesce_mmio_region(MemoryListener *listener,
459 MemoryRegionSection *secion,
460 hwaddr start, hwaddr size)
462 KVMState *s = kvm_state;
464 if (s->coalesced_mmio) {
465 struct kvm_coalesced_mmio_zone zone;
467 zone.addr = start;
468 zone.size = size;
469 zone.pad = 0;
471 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
475 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
476 MemoryRegionSection *secion,
477 hwaddr start, hwaddr size)
479 KVMState *s = kvm_state;
481 if (s->coalesced_mmio) {
482 struct kvm_coalesced_mmio_zone zone;
484 zone.addr = start;
485 zone.size = size;
486 zone.pad = 0;
488 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
492 int kvm_check_extension(KVMState *s, unsigned int extension)
494 int ret;
496 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
497 if (ret < 0) {
498 ret = 0;
501 return ret;
504 static int kvm_check_many_ioeventfds(void)
506 /* Userspace can use ioeventfd for io notification. This requires a host
507 * that supports eventfd(2) and an I/O thread; since eventfd does not
508 * support SIGIO it cannot interrupt the vcpu.
510 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
511 * can avoid creating too many ioeventfds.
513 #if defined(CONFIG_EVENTFD)
514 int ioeventfds[7];
515 int i, ret = 0;
516 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
517 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
518 if (ioeventfds[i] < 0) {
519 break;
521 ret = kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, true);
522 if (ret < 0) {
523 close(ioeventfds[i]);
524 break;
528 /* Decide whether many devices are supported or not */
529 ret = i == ARRAY_SIZE(ioeventfds);
531 while (i-- > 0) {
532 kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, false);
533 close(ioeventfds[i]);
535 return ret;
536 #else
537 return 0;
538 #endif
541 static const KVMCapabilityInfo *
542 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
544 while (list->name) {
545 if (!kvm_check_extension(s, list->value)) {
546 return list;
548 list++;
550 return NULL;
553 static void kvm_set_phys_mem(MemoryRegionSection *section, bool add)
555 KVMState *s = kvm_state;
556 KVMSlot *mem, old;
557 int err;
558 MemoryRegion *mr = section->mr;
559 bool log_dirty = memory_region_is_logging(mr);
560 hwaddr start_addr = section->offset_within_address_space;
561 ram_addr_t size = section->size;
562 void *ram = NULL;
563 unsigned delta;
565 /* kvm works in page size chunks, but the function may be called
566 with sub-page size and unaligned start address. */
567 delta = TARGET_PAGE_ALIGN(size) - size;
568 if (delta > size) {
569 return;
571 start_addr += delta;
572 size -= delta;
573 size &= TARGET_PAGE_MASK;
574 if (!size || (start_addr & ~TARGET_PAGE_MASK)) {
575 return;
578 if (!memory_region_is_ram(mr)) {
579 return;
582 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
584 while (1) {
585 mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
586 if (!mem) {
587 break;
590 if (add && start_addr >= mem->start_addr &&
591 (start_addr + size <= mem->start_addr + mem->memory_size) &&
592 (ram - start_addr == mem->ram - mem->start_addr)) {
593 /* The new slot fits into the existing one and comes with
594 * identical parameters - update flags and done. */
595 kvm_slot_dirty_pages_log_change(mem, log_dirty);
596 return;
599 old = *mem;
601 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
602 kvm_physical_sync_dirty_bitmap(section);
605 /* unregister the overlapping slot */
606 mem->memory_size = 0;
607 err = kvm_set_user_memory_region(s, mem);
608 if (err) {
609 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
610 __func__, strerror(-err));
611 abort();
614 /* Workaround for older KVM versions: we can't join slots, even not by
615 * unregistering the previous ones and then registering the larger
616 * slot. We have to maintain the existing fragmentation. Sigh.
618 * This workaround assumes that the new slot starts at the same
619 * address as the first existing one. If not or if some overlapping
620 * slot comes around later, we will fail (not seen in practice so far)
621 * - and actually require a recent KVM version. */
622 if (s->broken_set_mem_region &&
623 old.start_addr == start_addr && old.memory_size < size && add) {
624 mem = kvm_alloc_slot(s);
625 mem->memory_size = old.memory_size;
626 mem->start_addr = old.start_addr;
627 mem->ram = old.ram;
628 mem->flags = kvm_mem_flags(s, log_dirty);
630 err = kvm_set_user_memory_region(s, mem);
631 if (err) {
632 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
633 strerror(-err));
634 abort();
637 start_addr += old.memory_size;
638 ram += old.memory_size;
639 size -= old.memory_size;
640 continue;
643 /* register prefix slot */
644 if (old.start_addr < start_addr) {
645 mem = kvm_alloc_slot(s);
646 mem->memory_size = start_addr - old.start_addr;
647 mem->start_addr = old.start_addr;
648 mem->ram = old.ram;
649 mem->flags = kvm_mem_flags(s, log_dirty);
651 err = kvm_set_user_memory_region(s, mem);
652 if (err) {
653 fprintf(stderr, "%s: error registering prefix slot: %s\n",
654 __func__, strerror(-err));
655 #ifdef TARGET_PPC
656 fprintf(stderr, "%s: This is probably because your kernel's " \
657 "PAGE_SIZE is too big. Please try to use 4k " \
658 "PAGE_SIZE!\n", __func__);
659 #endif
660 abort();
664 /* register suffix slot */
665 if (old.start_addr + old.memory_size > start_addr + size) {
666 ram_addr_t size_delta;
668 mem = kvm_alloc_slot(s);
669 mem->start_addr = start_addr + size;
670 size_delta = mem->start_addr - old.start_addr;
671 mem->memory_size = old.memory_size - size_delta;
672 mem->ram = old.ram + size_delta;
673 mem->flags = kvm_mem_flags(s, log_dirty);
675 err = kvm_set_user_memory_region(s, mem);
676 if (err) {
677 fprintf(stderr, "%s: error registering suffix slot: %s\n",
678 __func__, strerror(-err));
679 abort();
684 /* in case the KVM bug workaround already "consumed" the new slot */
685 if (!size) {
686 return;
688 if (!add) {
689 return;
691 mem = kvm_alloc_slot(s);
692 mem->memory_size = size;
693 mem->start_addr = start_addr;
694 mem->ram = ram;
695 mem->flags = kvm_mem_flags(s, log_dirty);
697 err = kvm_set_user_memory_region(s, mem);
698 if (err) {
699 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
700 strerror(-err));
701 abort();
705 static void kvm_region_add(MemoryListener *listener,
706 MemoryRegionSection *section)
708 kvm_set_phys_mem(section, true);
711 static void kvm_region_del(MemoryListener *listener,
712 MemoryRegionSection *section)
714 kvm_set_phys_mem(section, false);
717 static void kvm_log_sync(MemoryListener *listener,
718 MemoryRegionSection *section)
720 int r;
722 r = kvm_physical_sync_dirty_bitmap(section);
723 if (r < 0) {
724 abort();
728 static void kvm_log_global_start(struct MemoryListener *listener)
730 int r;
732 r = kvm_set_migration_log(1);
733 assert(r >= 0);
736 static void kvm_log_global_stop(struct MemoryListener *listener)
738 int r;
740 r = kvm_set_migration_log(0);
741 assert(r >= 0);
744 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
745 MemoryRegionSection *section,
746 bool match_data, uint64_t data,
747 EventNotifier *e)
749 int fd = event_notifier_get_fd(e);
750 int r;
752 assert(match_data && section->size <= 8);
754 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
755 data, true, section->size);
756 if (r < 0) {
757 abort();
761 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
762 MemoryRegionSection *section,
763 bool match_data, uint64_t data,
764 EventNotifier *e)
766 int fd = event_notifier_get_fd(e);
767 int r;
769 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
770 data, false, section->size);
771 if (r < 0) {
772 abort();
776 static void kvm_io_ioeventfd_add(MemoryListener *listener,
777 MemoryRegionSection *section,
778 bool match_data, uint64_t data,
779 EventNotifier *e)
781 int fd = event_notifier_get_fd(e);
782 int r;
784 assert(match_data && section->size == 2);
786 r = kvm_set_ioeventfd_pio_word(fd, section->offset_within_address_space,
787 data, true);
788 if (r < 0) {
789 abort();
793 static void kvm_io_ioeventfd_del(MemoryListener *listener,
794 MemoryRegionSection *section,
795 bool match_data, uint64_t data,
796 EventNotifier *e)
799 int fd = event_notifier_get_fd(e);
800 int r;
802 r = kvm_set_ioeventfd_pio_word(fd, section->offset_within_address_space,
803 data, false);
804 if (r < 0) {
805 abort();
809 static MemoryListener kvm_memory_listener = {
810 .region_add = kvm_region_add,
811 .region_del = kvm_region_del,
812 .log_start = kvm_log_start,
813 .log_stop = kvm_log_stop,
814 .log_sync = kvm_log_sync,
815 .log_global_start = kvm_log_global_start,
816 .log_global_stop = kvm_log_global_stop,
817 .eventfd_add = kvm_mem_ioeventfd_add,
818 .eventfd_del = kvm_mem_ioeventfd_del,
819 .coalesced_mmio_add = kvm_coalesce_mmio_region,
820 .coalesced_mmio_del = kvm_uncoalesce_mmio_region,
821 .priority = 10,
824 static MemoryListener kvm_io_listener = {
825 .eventfd_add = kvm_io_ioeventfd_add,
826 .eventfd_del = kvm_io_ioeventfd_del,
827 .priority = 10,
830 static void kvm_handle_interrupt(CPUArchState *env, int mask)
832 CPUState *cpu = ENV_GET_CPU(env);
834 env->interrupt_request |= mask;
836 if (!qemu_cpu_is_self(cpu)) {
837 qemu_cpu_kick(cpu);
841 int kvm_set_irq(KVMState *s, int irq, int level)
843 struct kvm_irq_level event;
844 int ret;
846 assert(kvm_async_interrupts_enabled());
848 event.level = level;
849 event.irq = irq;
850 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
851 if (ret < 0) {
852 perror("kvm_set_irq");
853 abort();
856 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
859 #ifdef KVM_CAP_IRQ_ROUTING
860 typedef struct KVMMSIRoute {
861 struct kvm_irq_routing_entry kroute;
862 QTAILQ_ENTRY(KVMMSIRoute) entry;
863 } KVMMSIRoute;
865 static void set_gsi(KVMState *s, unsigned int gsi)
867 s->used_gsi_bitmap[gsi / 32] |= 1U << (gsi % 32);
870 static void clear_gsi(KVMState *s, unsigned int gsi)
872 s->used_gsi_bitmap[gsi / 32] &= ~(1U << (gsi % 32));
875 static void kvm_init_irq_routing(KVMState *s)
877 int gsi_count, i;
879 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING);
880 if (gsi_count > 0) {
881 unsigned int gsi_bits, i;
883 /* Round up so we can search ints using ffs */
884 gsi_bits = ALIGN(gsi_count, 32);
885 s->used_gsi_bitmap = g_malloc0(gsi_bits / 8);
886 s->gsi_count = gsi_count;
888 /* Mark any over-allocated bits as already in use */
889 for (i = gsi_count; i < gsi_bits; i++) {
890 set_gsi(s, i);
894 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
895 s->nr_allocated_irq_routes = 0;
897 if (!s->direct_msi) {
898 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
899 QTAILQ_INIT(&s->msi_hashtab[i]);
903 kvm_arch_init_irq_routing(s);
906 static void kvm_irqchip_commit_routes(KVMState *s)
908 int ret;
910 s->irq_routes->flags = 0;
911 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
912 assert(ret == 0);
915 static void kvm_add_routing_entry(KVMState *s,
916 struct kvm_irq_routing_entry *entry)
918 struct kvm_irq_routing_entry *new;
919 int n, size;
921 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
922 n = s->nr_allocated_irq_routes * 2;
923 if (n < 64) {
924 n = 64;
926 size = sizeof(struct kvm_irq_routing);
927 size += n * sizeof(*new);
928 s->irq_routes = g_realloc(s->irq_routes, size);
929 s->nr_allocated_irq_routes = n;
931 n = s->irq_routes->nr++;
932 new = &s->irq_routes->entries[n];
933 memset(new, 0, sizeof(*new));
934 new->gsi = entry->gsi;
935 new->type = entry->type;
936 new->flags = entry->flags;
937 new->u = entry->u;
939 set_gsi(s, entry->gsi);
941 kvm_irqchip_commit_routes(s);
944 static int kvm_update_routing_entry(KVMState *s,
945 struct kvm_irq_routing_entry *new_entry)
947 struct kvm_irq_routing_entry *entry;
948 int n;
950 for (n = 0; n < s->irq_routes->nr; n++) {
951 entry = &s->irq_routes->entries[n];
952 if (entry->gsi != new_entry->gsi) {
953 continue;
956 entry->type = new_entry->type;
957 entry->flags = new_entry->flags;
958 entry->u = new_entry->u;
960 kvm_irqchip_commit_routes(s);
962 return 0;
965 return -ESRCH;
968 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
970 struct kvm_irq_routing_entry e;
972 assert(pin < s->gsi_count);
974 e.gsi = irq;
975 e.type = KVM_IRQ_ROUTING_IRQCHIP;
976 e.flags = 0;
977 e.u.irqchip.irqchip = irqchip;
978 e.u.irqchip.pin = pin;
979 kvm_add_routing_entry(s, &e);
982 void kvm_irqchip_release_virq(KVMState *s, int virq)
984 struct kvm_irq_routing_entry *e;
985 int i;
987 for (i = 0; i < s->irq_routes->nr; i++) {
988 e = &s->irq_routes->entries[i];
989 if (e->gsi == virq) {
990 s->irq_routes->nr--;
991 *e = s->irq_routes->entries[s->irq_routes->nr];
994 clear_gsi(s, virq);
997 static unsigned int kvm_hash_msi(uint32_t data)
999 /* This is optimized for IA32 MSI layout. However, no other arch shall
1000 * repeat the mistake of not providing a direct MSI injection API. */
1001 return data & 0xff;
1004 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1006 KVMMSIRoute *route, *next;
1007 unsigned int hash;
1009 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1010 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1011 kvm_irqchip_release_virq(s, route->kroute.gsi);
1012 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1013 g_free(route);
1018 static int kvm_irqchip_get_virq(KVMState *s)
1020 uint32_t *word = s->used_gsi_bitmap;
1021 int max_words = ALIGN(s->gsi_count, 32) / 32;
1022 int i, bit;
1023 bool retry = true;
1025 again:
1026 /* Return the lowest unused GSI in the bitmap */
1027 for (i = 0; i < max_words; i++) {
1028 bit = ffs(~word[i]);
1029 if (!bit) {
1030 continue;
1033 return bit - 1 + i * 32;
1035 if (!s->direct_msi && retry) {
1036 retry = false;
1037 kvm_flush_dynamic_msi_routes(s);
1038 goto again;
1040 return -ENOSPC;
1044 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1046 unsigned int hash = kvm_hash_msi(msg.data);
1047 KVMMSIRoute *route;
1049 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1050 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1051 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1052 route->kroute.u.msi.data == msg.data) {
1053 return route;
1056 return NULL;
1059 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1061 struct kvm_msi msi;
1062 KVMMSIRoute *route;
1064 if (s->direct_msi) {
1065 msi.address_lo = (uint32_t)msg.address;
1066 msi.address_hi = msg.address >> 32;
1067 msi.data = msg.data;
1068 msi.flags = 0;
1069 memset(msi.pad, 0, sizeof(msi.pad));
1071 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1074 route = kvm_lookup_msi_route(s, msg);
1075 if (!route) {
1076 int virq;
1078 virq = kvm_irqchip_get_virq(s);
1079 if (virq < 0) {
1080 return virq;
1083 route = g_malloc(sizeof(KVMMSIRoute));
1084 route->kroute.gsi = virq;
1085 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1086 route->kroute.flags = 0;
1087 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1088 route->kroute.u.msi.address_hi = msg.address >> 32;
1089 route->kroute.u.msi.data = msg.data;
1091 kvm_add_routing_entry(s, &route->kroute);
1093 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1094 entry);
1097 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1099 return kvm_set_irq(s, route->kroute.gsi, 1);
1102 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1104 struct kvm_irq_routing_entry kroute;
1105 int virq;
1107 if (!kvm_gsi_routing_enabled()) {
1108 return -ENOSYS;
1111 virq = kvm_irqchip_get_virq(s);
1112 if (virq < 0) {
1113 return virq;
1116 kroute.gsi = virq;
1117 kroute.type = KVM_IRQ_ROUTING_MSI;
1118 kroute.flags = 0;
1119 kroute.u.msi.address_lo = (uint32_t)msg.address;
1120 kroute.u.msi.address_hi = msg.address >> 32;
1121 kroute.u.msi.data = msg.data;
1123 kvm_add_routing_entry(s, &kroute);
1125 return virq;
1128 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1130 struct kvm_irq_routing_entry kroute;
1132 if (!kvm_irqchip_in_kernel()) {
1133 return -ENOSYS;
1136 kroute.gsi = virq;
1137 kroute.type = KVM_IRQ_ROUTING_MSI;
1138 kroute.flags = 0;
1139 kroute.u.msi.address_lo = (uint32_t)msg.address;
1140 kroute.u.msi.address_hi = msg.address >> 32;
1141 kroute.u.msi.data = msg.data;
1143 return kvm_update_routing_entry(s, &kroute);
1146 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1148 struct kvm_irqfd irqfd = {
1149 .fd = fd,
1150 .gsi = virq,
1151 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1154 if (!kvm_irqfds_enabled()) {
1155 return -ENOSYS;
1158 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1161 #else /* !KVM_CAP_IRQ_ROUTING */
1163 static void kvm_init_irq_routing(KVMState *s)
1167 void kvm_irqchip_release_virq(KVMState *s, int virq)
1171 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1173 abort();
1176 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1178 return -ENOSYS;
1181 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1183 abort();
1185 #endif /* !KVM_CAP_IRQ_ROUTING */
1187 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n, int virq)
1189 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), virq, true);
1192 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n, int virq)
1194 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), virq, false);
1197 static int kvm_irqchip_create(KVMState *s)
1199 QemuOptsList *list = qemu_find_opts("machine");
1200 int ret;
1202 if (QTAILQ_EMPTY(&list->head) ||
1203 !qemu_opt_get_bool(QTAILQ_FIRST(&list->head),
1204 "kernel_irqchip", true) ||
1205 !kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
1206 return 0;
1209 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1210 if (ret < 0) {
1211 fprintf(stderr, "Create kernel irqchip failed\n");
1212 return ret;
1215 kvm_kernel_irqchip = true;
1216 /* If we have an in-kernel IRQ chip then we must have asynchronous
1217 * interrupt delivery (though the reverse is not necessarily true)
1219 kvm_async_interrupts_allowed = true;
1221 kvm_init_irq_routing(s);
1223 return 0;
1226 static int kvm_max_vcpus(KVMState *s)
1228 int ret;
1230 /* Find number of supported CPUs using the recommended
1231 * procedure from the kernel API documentation to cope with
1232 * older kernels that may be missing capabilities.
1234 ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1235 if (ret) {
1236 return ret;
1238 ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
1239 if (ret) {
1240 return ret;
1243 return 4;
1246 int kvm_init(void)
1248 static const char upgrade_note[] =
1249 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1250 "(see http://sourceforge.net/projects/kvm).\n";
1251 KVMState *s;
1252 const KVMCapabilityInfo *missing_cap;
1253 int ret;
1254 int i;
1255 int max_vcpus;
1257 s = g_malloc0(sizeof(KVMState));
1260 * On systems where the kernel can support different base page
1261 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1262 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1263 * page size for the system though.
1265 assert(TARGET_PAGE_SIZE <= getpagesize());
1267 #ifdef KVM_CAP_SET_GUEST_DEBUG
1268 QTAILQ_INIT(&s->kvm_sw_breakpoints);
1269 #endif
1270 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
1271 s->slots[i].slot = i;
1273 s->vmfd = -1;
1274 s->fd = qemu_open("/dev/kvm", O_RDWR);
1275 if (s->fd == -1) {
1276 fprintf(stderr, "Could not access KVM kernel module: %m\n");
1277 ret = -errno;
1278 goto err;
1281 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1282 if (ret < KVM_API_VERSION) {
1283 if (ret > 0) {
1284 ret = -EINVAL;
1286 fprintf(stderr, "kvm version too old\n");
1287 goto err;
1290 if (ret > KVM_API_VERSION) {
1291 ret = -EINVAL;
1292 fprintf(stderr, "kvm version not supported\n");
1293 goto err;
1296 max_vcpus = kvm_max_vcpus(s);
1297 if (smp_cpus > max_vcpus) {
1298 ret = -EINVAL;
1299 fprintf(stderr, "Number of SMP cpus requested (%d) exceeds max cpus "
1300 "supported by KVM (%d)\n", smp_cpus, max_vcpus);
1301 goto err;
1304 s->vmfd = kvm_ioctl(s, KVM_CREATE_VM, 0);
1305 if (s->vmfd < 0) {
1306 #ifdef TARGET_S390X
1307 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
1308 "your host kernel command line\n");
1309 #endif
1310 ret = s->vmfd;
1311 goto err;
1314 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1315 if (!missing_cap) {
1316 missing_cap =
1317 kvm_check_extension_list(s, kvm_arch_required_capabilities);
1319 if (missing_cap) {
1320 ret = -EINVAL;
1321 fprintf(stderr, "kvm does not support %s\n%s",
1322 missing_cap->name, upgrade_note);
1323 goto err;
1326 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1328 s->broken_set_mem_region = 1;
1329 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
1330 if (ret > 0) {
1331 s->broken_set_mem_region = 0;
1334 #ifdef KVM_CAP_VCPU_EVENTS
1335 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1336 #endif
1338 s->robust_singlestep =
1339 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1341 #ifdef KVM_CAP_DEBUGREGS
1342 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1343 #endif
1345 #ifdef KVM_CAP_XSAVE
1346 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1347 #endif
1349 #ifdef KVM_CAP_XCRS
1350 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1351 #endif
1353 #ifdef KVM_CAP_PIT_STATE2
1354 s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1355 #endif
1357 #ifdef KVM_CAP_IRQ_ROUTING
1358 s->direct_msi = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1359 #endif
1361 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1363 s->irq_set_ioctl = KVM_IRQ_LINE;
1364 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1365 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1368 ret = kvm_arch_init(s);
1369 if (ret < 0) {
1370 goto err;
1373 ret = kvm_irqchip_create(s);
1374 if (ret < 0) {
1375 goto err;
1378 kvm_state = s;
1379 memory_listener_register(&kvm_memory_listener, &address_space_memory);
1380 memory_listener_register(&kvm_io_listener, &address_space_io);
1382 s->many_ioeventfds = kvm_check_many_ioeventfds();
1384 cpu_interrupt_handler = kvm_handle_interrupt;
1386 return 0;
1388 err:
1389 if (s->vmfd >= 0) {
1390 close(s->vmfd);
1392 if (s->fd != -1) {
1393 close(s->fd);
1395 g_free(s);
1397 return ret;
1400 static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
1401 uint32_t count)
1403 int i;
1404 uint8_t *ptr = data;
1406 for (i = 0; i < count; i++) {
1407 if (direction == KVM_EXIT_IO_IN) {
1408 switch (size) {
1409 case 1:
1410 stb_p(ptr, cpu_inb(port));
1411 break;
1412 case 2:
1413 stw_p(ptr, cpu_inw(port));
1414 break;
1415 case 4:
1416 stl_p(ptr, cpu_inl(port));
1417 break;
1419 } else {
1420 switch (size) {
1421 case 1:
1422 cpu_outb(port, ldub_p(ptr));
1423 break;
1424 case 2:
1425 cpu_outw(port, lduw_p(ptr));
1426 break;
1427 case 4:
1428 cpu_outl(port, ldl_p(ptr));
1429 break;
1433 ptr += size;
1437 static int kvm_handle_internal_error(CPUArchState *env, struct kvm_run *run)
1439 CPUState *cpu = ENV_GET_CPU(env);
1441 fprintf(stderr, "KVM internal error.");
1442 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1443 int i;
1445 fprintf(stderr, " Suberror: %d\n", run->internal.suberror);
1446 for (i = 0; i < run->internal.ndata; ++i) {
1447 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1448 i, (uint64_t)run->internal.data[i]);
1450 } else {
1451 fprintf(stderr, "\n");
1453 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1454 fprintf(stderr, "emulation failure\n");
1455 if (!kvm_arch_stop_on_emulation_error(cpu)) {
1456 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1457 return EXCP_INTERRUPT;
1460 /* FIXME: Should trigger a qmp message to let management know
1461 * something went wrong.
1463 return -1;
1466 void kvm_flush_coalesced_mmio_buffer(void)
1468 KVMState *s = kvm_state;
1470 if (s->coalesced_flush_in_progress) {
1471 return;
1474 s->coalesced_flush_in_progress = true;
1476 if (s->coalesced_mmio_ring) {
1477 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1478 while (ring->first != ring->last) {
1479 struct kvm_coalesced_mmio *ent;
1481 ent = &ring->coalesced_mmio[ring->first];
1483 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1484 smp_wmb();
1485 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1489 s->coalesced_flush_in_progress = false;
1492 static void do_kvm_cpu_synchronize_state(void *arg)
1494 CPUState *cpu = arg;
1496 if (!cpu->kvm_vcpu_dirty) {
1497 kvm_arch_get_registers(cpu);
1498 cpu->kvm_vcpu_dirty = true;
1502 void kvm_cpu_synchronize_state(CPUArchState *env)
1504 CPUState *cpu = ENV_GET_CPU(env);
1506 if (!cpu->kvm_vcpu_dirty) {
1507 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, cpu);
1511 void kvm_cpu_synchronize_post_reset(CPUArchState *env)
1513 CPUState *cpu = ENV_GET_CPU(env);
1515 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1516 cpu->kvm_vcpu_dirty = false;
1519 void kvm_cpu_synchronize_post_init(CPUArchState *env)
1521 CPUState *cpu = ENV_GET_CPU(env);
1523 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1524 cpu->kvm_vcpu_dirty = false;
1527 int kvm_cpu_exec(CPUArchState *env)
1529 CPUState *cpu = ENV_GET_CPU(env);
1530 struct kvm_run *run = cpu->kvm_run;
1531 int ret, run_ret;
1533 DPRINTF("kvm_cpu_exec()\n");
1535 if (kvm_arch_process_async_events(cpu)) {
1536 env->exit_request = 0;
1537 return EXCP_HLT;
1540 do {
1541 if (cpu->kvm_vcpu_dirty) {
1542 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1543 cpu->kvm_vcpu_dirty = false;
1546 kvm_arch_pre_run(cpu, run);
1547 if (env->exit_request) {
1548 DPRINTF("interrupt exit requested\n");
1550 * KVM requires us to reenter the kernel after IO exits to complete
1551 * instruction emulation. This self-signal will ensure that we
1552 * leave ASAP again.
1554 qemu_cpu_kick_self();
1556 qemu_mutex_unlock_iothread();
1558 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
1560 qemu_mutex_lock_iothread();
1561 kvm_arch_post_run(cpu, run);
1563 if (run_ret < 0) {
1564 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1565 DPRINTF("io window exit\n");
1566 ret = EXCP_INTERRUPT;
1567 break;
1569 fprintf(stderr, "error: kvm run failed %s\n",
1570 strerror(-run_ret));
1571 abort();
1574 switch (run->exit_reason) {
1575 case KVM_EXIT_IO:
1576 DPRINTF("handle_io\n");
1577 kvm_handle_io(run->io.port,
1578 (uint8_t *)run + run->io.data_offset,
1579 run->io.direction,
1580 run->io.size,
1581 run->io.count);
1582 ret = 0;
1583 break;
1584 case KVM_EXIT_MMIO:
1585 DPRINTF("handle_mmio\n");
1586 cpu_physical_memory_rw(run->mmio.phys_addr,
1587 run->mmio.data,
1588 run->mmio.len,
1589 run->mmio.is_write);
1590 ret = 0;
1591 break;
1592 case KVM_EXIT_IRQ_WINDOW_OPEN:
1593 DPRINTF("irq_window_open\n");
1594 ret = EXCP_INTERRUPT;
1595 break;
1596 case KVM_EXIT_SHUTDOWN:
1597 DPRINTF("shutdown\n");
1598 qemu_system_reset_request();
1599 ret = EXCP_INTERRUPT;
1600 break;
1601 case KVM_EXIT_UNKNOWN:
1602 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1603 (uint64_t)run->hw.hardware_exit_reason);
1604 ret = -1;
1605 break;
1606 case KVM_EXIT_INTERNAL_ERROR:
1607 ret = kvm_handle_internal_error(env, run);
1608 break;
1609 default:
1610 DPRINTF("kvm_arch_handle_exit\n");
1611 ret = kvm_arch_handle_exit(cpu, run);
1612 break;
1614 } while (ret == 0);
1616 if (ret < 0) {
1617 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1618 vm_stop(RUN_STATE_INTERNAL_ERROR);
1621 env->exit_request = 0;
1622 return ret;
1625 int kvm_ioctl(KVMState *s, int type, ...)
1627 int ret;
1628 void *arg;
1629 va_list ap;
1631 va_start(ap, type);
1632 arg = va_arg(ap, void *);
1633 va_end(ap);
1635 ret = ioctl(s->fd, type, arg);
1636 if (ret == -1) {
1637 ret = -errno;
1639 return ret;
1642 int kvm_vm_ioctl(KVMState *s, int type, ...)
1644 int ret;
1645 void *arg;
1646 va_list ap;
1648 va_start(ap, type);
1649 arg = va_arg(ap, void *);
1650 va_end(ap);
1652 ret = ioctl(s->vmfd, type, arg);
1653 if (ret == -1) {
1654 ret = -errno;
1656 return ret;
1659 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
1661 int ret;
1662 void *arg;
1663 va_list ap;
1665 va_start(ap, type);
1666 arg = va_arg(ap, void *);
1667 va_end(ap);
1669 ret = ioctl(cpu->kvm_fd, type, arg);
1670 if (ret == -1) {
1671 ret = -errno;
1673 return ret;
1676 int kvm_has_sync_mmu(void)
1678 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1681 int kvm_has_vcpu_events(void)
1683 return kvm_state->vcpu_events;
1686 int kvm_has_robust_singlestep(void)
1688 return kvm_state->robust_singlestep;
1691 int kvm_has_debugregs(void)
1693 return kvm_state->debugregs;
1696 int kvm_has_xsave(void)
1698 return kvm_state->xsave;
1701 int kvm_has_xcrs(void)
1703 return kvm_state->xcrs;
1706 int kvm_has_pit_state2(void)
1708 return kvm_state->pit_state2;
1711 int kvm_has_many_ioeventfds(void)
1713 if (!kvm_enabled()) {
1714 return 0;
1716 return kvm_state->many_ioeventfds;
1719 int kvm_has_gsi_routing(void)
1721 #ifdef KVM_CAP_IRQ_ROUTING
1722 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
1723 #else
1724 return false;
1725 #endif
1728 int kvm_has_intx_set_mask(void)
1730 return kvm_state->intx_set_mask;
1733 void *kvm_vmalloc(ram_addr_t size)
1735 #ifdef TARGET_S390X
1736 void *mem;
1738 mem = kvm_arch_vmalloc(size);
1739 if (mem) {
1740 return mem;
1742 #endif
1743 return qemu_vmalloc(size);
1746 void kvm_setup_guest_memory(void *start, size_t size)
1748 #ifdef CONFIG_VALGRIND_H
1749 VALGRIND_MAKE_MEM_DEFINED(start, size);
1750 #endif
1751 if (!kvm_has_sync_mmu()) {
1752 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1754 if (ret) {
1755 perror("qemu_madvise");
1756 fprintf(stderr,
1757 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1758 exit(1);
1763 #ifdef KVM_CAP_SET_GUEST_DEBUG
1764 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
1765 target_ulong pc)
1767 struct kvm_sw_breakpoint *bp;
1769 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
1770 if (bp->pc == pc) {
1771 return bp;
1774 return NULL;
1777 int kvm_sw_breakpoints_active(CPUState *cpu)
1779 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
1782 struct kvm_set_guest_debug_data {
1783 struct kvm_guest_debug dbg;
1784 CPUState *cpu;
1785 int err;
1788 static void kvm_invoke_set_guest_debug(void *data)
1790 struct kvm_set_guest_debug_data *dbg_data = data;
1792 dbg_data->err = kvm_vcpu_ioctl(dbg_data->cpu, KVM_SET_GUEST_DEBUG,
1793 &dbg_data->dbg);
1796 int kvm_update_guest_debug(CPUArchState *env, unsigned long reinject_trap)
1798 CPUState *cpu = ENV_GET_CPU(env);
1799 struct kvm_set_guest_debug_data data;
1801 data.dbg.control = reinject_trap;
1803 if (env->singlestep_enabled) {
1804 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
1806 kvm_arch_update_guest_debug(cpu, &data.dbg);
1807 data.cpu = cpu;
1809 run_on_cpu(cpu, kvm_invoke_set_guest_debug, &data);
1810 return data.err;
1813 int kvm_insert_breakpoint(CPUArchState *current_env, target_ulong addr,
1814 target_ulong len, int type)
1816 CPUState *current_cpu = ENV_GET_CPU(current_env);
1817 struct kvm_sw_breakpoint *bp;
1818 CPUArchState *env;
1819 int err;
1821 if (type == GDB_BREAKPOINT_SW) {
1822 bp = kvm_find_sw_breakpoint(current_cpu, addr);
1823 if (bp) {
1824 bp->use_count++;
1825 return 0;
1828 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
1829 if (!bp) {
1830 return -ENOMEM;
1833 bp->pc = addr;
1834 bp->use_count = 1;
1835 err = kvm_arch_insert_sw_breakpoint(current_cpu, bp);
1836 if (err) {
1837 g_free(bp);
1838 return err;
1841 QTAILQ_INSERT_HEAD(&current_cpu->kvm_state->kvm_sw_breakpoints,
1842 bp, entry);
1843 } else {
1844 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
1845 if (err) {
1846 return err;
1850 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1851 err = kvm_update_guest_debug(env, 0);
1852 if (err) {
1853 return err;
1856 return 0;
1859 int kvm_remove_breakpoint(CPUArchState *current_env, target_ulong addr,
1860 target_ulong len, int type)
1862 CPUState *current_cpu = ENV_GET_CPU(current_env);
1863 struct kvm_sw_breakpoint *bp;
1864 CPUArchState *env;
1865 int err;
1867 if (type == GDB_BREAKPOINT_SW) {
1868 bp = kvm_find_sw_breakpoint(current_cpu, addr);
1869 if (!bp) {
1870 return -ENOENT;
1873 if (bp->use_count > 1) {
1874 bp->use_count--;
1875 return 0;
1878 err = kvm_arch_remove_sw_breakpoint(current_cpu, bp);
1879 if (err) {
1880 return err;
1883 QTAILQ_REMOVE(&current_cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
1884 g_free(bp);
1885 } else {
1886 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
1887 if (err) {
1888 return err;
1892 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1893 err = kvm_update_guest_debug(env, 0);
1894 if (err) {
1895 return err;
1898 return 0;
1901 void kvm_remove_all_breakpoints(CPUArchState *current_env)
1903 CPUState *current_cpu = ENV_GET_CPU(current_env);
1904 struct kvm_sw_breakpoint *bp, *next;
1905 KVMState *s = current_cpu->kvm_state;
1906 CPUArchState *env;
1907 CPUState *cpu;
1909 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
1910 if (kvm_arch_remove_sw_breakpoint(current_cpu, bp) != 0) {
1911 /* Try harder to find a CPU that currently sees the breakpoint. */
1912 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1913 cpu = ENV_GET_CPU(env);
1914 if (kvm_arch_remove_sw_breakpoint(cpu, bp) == 0) {
1915 break;
1919 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
1920 g_free(bp);
1922 kvm_arch_remove_all_hw_breakpoints();
1924 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1925 kvm_update_guest_debug(env, 0);
1929 #else /* !KVM_CAP_SET_GUEST_DEBUG */
1931 int kvm_update_guest_debug(CPUArchState *env, unsigned long reinject_trap)
1933 return -EINVAL;
1936 int kvm_insert_breakpoint(CPUArchState *current_env, target_ulong addr,
1937 target_ulong len, int type)
1939 return -EINVAL;
1942 int kvm_remove_breakpoint(CPUArchState *current_env, target_ulong addr,
1943 target_ulong len, int type)
1945 return -EINVAL;
1948 void kvm_remove_all_breakpoints(CPUArchState *current_env)
1951 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
1953 int kvm_set_signal_mask(CPUArchState *env, const sigset_t *sigset)
1955 CPUState *cpu = ENV_GET_CPU(env);
1956 struct kvm_signal_mask *sigmask;
1957 int r;
1959 if (!sigset) {
1960 return kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, NULL);
1963 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
1965 sigmask->len = 8;
1966 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
1967 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
1968 g_free(sigmask);
1970 return r;
1973 int kvm_set_ioeventfd_mmio(int fd, uint32_t addr, uint32_t val, bool assign,
1974 uint32_t size)
1976 int ret;
1977 struct kvm_ioeventfd iofd;
1979 iofd.datamatch = val;
1980 iofd.addr = addr;
1981 iofd.len = size;
1982 iofd.flags = KVM_IOEVENTFD_FLAG_DATAMATCH;
1983 iofd.fd = fd;
1985 if (!kvm_enabled()) {
1986 return -ENOSYS;
1989 if (!assign) {
1990 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1993 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
1995 if (ret < 0) {
1996 return -errno;
1999 return 0;
2002 int kvm_set_ioeventfd_pio_word(int fd, uint16_t addr, uint16_t val, bool assign)
2004 struct kvm_ioeventfd kick = {
2005 .datamatch = val,
2006 .addr = addr,
2007 .len = 2,
2008 .flags = KVM_IOEVENTFD_FLAG_DATAMATCH | KVM_IOEVENTFD_FLAG_PIO,
2009 .fd = fd,
2011 int r;
2012 if (!kvm_enabled()) {
2013 return -ENOSYS;
2015 if (!assign) {
2016 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
2018 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
2019 if (r < 0) {
2020 return r;
2022 return 0;
2025 int kvm_on_sigbus_vcpu(CPUArchState *env, int code, void *addr)
2027 CPUState *cpu = ENV_GET_CPU(env);
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);