memory: remove memory_region_set_offset()
[qemu-kvm.git] / kvm-all.c
blob0b87658f6a182099b1552b322e48d0f90b07653c
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-barrier.h"
25 #include "sysemu.h"
26 #include "hw/hw.h"
27 #include "gdbstub.h"
28 #include "kvm.h"
29 #include "bswap.h"
30 #include "memory.h"
32 /* This check must be after config-host.h is included */
33 #ifdef CONFIG_EVENTFD
34 #include <sys/eventfd.h>
35 #endif
37 /* KVM uses PAGE_SIZE in it's definition of COALESCED_MMIO_MAX */
38 #define PAGE_SIZE TARGET_PAGE_SIZE
40 //#define DEBUG_KVM
42 #ifdef DEBUG_KVM
43 #define DPRINTF(fmt, ...) \
44 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
45 #else
46 #define DPRINTF(fmt, ...) \
47 do { } while (0)
48 #endif
50 typedef struct KVMSlot
52 target_phys_addr_t start_addr;
53 ram_addr_t memory_size;
54 void *ram;
55 int slot;
56 int flags;
57 } KVMSlot;
59 typedef struct kvm_dirty_log KVMDirtyLog;
61 struct KVMState
63 KVMSlot slots[32];
64 int fd;
65 int vmfd;
66 int coalesced_mmio;
67 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
68 bool coalesced_flush_in_progress;
69 int broken_set_mem_region;
70 int migration_log;
71 int vcpu_events;
72 int robust_singlestep;
73 int debugregs;
74 #ifdef KVM_CAP_SET_GUEST_DEBUG
75 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
76 #endif
77 int irqchip_in_kernel;
78 int pit_in_kernel;
79 int xsave, xcrs;
80 int many_ioeventfds;
81 int irqchip_inject_ioctl;
82 #ifdef KVM_CAP_IRQ_ROUTING
83 struct kvm_irq_routing *irq_routes;
84 int nr_allocated_irq_routes;
85 uint32_t *used_gsi_bitmap;
86 unsigned int max_gsi;
87 #endif
90 KVMState *kvm_state;
92 static const KVMCapabilityInfo kvm_required_capabilites[] = {
93 KVM_CAP_INFO(USER_MEMORY),
94 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
95 KVM_CAP_LAST_INFO
98 static KVMSlot *kvm_alloc_slot(KVMState *s)
100 int i;
102 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
103 if (s->slots[i].memory_size == 0) {
104 return &s->slots[i];
108 fprintf(stderr, "%s: no free slot available\n", __func__);
109 abort();
112 static KVMSlot *kvm_lookup_matching_slot(KVMState *s,
113 target_phys_addr_t start_addr,
114 target_phys_addr_t end_addr)
116 int i;
118 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
119 KVMSlot *mem = &s->slots[i];
121 if (start_addr == mem->start_addr &&
122 end_addr == mem->start_addr + mem->memory_size) {
123 return mem;
127 return NULL;
131 * Find overlapping slot with lowest start address
133 static KVMSlot *kvm_lookup_overlapping_slot(KVMState *s,
134 target_phys_addr_t start_addr,
135 target_phys_addr_t end_addr)
137 KVMSlot *found = NULL;
138 int i;
140 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
141 KVMSlot *mem = &s->slots[i];
143 if (mem->memory_size == 0 ||
144 (found && found->start_addr < mem->start_addr)) {
145 continue;
148 if (end_addr > mem->start_addr &&
149 start_addr < mem->start_addr + mem->memory_size) {
150 found = mem;
154 return found;
157 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
158 target_phys_addr_t *phys_addr)
160 int i;
162 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
163 KVMSlot *mem = &s->slots[i];
165 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
166 *phys_addr = mem->start_addr + (ram - mem->ram);
167 return 1;
171 return 0;
174 static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)
176 struct kvm_userspace_memory_region mem;
178 mem.slot = slot->slot;
179 mem.guest_phys_addr = slot->start_addr;
180 mem.memory_size = slot->memory_size;
181 mem.userspace_addr = (unsigned long)slot->ram;
182 mem.flags = slot->flags;
183 if (s->migration_log) {
184 mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;
186 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
189 static void kvm_reset_vcpu(void *opaque)
191 CPUState *env = opaque;
193 kvm_arch_reset_vcpu(env);
196 int kvm_irqchip_in_kernel(void)
198 return kvm_state->irqchip_in_kernel;
201 int kvm_pit_in_kernel(void)
203 return kvm_state->pit_in_kernel;
206 int kvm_init_vcpu(CPUState *env)
208 KVMState *s = kvm_state;
209 long mmap_size;
210 int ret;
212 DPRINTF("kvm_init_vcpu\n");
214 ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, env->cpu_index);
215 if (ret < 0) {
216 DPRINTF("kvm_create_vcpu failed\n");
217 goto err;
220 env->kvm_fd = ret;
221 env->kvm_state = s;
222 env->kvm_vcpu_dirty = 1;
224 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
225 if (mmap_size < 0) {
226 ret = mmap_size;
227 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
228 goto err;
231 env->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
232 env->kvm_fd, 0);
233 if (env->kvm_run == MAP_FAILED) {
234 ret = -errno;
235 DPRINTF("mmap'ing vcpu state failed\n");
236 goto err;
239 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
240 s->coalesced_mmio_ring =
241 (void *)env->kvm_run + s->coalesced_mmio * PAGE_SIZE;
244 ret = kvm_arch_init_vcpu(env);
245 if (ret == 0) {
246 qemu_register_reset(kvm_reset_vcpu, env);
247 kvm_arch_reset_vcpu(env);
249 err:
250 return ret;
254 * dirty pages logging control
257 static int kvm_mem_flags(KVMState *s, bool log_dirty)
259 return log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
262 static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
264 KVMState *s = kvm_state;
265 int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
266 int old_flags;
268 old_flags = mem->flags;
270 flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty);
271 mem->flags = flags;
273 /* If nothing changed effectively, no need to issue ioctl */
274 if (s->migration_log) {
275 flags |= KVM_MEM_LOG_DIRTY_PAGES;
278 if (flags == old_flags) {
279 return 0;
282 return kvm_set_user_memory_region(s, mem);
285 static int kvm_dirty_pages_log_change(target_phys_addr_t phys_addr,
286 ram_addr_t size, bool log_dirty)
288 KVMState *s = kvm_state;
289 KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
291 if (mem == NULL) {
292 fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
293 TARGET_FMT_plx "\n", __func__, phys_addr,
294 (target_phys_addr_t)(phys_addr + size - 1));
295 return -EINVAL;
297 return kvm_slot_dirty_pages_log_change(mem, log_dirty);
300 static void kvm_log_start(MemoryListener *listener,
301 MemoryRegionSection *section)
303 int r;
305 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
306 section->size, true);
307 if (r < 0) {
308 abort();
312 static void kvm_log_stop(MemoryListener *listener,
313 MemoryRegionSection *section)
315 int r;
317 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
318 section->size, false);
319 if (r < 0) {
320 abort();
324 static int kvm_set_migration_log(int enable)
326 KVMState *s = kvm_state;
327 KVMSlot *mem;
328 int i, err;
330 s->migration_log = enable;
332 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
333 mem = &s->slots[i];
335 if (!mem->memory_size) {
336 continue;
338 if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
339 continue;
341 err = kvm_set_user_memory_region(s, mem);
342 if (err) {
343 return err;
346 return 0;
349 /* get kvm's dirty pages bitmap and update qemu's */
350 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
351 unsigned long *bitmap)
353 unsigned int i, j;
354 unsigned long page_number, c;
355 target_phys_addr_t addr, addr1;
356 unsigned int len = ((section->size / TARGET_PAGE_SIZE) + HOST_LONG_BITS - 1) / HOST_LONG_BITS;
359 * bitmap-traveling is faster than memory-traveling (for addr...)
360 * especially when most of the memory is not dirty.
362 for (i = 0; i < len; i++) {
363 if (bitmap[i] != 0) {
364 c = leul_to_cpu(bitmap[i]);
365 do {
366 j = ffsl(c) - 1;
367 c &= ~(1ul << j);
368 page_number = i * HOST_LONG_BITS + j;
369 addr1 = page_number * TARGET_PAGE_SIZE;
370 addr = section->offset_within_region + addr1;
371 memory_region_set_dirty(section->mr, addr, TARGET_PAGE_SIZE);
372 } while (c != 0);
375 return 0;
378 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
381 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
382 * This function updates qemu's dirty bitmap using
383 * memory_region_set_dirty(). This means all bits are set
384 * to dirty.
386 * @start_add: start of logged region.
387 * @end_addr: end of logged region.
389 static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)
391 KVMState *s = kvm_state;
392 unsigned long size, allocated_size = 0;
393 KVMDirtyLog d;
394 KVMSlot *mem;
395 int ret = 0;
396 target_phys_addr_t start_addr = section->offset_within_address_space;
397 target_phys_addr_t end_addr = start_addr + section->size;
399 d.dirty_bitmap = NULL;
400 while (start_addr < end_addr) {
401 mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
402 if (mem == NULL) {
403 break;
406 /* XXX bad kernel interface alert
407 * For dirty bitmap, kernel allocates array of size aligned to
408 * bits-per-long. But for case when the kernel is 64bits and
409 * the userspace is 32bits, userspace can't align to the same
410 * bits-per-long, since sizeof(long) is different between kernel
411 * and user space. This way, userspace will provide buffer which
412 * may be 4 bytes less than the kernel will use, resulting in
413 * userspace memory corruption (which is not detectable by valgrind
414 * too, in most cases).
415 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
416 * a hope that sizeof(long) wont become >8 any time soon.
418 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
419 /*HOST_LONG_BITS*/ 64) / 8;
420 if (!d.dirty_bitmap) {
421 d.dirty_bitmap = g_malloc(size);
422 } else if (size > allocated_size) {
423 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
425 allocated_size = size;
426 memset(d.dirty_bitmap, 0, allocated_size);
428 d.slot = mem->slot;
430 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
431 DPRINTF("ioctl failed %d\n", errno);
432 ret = -1;
433 break;
436 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
437 start_addr = mem->start_addr + mem->memory_size;
439 g_free(d.dirty_bitmap);
441 return ret;
444 int kvm_coalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
446 int ret = -ENOSYS;
447 KVMState *s = kvm_state;
449 if (s->coalesced_mmio) {
450 struct kvm_coalesced_mmio_zone zone;
452 zone.addr = start;
453 zone.size = size;
455 ret = kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
458 return ret;
461 int kvm_uncoalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
463 int ret = -ENOSYS;
464 KVMState *s = kvm_state;
466 if (s->coalesced_mmio) {
467 struct kvm_coalesced_mmio_zone zone;
469 zone.addr = start;
470 zone.size = size;
472 ret = kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
475 return ret;
478 int kvm_check_extension(KVMState *s, unsigned int extension)
480 int ret;
482 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
483 if (ret < 0) {
484 ret = 0;
487 return ret;
490 static int kvm_check_many_ioeventfds(void)
492 /* Userspace can use ioeventfd for io notification. This requires a host
493 * that supports eventfd(2) and an I/O thread; since eventfd does not
494 * support SIGIO it cannot interrupt the vcpu.
496 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
497 * can avoid creating too many ioeventfds.
499 #if defined(CONFIG_EVENTFD)
500 int ioeventfds[7];
501 int i, ret = 0;
502 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
503 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
504 if (ioeventfds[i] < 0) {
505 break;
507 ret = kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, true);
508 if (ret < 0) {
509 close(ioeventfds[i]);
510 break;
514 /* Decide whether many devices are supported or not */
515 ret = i == ARRAY_SIZE(ioeventfds);
517 while (i-- > 0) {
518 kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, false);
519 close(ioeventfds[i]);
521 return ret;
522 #else
523 return 0;
524 #endif
527 static const KVMCapabilityInfo *
528 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
530 while (list->name) {
531 if (!kvm_check_extension(s, list->value)) {
532 return list;
534 list++;
536 return NULL;
539 static void kvm_set_phys_mem(MemoryRegionSection *section, bool add)
541 KVMState *s = kvm_state;
542 KVMSlot *mem, old;
543 int err;
544 MemoryRegion *mr = section->mr;
545 bool log_dirty = memory_region_is_logging(mr);
546 target_phys_addr_t start_addr = section->offset_within_address_space;
547 ram_addr_t size = section->size;
548 void *ram = NULL;
550 /* kvm works in page size chunks, but the function may be called
551 with sub-page size and unaligned start address. */
552 size = TARGET_PAGE_ALIGN(size);
553 start_addr = TARGET_PAGE_ALIGN(start_addr);
555 if (!memory_region_is_ram(mr)) {
556 return;
559 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region;
561 while (1) {
562 mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
563 if (!mem) {
564 break;
567 if (add && start_addr >= mem->start_addr &&
568 (start_addr + size <= mem->start_addr + mem->memory_size) &&
569 (ram - start_addr == mem->ram - mem->start_addr)) {
570 /* The new slot fits into the existing one and comes with
571 * identical parameters - update flags and done. */
572 kvm_slot_dirty_pages_log_change(mem, log_dirty);
573 return;
576 old = *mem;
578 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
579 kvm_physical_sync_dirty_bitmap(section);
582 /* unregister the overlapping slot */
583 mem->memory_size = 0;
584 err = kvm_set_user_memory_region(s, mem);
585 if (err) {
586 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
587 __func__, strerror(-err));
588 abort();
591 /* Workaround for older KVM versions: we can't join slots, even not by
592 * unregistering the previous ones and then registering the larger
593 * slot. We have to maintain the existing fragmentation. Sigh.
595 * This workaround assumes that the new slot starts at the same
596 * address as the first existing one. If not or if some overlapping
597 * slot comes around later, we will fail (not seen in practice so far)
598 * - and actually require a recent KVM version. */
599 if (s->broken_set_mem_region &&
600 old.start_addr == start_addr && old.memory_size < size && add) {
601 mem = kvm_alloc_slot(s);
602 mem->memory_size = old.memory_size;
603 mem->start_addr = old.start_addr;
604 mem->ram = old.ram;
605 mem->flags = kvm_mem_flags(s, log_dirty);
607 err = kvm_set_user_memory_region(s, mem);
608 if (err) {
609 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
610 strerror(-err));
611 abort();
614 start_addr += old.memory_size;
615 ram += old.memory_size;
616 size -= old.memory_size;
617 continue;
620 /* register prefix slot */
621 if (old.start_addr < start_addr) {
622 mem = kvm_alloc_slot(s);
623 mem->memory_size = start_addr - old.start_addr;
624 mem->start_addr = old.start_addr;
625 mem->ram = old.ram;
626 mem->flags = kvm_mem_flags(s, log_dirty);
628 err = kvm_set_user_memory_region(s, mem);
629 if (err) {
630 fprintf(stderr, "%s: error registering prefix slot: %s\n",
631 __func__, strerror(-err));
632 #ifdef TARGET_PPC
633 fprintf(stderr, "%s: This is probably because your kernel's " \
634 "PAGE_SIZE is too big. Please try to use 4k " \
635 "PAGE_SIZE!\n", __func__);
636 #endif
637 abort();
641 /* register suffix slot */
642 if (old.start_addr + old.memory_size > start_addr + size) {
643 ram_addr_t size_delta;
645 mem = kvm_alloc_slot(s);
646 mem->start_addr = start_addr + size;
647 size_delta = mem->start_addr - old.start_addr;
648 mem->memory_size = old.memory_size - size_delta;
649 mem->ram = old.ram + size_delta;
650 mem->flags = kvm_mem_flags(s, log_dirty);
652 err = kvm_set_user_memory_region(s, mem);
653 if (err) {
654 fprintf(stderr, "%s: error registering suffix slot: %s\n",
655 __func__, strerror(-err));
656 abort();
661 /* in case the KVM bug workaround already "consumed" the new slot */
662 if (!size) {
663 return;
665 if (!add) {
666 return;
668 mem = kvm_alloc_slot(s);
669 mem->memory_size = size;
670 mem->start_addr = start_addr;
671 mem->ram = ram;
672 mem->flags = kvm_mem_flags(s, log_dirty);
674 err = kvm_set_user_memory_region(s, mem);
675 if (err) {
676 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
677 strerror(-err));
678 abort();
682 static void kvm_region_add(MemoryListener *listener,
683 MemoryRegionSection *section)
685 kvm_set_phys_mem(section, true);
688 static void kvm_region_del(MemoryListener *listener,
689 MemoryRegionSection *section)
691 kvm_set_phys_mem(section, false);
694 static void kvm_log_sync(MemoryListener *listener,
695 MemoryRegionSection *section)
697 int r;
699 r = kvm_physical_sync_dirty_bitmap(section);
700 if (r < 0) {
701 abort();
705 static void kvm_log_global_start(struct MemoryListener *listener)
707 int r;
709 r = kvm_set_migration_log(1);
710 assert(r >= 0);
713 static void kvm_log_global_stop(struct MemoryListener *listener)
715 int r;
717 r = kvm_set_migration_log(0);
718 assert(r >= 0);
721 static MemoryListener kvm_memory_listener = {
722 .region_add = kvm_region_add,
723 .region_del = kvm_region_del,
724 .log_start = kvm_log_start,
725 .log_stop = kvm_log_stop,
726 .log_sync = kvm_log_sync,
727 .log_global_start = kvm_log_global_start,
728 .log_global_stop = kvm_log_global_stop,
731 static void kvm_handle_interrupt(CPUState *env, int mask)
733 env->interrupt_request |= mask;
735 if (!qemu_cpu_is_self(env)) {
736 qemu_cpu_kick(env);
740 int kvm_irqchip_set_irq(KVMState *s, int irq, int level)
742 struct kvm_irq_level event;
743 int ret;
745 assert(s->irqchip_in_kernel);
747 event.level = level;
748 event.irq = irq;
749 ret = kvm_vm_ioctl(s, s->irqchip_inject_ioctl, &event);
750 if (ret < 0) {
751 perror("kvm_set_irqchip_line");
752 abort();
755 return (s->irqchip_inject_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
758 #ifdef KVM_CAP_IRQ_ROUTING
759 static void set_gsi(KVMState *s, unsigned int gsi)
761 assert(gsi < s->max_gsi);
763 s->used_gsi_bitmap[gsi / 32] |= 1U << (gsi % 32);
766 static void kvm_init_irq_routing(KVMState *s)
768 int gsi_count;
770 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING);
771 if (gsi_count > 0) {
772 unsigned int gsi_bits, i;
774 /* Round up so we can search ints using ffs */
775 gsi_bits = (gsi_count + 31) / 32;
776 s->used_gsi_bitmap = g_malloc0(gsi_bits / 8);
777 s->max_gsi = gsi_bits;
779 /* Mark any over-allocated bits as already in use */
780 for (i = gsi_count; i < gsi_bits; i++) {
781 set_gsi(s, i);
785 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
786 s->nr_allocated_irq_routes = 0;
788 kvm_arch_init_irq_routing(s);
791 static void kvm_add_routing_entry(KVMState *s,
792 struct kvm_irq_routing_entry *entry)
794 struct kvm_irq_routing_entry *new;
795 int n, size;
797 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
798 n = s->nr_allocated_irq_routes * 2;
799 if (n < 64) {
800 n = 64;
802 size = sizeof(struct kvm_irq_routing);
803 size += n * sizeof(*new);
804 s->irq_routes = g_realloc(s->irq_routes, size);
805 s->nr_allocated_irq_routes = n;
807 n = s->irq_routes->nr++;
808 new = &s->irq_routes->entries[n];
809 memset(new, 0, sizeof(*new));
810 new->gsi = entry->gsi;
811 new->type = entry->type;
812 new->flags = entry->flags;
813 new->u = entry->u;
815 set_gsi(s, entry->gsi);
818 void kvm_irqchip_add_route(KVMState *s, int irq, int irqchip, int pin)
820 struct kvm_irq_routing_entry e;
822 e.gsi = irq;
823 e.type = KVM_IRQ_ROUTING_IRQCHIP;
824 e.flags = 0;
825 e.u.irqchip.irqchip = irqchip;
826 e.u.irqchip.pin = pin;
827 kvm_add_routing_entry(s, &e);
830 int kvm_irqchip_commit_routes(KVMState *s)
832 s->irq_routes->flags = 0;
833 return kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
836 #else /* !KVM_CAP_IRQ_ROUTING */
838 static void kvm_init_irq_routing(KVMState *s)
841 #endif /* !KVM_CAP_IRQ_ROUTING */
843 static int kvm_irqchip_create(KVMState *s)
845 QemuOptsList *list = qemu_find_opts("machine");
846 int ret;
848 if (QTAILQ_EMPTY(&list->head) ||
849 !qemu_opt_get_bool(QTAILQ_FIRST(&list->head),
850 "kernel_irqchip", false) ||
851 !kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
852 return 0;
855 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
856 if (ret < 0) {
857 fprintf(stderr, "Create kernel irqchip failed\n");
858 return ret;
861 s->irqchip_inject_ioctl = KVM_IRQ_LINE;
862 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
863 s->irqchip_inject_ioctl = KVM_IRQ_LINE_STATUS;
865 s->irqchip_in_kernel = 1;
867 kvm_init_irq_routing(s);
869 return 0;
872 int kvm_init(void)
874 static const char upgrade_note[] =
875 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
876 "(see http://sourceforge.net/projects/kvm).\n";
877 KVMState *s;
878 const KVMCapabilityInfo *missing_cap;
879 int ret;
880 int i;
882 s = g_malloc0(sizeof(KVMState));
884 #ifdef KVM_CAP_SET_GUEST_DEBUG
885 QTAILQ_INIT(&s->kvm_sw_breakpoints);
886 #endif
887 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
888 s->slots[i].slot = i;
890 s->vmfd = -1;
891 s->fd = qemu_open("/dev/kvm", O_RDWR);
892 if (s->fd == -1) {
893 fprintf(stderr, "Could not access KVM kernel module: %m\n");
894 ret = -errno;
895 goto err;
898 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
899 if (ret < KVM_API_VERSION) {
900 if (ret > 0) {
901 ret = -EINVAL;
903 fprintf(stderr, "kvm version too old\n");
904 goto err;
907 if (ret > KVM_API_VERSION) {
908 ret = -EINVAL;
909 fprintf(stderr, "kvm version not supported\n");
910 goto err;
913 s->vmfd = kvm_ioctl(s, KVM_CREATE_VM, 0);
914 if (s->vmfd < 0) {
915 #ifdef TARGET_S390X
916 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
917 "your host kernel command line\n");
918 #endif
919 ret = s->vmfd;
920 goto err;
923 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
924 if (!missing_cap) {
925 missing_cap =
926 kvm_check_extension_list(s, kvm_arch_required_capabilities);
928 if (missing_cap) {
929 ret = -EINVAL;
930 fprintf(stderr, "kvm does not support %s\n%s",
931 missing_cap->name, upgrade_note);
932 goto err;
935 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
937 s->broken_set_mem_region = 1;
938 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
939 if (ret > 0) {
940 s->broken_set_mem_region = 0;
943 #ifdef KVM_CAP_VCPU_EVENTS
944 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
945 #endif
947 s->robust_singlestep =
948 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
950 #ifdef KVM_CAP_DEBUGREGS
951 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
952 #endif
954 #ifdef KVM_CAP_XSAVE
955 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
956 #endif
958 #ifdef KVM_CAP_XCRS
959 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
960 #endif
962 ret = kvm_arch_init(s);
963 if (ret < 0) {
964 goto err;
967 ret = kvm_irqchip_create(s);
968 if (ret < 0) {
969 goto err;
972 kvm_state = s;
973 memory_listener_register(&kvm_memory_listener);
975 s->many_ioeventfds = kvm_check_many_ioeventfds();
977 cpu_interrupt_handler = kvm_handle_interrupt;
979 return 0;
981 err:
982 if (s) {
983 if (s->vmfd >= 0) {
984 close(s->vmfd);
986 if (s->fd != -1) {
987 close(s->fd);
990 g_free(s);
992 return ret;
995 static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
996 uint32_t count)
998 int i;
999 uint8_t *ptr = data;
1001 for (i = 0; i < count; i++) {
1002 if (direction == KVM_EXIT_IO_IN) {
1003 switch (size) {
1004 case 1:
1005 stb_p(ptr, cpu_inb(port));
1006 break;
1007 case 2:
1008 stw_p(ptr, cpu_inw(port));
1009 break;
1010 case 4:
1011 stl_p(ptr, cpu_inl(port));
1012 break;
1014 } else {
1015 switch (size) {
1016 case 1:
1017 cpu_outb(port, ldub_p(ptr));
1018 break;
1019 case 2:
1020 cpu_outw(port, lduw_p(ptr));
1021 break;
1022 case 4:
1023 cpu_outl(port, ldl_p(ptr));
1024 break;
1028 ptr += size;
1032 static int kvm_handle_internal_error(CPUState *env, struct kvm_run *run)
1034 fprintf(stderr, "KVM internal error.");
1035 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1036 int i;
1038 fprintf(stderr, " Suberror: %d\n", run->internal.suberror);
1039 for (i = 0; i < run->internal.ndata; ++i) {
1040 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1041 i, (uint64_t)run->internal.data[i]);
1043 } else {
1044 fprintf(stderr, "\n");
1046 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1047 fprintf(stderr, "emulation failure\n");
1048 if (!kvm_arch_stop_on_emulation_error(env)) {
1049 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1050 return EXCP_INTERRUPT;
1053 /* FIXME: Should trigger a qmp message to let management know
1054 * something went wrong.
1056 return -1;
1059 void kvm_flush_coalesced_mmio_buffer(void)
1061 KVMState *s = kvm_state;
1063 if (s->coalesced_flush_in_progress) {
1064 return;
1067 s->coalesced_flush_in_progress = true;
1069 if (s->coalesced_mmio_ring) {
1070 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1071 while (ring->first != ring->last) {
1072 struct kvm_coalesced_mmio *ent;
1074 ent = &ring->coalesced_mmio[ring->first];
1076 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1077 smp_wmb();
1078 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1082 s->coalesced_flush_in_progress = false;
1085 static void do_kvm_cpu_synchronize_state(void *_env)
1087 CPUState *env = _env;
1089 if (!env->kvm_vcpu_dirty) {
1090 kvm_arch_get_registers(env);
1091 env->kvm_vcpu_dirty = 1;
1095 void kvm_cpu_synchronize_state(CPUState *env)
1097 if (!env->kvm_vcpu_dirty) {
1098 run_on_cpu(env, do_kvm_cpu_synchronize_state, env);
1102 void kvm_cpu_synchronize_post_reset(CPUState *env)
1104 kvm_arch_put_registers(env, KVM_PUT_RESET_STATE);
1105 env->kvm_vcpu_dirty = 0;
1108 void kvm_cpu_synchronize_post_init(CPUState *env)
1110 kvm_arch_put_registers(env, KVM_PUT_FULL_STATE);
1111 env->kvm_vcpu_dirty = 0;
1114 int kvm_cpu_exec(CPUState *env)
1116 struct kvm_run *run = env->kvm_run;
1117 int ret, run_ret;
1119 DPRINTF("kvm_cpu_exec()\n");
1121 if (kvm_arch_process_async_events(env)) {
1122 env->exit_request = 0;
1123 return EXCP_HLT;
1126 cpu_single_env = env;
1128 do {
1129 if (env->kvm_vcpu_dirty) {
1130 kvm_arch_put_registers(env, KVM_PUT_RUNTIME_STATE);
1131 env->kvm_vcpu_dirty = 0;
1134 kvm_arch_pre_run(env, run);
1135 if (env->exit_request) {
1136 DPRINTF("interrupt exit requested\n");
1138 * KVM requires us to reenter the kernel after IO exits to complete
1139 * instruction emulation. This self-signal will ensure that we
1140 * leave ASAP again.
1142 qemu_cpu_kick_self();
1144 cpu_single_env = NULL;
1145 qemu_mutex_unlock_iothread();
1147 run_ret = kvm_vcpu_ioctl(env, KVM_RUN, 0);
1149 qemu_mutex_lock_iothread();
1150 cpu_single_env = env;
1151 kvm_arch_post_run(env, run);
1153 kvm_flush_coalesced_mmio_buffer();
1155 if (run_ret < 0) {
1156 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1157 DPRINTF("io window exit\n");
1158 ret = EXCP_INTERRUPT;
1159 break;
1161 fprintf(stderr, "error: kvm run failed %s\n",
1162 strerror(-run_ret));
1163 abort();
1166 switch (run->exit_reason) {
1167 case KVM_EXIT_IO:
1168 DPRINTF("handle_io\n");
1169 kvm_handle_io(run->io.port,
1170 (uint8_t *)run + run->io.data_offset,
1171 run->io.direction,
1172 run->io.size,
1173 run->io.count);
1174 ret = 0;
1175 break;
1176 case KVM_EXIT_MMIO:
1177 DPRINTF("handle_mmio\n");
1178 cpu_physical_memory_rw(run->mmio.phys_addr,
1179 run->mmio.data,
1180 run->mmio.len,
1181 run->mmio.is_write);
1182 ret = 0;
1183 break;
1184 case KVM_EXIT_IRQ_WINDOW_OPEN:
1185 DPRINTF("irq_window_open\n");
1186 ret = EXCP_INTERRUPT;
1187 break;
1188 case KVM_EXIT_SHUTDOWN:
1189 DPRINTF("shutdown\n");
1190 qemu_system_reset_request();
1191 ret = EXCP_INTERRUPT;
1192 break;
1193 case KVM_EXIT_UNKNOWN:
1194 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1195 (uint64_t)run->hw.hardware_exit_reason);
1196 ret = -1;
1197 break;
1198 case KVM_EXIT_INTERNAL_ERROR:
1199 ret = kvm_handle_internal_error(env, run);
1200 break;
1201 default:
1202 DPRINTF("kvm_arch_handle_exit\n");
1203 ret = kvm_arch_handle_exit(env, run);
1204 break;
1206 } while (ret == 0);
1208 if (ret < 0) {
1209 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1210 vm_stop(RUN_STATE_INTERNAL_ERROR);
1213 env->exit_request = 0;
1214 cpu_single_env = NULL;
1215 return ret;
1218 int kvm_ioctl(KVMState *s, int type, ...)
1220 int ret;
1221 void *arg;
1222 va_list ap;
1224 va_start(ap, type);
1225 arg = va_arg(ap, void *);
1226 va_end(ap);
1228 ret = ioctl(s->fd, type, arg);
1229 if (ret == -1) {
1230 ret = -errno;
1232 return ret;
1235 int kvm_vm_ioctl(KVMState *s, int type, ...)
1237 int ret;
1238 void *arg;
1239 va_list ap;
1241 va_start(ap, type);
1242 arg = va_arg(ap, void *);
1243 va_end(ap);
1245 ret = ioctl(s->vmfd, type, arg);
1246 if (ret == -1) {
1247 ret = -errno;
1249 return ret;
1252 int kvm_vcpu_ioctl(CPUState *env, int type, ...)
1254 int ret;
1255 void *arg;
1256 va_list ap;
1258 va_start(ap, type);
1259 arg = va_arg(ap, void *);
1260 va_end(ap);
1262 ret = ioctl(env->kvm_fd, type, arg);
1263 if (ret == -1) {
1264 ret = -errno;
1266 return ret;
1269 int kvm_has_sync_mmu(void)
1271 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1274 int kvm_has_vcpu_events(void)
1276 return kvm_state->vcpu_events;
1279 int kvm_has_robust_singlestep(void)
1281 return kvm_state->robust_singlestep;
1284 int kvm_has_debugregs(void)
1286 return kvm_state->debugregs;
1289 int kvm_has_xsave(void)
1291 return kvm_state->xsave;
1294 int kvm_has_xcrs(void)
1296 return kvm_state->xcrs;
1299 int kvm_has_many_ioeventfds(void)
1301 if (!kvm_enabled()) {
1302 return 0;
1304 return kvm_state->many_ioeventfds;
1307 int kvm_has_gsi_routing(void)
1309 #ifdef KVM_CAP_IRQ_ROUTING
1310 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
1311 #else
1312 return false;
1313 #endif
1316 int kvm_allows_irq0_override(void)
1318 return !kvm_enabled() || !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
1321 void kvm_setup_guest_memory(void *start, size_t size)
1323 if (!kvm_has_sync_mmu()) {
1324 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1326 if (ret) {
1327 perror("qemu_madvise");
1328 fprintf(stderr,
1329 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1330 exit(1);
1335 #ifdef KVM_CAP_SET_GUEST_DEBUG
1336 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *env,
1337 target_ulong pc)
1339 struct kvm_sw_breakpoint *bp;
1341 QTAILQ_FOREACH(bp, &env->kvm_state->kvm_sw_breakpoints, entry) {
1342 if (bp->pc == pc) {
1343 return bp;
1346 return NULL;
1349 int kvm_sw_breakpoints_active(CPUState *env)
1351 return !QTAILQ_EMPTY(&env->kvm_state->kvm_sw_breakpoints);
1354 struct kvm_set_guest_debug_data {
1355 struct kvm_guest_debug dbg;
1356 CPUState *env;
1357 int err;
1360 static void kvm_invoke_set_guest_debug(void *data)
1362 struct kvm_set_guest_debug_data *dbg_data = data;
1363 CPUState *env = dbg_data->env;
1365 dbg_data->err = kvm_vcpu_ioctl(env, KVM_SET_GUEST_DEBUG, &dbg_data->dbg);
1368 int kvm_update_guest_debug(CPUState *env, unsigned long reinject_trap)
1370 struct kvm_set_guest_debug_data data;
1372 data.dbg.control = reinject_trap;
1374 if (env->singlestep_enabled) {
1375 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
1377 kvm_arch_update_guest_debug(env, &data.dbg);
1378 data.env = env;
1380 run_on_cpu(env, kvm_invoke_set_guest_debug, &data);
1381 return data.err;
1384 int kvm_insert_breakpoint(CPUState *current_env, target_ulong addr,
1385 target_ulong len, int type)
1387 struct kvm_sw_breakpoint *bp;
1388 CPUState *env;
1389 int err;
1391 if (type == GDB_BREAKPOINT_SW) {
1392 bp = kvm_find_sw_breakpoint(current_env, addr);
1393 if (bp) {
1394 bp->use_count++;
1395 return 0;
1398 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
1399 if (!bp) {
1400 return -ENOMEM;
1403 bp->pc = addr;
1404 bp->use_count = 1;
1405 err = kvm_arch_insert_sw_breakpoint(current_env, bp);
1406 if (err) {
1407 g_free(bp);
1408 return err;
1411 QTAILQ_INSERT_HEAD(&current_env->kvm_state->kvm_sw_breakpoints,
1412 bp, entry);
1413 } else {
1414 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
1415 if (err) {
1416 return err;
1420 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1421 err = kvm_update_guest_debug(env, 0);
1422 if (err) {
1423 return err;
1426 return 0;
1429 int kvm_remove_breakpoint(CPUState *current_env, target_ulong addr,
1430 target_ulong len, int type)
1432 struct kvm_sw_breakpoint *bp;
1433 CPUState *env;
1434 int err;
1436 if (type == GDB_BREAKPOINT_SW) {
1437 bp = kvm_find_sw_breakpoint(current_env, addr);
1438 if (!bp) {
1439 return -ENOENT;
1442 if (bp->use_count > 1) {
1443 bp->use_count--;
1444 return 0;
1447 err = kvm_arch_remove_sw_breakpoint(current_env, bp);
1448 if (err) {
1449 return err;
1452 QTAILQ_REMOVE(&current_env->kvm_state->kvm_sw_breakpoints, bp, entry);
1453 g_free(bp);
1454 } else {
1455 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
1456 if (err) {
1457 return err;
1461 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1462 err = kvm_update_guest_debug(env, 0);
1463 if (err) {
1464 return err;
1467 return 0;
1470 void kvm_remove_all_breakpoints(CPUState *current_env)
1472 struct kvm_sw_breakpoint *bp, *next;
1473 KVMState *s = current_env->kvm_state;
1474 CPUState *env;
1476 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
1477 if (kvm_arch_remove_sw_breakpoint(current_env, bp) != 0) {
1478 /* Try harder to find a CPU that currently sees the breakpoint. */
1479 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1480 if (kvm_arch_remove_sw_breakpoint(env, bp) == 0) {
1481 break;
1486 kvm_arch_remove_all_hw_breakpoints();
1488 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1489 kvm_update_guest_debug(env, 0);
1493 #else /* !KVM_CAP_SET_GUEST_DEBUG */
1495 int kvm_update_guest_debug(CPUState *env, unsigned long reinject_trap)
1497 return -EINVAL;
1500 int kvm_insert_breakpoint(CPUState *current_env, target_ulong addr,
1501 target_ulong len, int type)
1503 return -EINVAL;
1506 int kvm_remove_breakpoint(CPUState *current_env, target_ulong addr,
1507 target_ulong len, int type)
1509 return -EINVAL;
1512 void kvm_remove_all_breakpoints(CPUState *current_env)
1515 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
1517 int kvm_set_signal_mask(CPUState *env, const sigset_t *sigset)
1519 struct kvm_signal_mask *sigmask;
1520 int r;
1522 if (!sigset) {
1523 return kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, NULL);
1526 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
1528 sigmask->len = 8;
1529 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
1530 r = kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, sigmask);
1531 g_free(sigmask);
1533 return r;
1536 int kvm_set_ioeventfd_mmio_long(int fd, uint32_t addr, uint32_t val, bool assign)
1538 int ret;
1539 struct kvm_ioeventfd iofd;
1541 iofd.datamatch = val;
1542 iofd.addr = addr;
1543 iofd.len = 4;
1544 iofd.flags = KVM_IOEVENTFD_FLAG_DATAMATCH;
1545 iofd.fd = fd;
1547 if (!kvm_enabled()) {
1548 return -ENOSYS;
1551 if (!assign) {
1552 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1555 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
1557 if (ret < 0) {
1558 return -errno;
1561 return 0;
1564 int kvm_set_ioeventfd_pio_word(int fd, uint16_t addr, uint16_t val, bool assign)
1566 struct kvm_ioeventfd kick = {
1567 .datamatch = val,
1568 .addr = addr,
1569 .len = 2,
1570 .flags = KVM_IOEVENTFD_FLAG_DATAMATCH | KVM_IOEVENTFD_FLAG_PIO,
1571 .fd = fd,
1573 int r;
1574 if (!kvm_enabled()) {
1575 return -ENOSYS;
1577 if (!assign) {
1578 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1580 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
1581 if (r < 0) {
1582 return r;
1584 return 0;
1587 int kvm_on_sigbus_vcpu(CPUState *env, int code, void *addr)
1589 return kvm_arch_on_sigbus_vcpu(env, code, addr);
1592 int kvm_on_sigbus(int code, void *addr)
1594 return kvm_arch_on_sigbus(code, addr);