Add SPICE support to add_client monitor command
[qemu/ar7.git] / kvm-all.c
blobc4babdac0dd3335eab1a9e45371b7df2c0dd1c9c
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 pit_in_kernel;
78 int xsave, xcrs;
79 int many_ioeventfds;
80 int irqchip_inject_ioctl;
81 #ifdef KVM_CAP_IRQ_ROUTING
82 struct kvm_irq_routing *irq_routes;
83 int nr_allocated_irq_routes;
84 uint32_t *used_gsi_bitmap;
85 unsigned int max_gsi;
86 #endif
89 KVMState *kvm_state;
90 bool kvm_kernel_irqchip;
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_pit_in_kernel(void)
198 return kvm_state->pit_in_kernel;
201 int kvm_init_vcpu(CPUState *env)
203 KVMState *s = kvm_state;
204 long mmap_size;
205 int ret;
207 DPRINTF("kvm_init_vcpu\n");
209 ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, env->cpu_index);
210 if (ret < 0) {
211 DPRINTF("kvm_create_vcpu failed\n");
212 goto err;
215 env->kvm_fd = ret;
216 env->kvm_state = s;
217 env->kvm_vcpu_dirty = 1;
219 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
220 if (mmap_size < 0) {
221 ret = mmap_size;
222 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
223 goto err;
226 env->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
227 env->kvm_fd, 0);
228 if (env->kvm_run == MAP_FAILED) {
229 ret = -errno;
230 DPRINTF("mmap'ing vcpu state failed\n");
231 goto err;
234 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
235 s->coalesced_mmio_ring =
236 (void *)env->kvm_run + s->coalesced_mmio * PAGE_SIZE;
239 ret = kvm_arch_init_vcpu(env);
240 if (ret == 0) {
241 qemu_register_reset(kvm_reset_vcpu, env);
242 kvm_arch_reset_vcpu(env);
244 err:
245 return ret;
249 * dirty pages logging control
252 static int kvm_mem_flags(KVMState *s, bool log_dirty)
254 return log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
257 static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
259 KVMState *s = kvm_state;
260 int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
261 int old_flags;
263 old_flags = mem->flags;
265 flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty);
266 mem->flags = flags;
268 /* If nothing changed effectively, no need to issue ioctl */
269 if (s->migration_log) {
270 flags |= KVM_MEM_LOG_DIRTY_PAGES;
273 if (flags == old_flags) {
274 return 0;
277 return kvm_set_user_memory_region(s, mem);
280 static int kvm_dirty_pages_log_change(target_phys_addr_t phys_addr,
281 ram_addr_t size, bool log_dirty)
283 KVMState *s = kvm_state;
284 KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
286 if (mem == NULL) {
287 fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
288 TARGET_FMT_plx "\n", __func__, phys_addr,
289 (target_phys_addr_t)(phys_addr + size - 1));
290 return -EINVAL;
292 return kvm_slot_dirty_pages_log_change(mem, log_dirty);
295 static void kvm_log_start(MemoryListener *listener,
296 MemoryRegionSection *section)
298 int r;
300 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
301 section->size, true);
302 if (r < 0) {
303 abort();
307 static void kvm_log_stop(MemoryListener *listener,
308 MemoryRegionSection *section)
310 int r;
312 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
313 section->size, false);
314 if (r < 0) {
315 abort();
319 static int kvm_set_migration_log(int enable)
321 KVMState *s = kvm_state;
322 KVMSlot *mem;
323 int i, err;
325 s->migration_log = enable;
327 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
328 mem = &s->slots[i];
330 if (!mem->memory_size) {
331 continue;
333 if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
334 continue;
336 err = kvm_set_user_memory_region(s, mem);
337 if (err) {
338 return err;
341 return 0;
344 /* get kvm's dirty pages bitmap and update qemu's */
345 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
346 unsigned long *bitmap)
348 unsigned int i, j;
349 unsigned long page_number, c;
350 target_phys_addr_t addr, addr1;
351 unsigned int len = ((section->size / TARGET_PAGE_SIZE) + HOST_LONG_BITS - 1) / HOST_LONG_BITS;
354 * bitmap-traveling is faster than memory-traveling (for addr...)
355 * especially when most of the memory is not dirty.
357 for (i = 0; i < len; i++) {
358 if (bitmap[i] != 0) {
359 c = leul_to_cpu(bitmap[i]);
360 do {
361 j = ffsl(c) - 1;
362 c &= ~(1ul << j);
363 page_number = i * HOST_LONG_BITS + j;
364 addr1 = page_number * TARGET_PAGE_SIZE;
365 addr = section->offset_within_region + addr1;
366 memory_region_set_dirty(section->mr, addr, TARGET_PAGE_SIZE);
367 } while (c != 0);
370 return 0;
373 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
376 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
377 * This function updates qemu's dirty bitmap using
378 * memory_region_set_dirty(). This means all bits are set
379 * to dirty.
381 * @start_add: start of logged region.
382 * @end_addr: end of logged region.
384 static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)
386 KVMState *s = kvm_state;
387 unsigned long size, allocated_size = 0;
388 KVMDirtyLog d;
389 KVMSlot *mem;
390 int ret = 0;
391 target_phys_addr_t start_addr = section->offset_within_address_space;
392 target_phys_addr_t end_addr = start_addr + section->size;
394 d.dirty_bitmap = NULL;
395 while (start_addr < end_addr) {
396 mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
397 if (mem == NULL) {
398 break;
401 /* XXX bad kernel interface alert
402 * For dirty bitmap, kernel allocates array of size aligned to
403 * bits-per-long. But for case when the kernel is 64bits and
404 * the userspace is 32bits, userspace can't align to the same
405 * bits-per-long, since sizeof(long) is different between kernel
406 * and user space. This way, userspace will provide buffer which
407 * may be 4 bytes less than the kernel will use, resulting in
408 * userspace memory corruption (which is not detectable by valgrind
409 * too, in most cases).
410 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
411 * a hope that sizeof(long) wont become >8 any time soon.
413 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
414 /*HOST_LONG_BITS*/ 64) / 8;
415 if (!d.dirty_bitmap) {
416 d.dirty_bitmap = g_malloc(size);
417 } else if (size > allocated_size) {
418 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
420 allocated_size = size;
421 memset(d.dirty_bitmap, 0, allocated_size);
423 d.slot = mem->slot;
425 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
426 DPRINTF("ioctl failed %d\n", errno);
427 ret = -1;
428 break;
431 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
432 start_addr = mem->start_addr + mem->memory_size;
434 g_free(d.dirty_bitmap);
436 return ret;
439 int kvm_coalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
441 int ret = -ENOSYS;
442 KVMState *s = kvm_state;
444 if (s->coalesced_mmio) {
445 struct kvm_coalesced_mmio_zone zone;
447 zone.addr = start;
448 zone.size = size;
450 ret = kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
453 return ret;
456 int kvm_uncoalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
458 int ret = -ENOSYS;
459 KVMState *s = kvm_state;
461 if (s->coalesced_mmio) {
462 struct kvm_coalesced_mmio_zone zone;
464 zone.addr = start;
465 zone.size = size;
467 ret = kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
470 return ret;
473 int kvm_check_extension(KVMState *s, unsigned int extension)
475 int ret;
477 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
478 if (ret < 0) {
479 ret = 0;
482 return ret;
485 static int kvm_check_many_ioeventfds(void)
487 /* Userspace can use ioeventfd for io notification. This requires a host
488 * that supports eventfd(2) and an I/O thread; since eventfd does not
489 * support SIGIO it cannot interrupt the vcpu.
491 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
492 * can avoid creating too many ioeventfds.
494 #if defined(CONFIG_EVENTFD)
495 int ioeventfds[7];
496 int i, ret = 0;
497 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
498 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
499 if (ioeventfds[i] < 0) {
500 break;
502 ret = kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, true);
503 if (ret < 0) {
504 close(ioeventfds[i]);
505 break;
509 /* Decide whether many devices are supported or not */
510 ret = i == ARRAY_SIZE(ioeventfds);
512 while (i-- > 0) {
513 kvm_set_ioeventfd_pio_word(ioeventfds[i], 0, i, false);
514 close(ioeventfds[i]);
516 return ret;
517 #else
518 return 0;
519 #endif
522 static const KVMCapabilityInfo *
523 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
525 while (list->name) {
526 if (!kvm_check_extension(s, list->value)) {
527 return list;
529 list++;
531 return NULL;
534 static void kvm_set_phys_mem(MemoryRegionSection *section, bool add)
536 KVMState *s = kvm_state;
537 KVMSlot *mem, old;
538 int err;
539 MemoryRegion *mr = section->mr;
540 bool log_dirty = memory_region_is_logging(mr);
541 target_phys_addr_t start_addr = section->offset_within_address_space;
542 ram_addr_t size = section->size;
543 void *ram = NULL;
545 /* kvm works in page size chunks, but the function may be called
546 with sub-page size and unaligned start address. */
547 size = TARGET_PAGE_ALIGN(size);
548 start_addr = TARGET_PAGE_ALIGN(start_addr);
550 if (!memory_region_is_ram(mr)) {
551 return;
554 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region;
556 while (1) {
557 mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
558 if (!mem) {
559 break;
562 if (add && start_addr >= mem->start_addr &&
563 (start_addr + size <= mem->start_addr + mem->memory_size) &&
564 (ram - start_addr == mem->ram - mem->start_addr)) {
565 /* The new slot fits into the existing one and comes with
566 * identical parameters - update flags and done. */
567 kvm_slot_dirty_pages_log_change(mem, log_dirty);
568 return;
571 old = *mem;
573 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
574 kvm_physical_sync_dirty_bitmap(section);
577 /* unregister the overlapping slot */
578 mem->memory_size = 0;
579 err = kvm_set_user_memory_region(s, mem);
580 if (err) {
581 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
582 __func__, strerror(-err));
583 abort();
586 /* Workaround for older KVM versions: we can't join slots, even not by
587 * unregistering the previous ones and then registering the larger
588 * slot. We have to maintain the existing fragmentation. Sigh.
590 * This workaround assumes that the new slot starts at the same
591 * address as the first existing one. If not or if some overlapping
592 * slot comes around later, we will fail (not seen in practice so far)
593 * - and actually require a recent KVM version. */
594 if (s->broken_set_mem_region &&
595 old.start_addr == start_addr && old.memory_size < size && add) {
596 mem = kvm_alloc_slot(s);
597 mem->memory_size = old.memory_size;
598 mem->start_addr = old.start_addr;
599 mem->ram = old.ram;
600 mem->flags = kvm_mem_flags(s, log_dirty);
602 err = kvm_set_user_memory_region(s, mem);
603 if (err) {
604 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
605 strerror(-err));
606 abort();
609 start_addr += old.memory_size;
610 ram += old.memory_size;
611 size -= old.memory_size;
612 continue;
615 /* register prefix slot */
616 if (old.start_addr < start_addr) {
617 mem = kvm_alloc_slot(s);
618 mem->memory_size = start_addr - old.start_addr;
619 mem->start_addr = old.start_addr;
620 mem->ram = old.ram;
621 mem->flags = kvm_mem_flags(s, log_dirty);
623 err = kvm_set_user_memory_region(s, mem);
624 if (err) {
625 fprintf(stderr, "%s: error registering prefix slot: %s\n",
626 __func__, strerror(-err));
627 #ifdef TARGET_PPC
628 fprintf(stderr, "%s: This is probably because your kernel's " \
629 "PAGE_SIZE is too big. Please try to use 4k " \
630 "PAGE_SIZE!\n", __func__);
631 #endif
632 abort();
636 /* register suffix slot */
637 if (old.start_addr + old.memory_size > start_addr + size) {
638 ram_addr_t size_delta;
640 mem = kvm_alloc_slot(s);
641 mem->start_addr = start_addr + size;
642 size_delta = mem->start_addr - old.start_addr;
643 mem->memory_size = old.memory_size - size_delta;
644 mem->ram = old.ram + size_delta;
645 mem->flags = kvm_mem_flags(s, log_dirty);
647 err = kvm_set_user_memory_region(s, mem);
648 if (err) {
649 fprintf(stderr, "%s: error registering suffix slot: %s\n",
650 __func__, strerror(-err));
651 abort();
656 /* in case the KVM bug workaround already "consumed" the new slot */
657 if (!size) {
658 return;
660 if (!add) {
661 return;
663 mem = kvm_alloc_slot(s);
664 mem->memory_size = size;
665 mem->start_addr = start_addr;
666 mem->ram = ram;
667 mem->flags = kvm_mem_flags(s, log_dirty);
669 err = kvm_set_user_memory_region(s, mem);
670 if (err) {
671 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
672 strerror(-err));
673 abort();
677 static void kvm_region_add(MemoryListener *listener,
678 MemoryRegionSection *section)
680 kvm_set_phys_mem(section, true);
683 static void kvm_region_del(MemoryListener *listener,
684 MemoryRegionSection *section)
686 kvm_set_phys_mem(section, false);
689 static void kvm_log_sync(MemoryListener *listener,
690 MemoryRegionSection *section)
692 int r;
694 r = kvm_physical_sync_dirty_bitmap(section);
695 if (r < 0) {
696 abort();
700 static void kvm_log_global_start(struct MemoryListener *listener)
702 int r;
704 r = kvm_set_migration_log(1);
705 assert(r >= 0);
708 static void kvm_log_global_stop(struct MemoryListener *listener)
710 int r;
712 r = kvm_set_migration_log(0);
713 assert(r >= 0);
716 static MemoryListener kvm_memory_listener = {
717 .region_add = kvm_region_add,
718 .region_del = kvm_region_del,
719 .log_start = kvm_log_start,
720 .log_stop = kvm_log_stop,
721 .log_sync = kvm_log_sync,
722 .log_global_start = kvm_log_global_start,
723 .log_global_stop = kvm_log_global_stop,
726 static void kvm_handle_interrupt(CPUState *env, int mask)
728 env->interrupt_request |= mask;
730 if (!qemu_cpu_is_self(env)) {
731 qemu_cpu_kick(env);
735 int kvm_irqchip_set_irq(KVMState *s, int irq, int level)
737 struct kvm_irq_level event;
738 int ret;
740 assert(kvm_irqchip_in_kernel());
742 event.level = level;
743 event.irq = irq;
744 ret = kvm_vm_ioctl(s, s->irqchip_inject_ioctl, &event);
745 if (ret < 0) {
746 perror("kvm_set_irqchip_line");
747 abort();
750 return (s->irqchip_inject_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
753 #ifdef KVM_CAP_IRQ_ROUTING
754 static void set_gsi(KVMState *s, unsigned int gsi)
756 assert(gsi < s->max_gsi);
758 s->used_gsi_bitmap[gsi / 32] |= 1U << (gsi % 32);
761 static void kvm_init_irq_routing(KVMState *s)
763 int gsi_count;
765 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING);
766 if (gsi_count > 0) {
767 unsigned int gsi_bits, i;
769 /* Round up so we can search ints using ffs */
770 gsi_bits = (gsi_count + 31) / 32;
771 s->used_gsi_bitmap = g_malloc0(gsi_bits / 8);
772 s->max_gsi = gsi_bits;
774 /* Mark any over-allocated bits as already in use */
775 for (i = gsi_count; i < gsi_bits; i++) {
776 set_gsi(s, i);
780 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
781 s->nr_allocated_irq_routes = 0;
783 kvm_arch_init_irq_routing(s);
786 static void kvm_add_routing_entry(KVMState *s,
787 struct kvm_irq_routing_entry *entry)
789 struct kvm_irq_routing_entry *new;
790 int n, size;
792 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
793 n = s->nr_allocated_irq_routes * 2;
794 if (n < 64) {
795 n = 64;
797 size = sizeof(struct kvm_irq_routing);
798 size += n * sizeof(*new);
799 s->irq_routes = g_realloc(s->irq_routes, size);
800 s->nr_allocated_irq_routes = n;
802 n = s->irq_routes->nr++;
803 new = &s->irq_routes->entries[n];
804 memset(new, 0, sizeof(*new));
805 new->gsi = entry->gsi;
806 new->type = entry->type;
807 new->flags = entry->flags;
808 new->u = entry->u;
810 set_gsi(s, entry->gsi);
813 void kvm_irqchip_add_route(KVMState *s, int irq, int irqchip, int pin)
815 struct kvm_irq_routing_entry e;
817 e.gsi = irq;
818 e.type = KVM_IRQ_ROUTING_IRQCHIP;
819 e.flags = 0;
820 e.u.irqchip.irqchip = irqchip;
821 e.u.irqchip.pin = pin;
822 kvm_add_routing_entry(s, &e);
825 int kvm_irqchip_commit_routes(KVMState *s)
827 s->irq_routes->flags = 0;
828 return kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
831 #else /* !KVM_CAP_IRQ_ROUTING */
833 static void kvm_init_irq_routing(KVMState *s)
836 #endif /* !KVM_CAP_IRQ_ROUTING */
838 static int kvm_irqchip_create(KVMState *s)
840 QemuOptsList *list = qemu_find_opts("machine");
841 int ret;
843 if (QTAILQ_EMPTY(&list->head) ||
844 !qemu_opt_get_bool(QTAILQ_FIRST(&list->head),
845 "kernel_irqchip", false) ||
846 !kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
847 return 0;
850 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
851 if (ret < 0) {
852 fprintf(stderr, "Create kernel irqchip failed\n");
853 return ret;
856 s->irqchip_inject_ioctl = KVM_IRQ_LINE;
857 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
858 s->irqchip_inject_ioctl = KVM_IRQ_LINE_STATUS;
860 kvm_kernel_irqchip = true;
862 kvm_init_irq_routing(s);
864 return 0;
867 int kvm_init(void)
869 static const char upgrade_note[] =
870 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
871 "(see http://sourceforge.net/projects/kvm).\n";
872 KVMState *s;
873 const KVMCapabilityInfo *missing_cap;
874 int ret;
875 int i;
877 s = g_malloc0(sizeof(KVMState));
879 #ifdef KVM_CAP_SET_GUEST_DEBUG
880 QTAILQ_INIT(&s->kvm_sw_breakpoints);
881 #endif
882 for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
883 s->slots[i].slot = i;
885 s->vmfd = -1;
886 s->fd = qemu_open("/dev/kvm", O_RDWR);
887 if (s->fd == -1) {
888 fprintf(stderr, "Could not access KVM kernel module: %m\n");
889 ret = -errno;
890 goto err;
893 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
894 if (ret < KVM_API_VERSION) {
895 if (ret > 0) {
896 ret = -EINVAL;
898 fprintf(stderr, "kvm version too old\n");
899 goto err;
902 if (ret > KVM_API_VERSION) {
903 ret = -EINVAL;
904 fprintf(stderr, "kvm version not supported\n");
905 goto err;
908 s->vmfd = kvm_ioctl(s, KVM_CREATE_VM, 0);
909 if (s->vmfd < 0) {
910 #ifdef TARGET_S390X
911 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
912 "your host kernel command line\n");
913 #endif
914 ret = s->vmfd;
915 goto err;
918 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
919 if (!missing_cap) {
920 missing_cap =
921 kvm_check_extension_list(s, kvm_arch_required_capabilities);
923 if (missing_cap) {
924 ret = -EINVAL;
925 fprintf(stderr, "kvm does not support %s\n%s",
926 missing_cap->name, upgrade_note);
927 goto err;
930 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
932 s->broken_set_mem_region = 1;
933 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
934 if (ret > 0) {
935 s->broken_set_mem_region = 0;
938 #ifdef KVM_CAP_VCPU_EVENTS
939 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
940 #endif
942 s->robust_singlestep =
943 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
945 #ifdef KVM_CAP_DEBUGREGS
946 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
947 #endif
949 #ifdef KVM_CAP_XSAVE
950 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
951 #endif
953 #ifdef KVM_CAP_XCRS
954 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
955 #endif
957 ret = kvm_arch_init(s);
958 if (ret < 0) {
959 goto err;
962 ret = kvm_irqchip_create(s);
963 if (ret < 0) {
964 goto err;
967 kvm_state = s;
968 memory_listener_register(&kvm_memory_listener);
970 s->many_ioeventfds = kvm_check_many_ioeventfds();
972 cpu_interrupt_handler = kvm_handle_interrupt;
974 return 0;
976 err:
977 if (s) {
978 if (s->vmfd >= 0) {
979 close(s->vmfd);
981 if (s->fd != -1) {
982 close(s->fd);
985 g_free(s);
987 return ret;
990 static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
991 uint32_t count)
993 int i;
994 uint8_t *ptr = data;
996 for (i = 0; i < count; i++) {
997 if (direction == KVM_EXIT_IO_IN) {
998 switch (size) {
999 case 1:
1000 stb_p(ptr, cpu_inb(port));
1001 break;
1002 case 2:
1003 stw_p(ptr, cpu_inw(port));
1004 break;
1005 case 4:
1006 stl_p(ptr, cpu_inl(port));
1007 break;
1009 } else {
1010 switch (size) {
1011 case 1:
1012 cpu_outb(port, ldub_p(ptr));
1013 break;
1014 case 2:
1015 cpu_outw(port, lduw_p(ptr));
1016 break;
1017 case 4:
1018 cpu_outl(port, ldl_p(ptr));
1019 break;
1023 ptr += size;
1027 static int kvm_handle_internal_error(CPUState *env, struct kvm_run *run)
1029 fprintf(stderr, "KVM internal error.");
1030 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1031 int i;
1033 fprintf(stderr, " Suberror: %d\n", run->internal.suberror);
1034 for (i = 0; i < run->internal.ndata; ++i) {
1035 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1036 i, (uint64_t)run->internal.data[i]);
1038 } else {
1039 fprintf(stderr, "\n");
1041 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1042 fprintf(stderr, "emulation failure\n");
1043 if (!kvm_arch_stop_on_emulation_error(env)) {
1044 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1045 return EXCP_INTERRUPT;
1048 /* FIXME: Should trigger a qmp message to let management know
1049 * something went wrong.
1051 return -1;
1054 void kvm_flush_coalesced_mmio_buffer(void)
1056 KVMState *s = kvm_state;
1058 if (s->coalesced_flush_in_progress) {
1059 return;
1062 s->coalesced_flush_in_progress = true;
1064 if (s->coalesced_mmio_ring) {
1065 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1066 while (ring->first != ring->last) {
1067 struct kvm_coalesced_mmio *ent;
1069 ent = &ring->coalesced_mmio[ring->first];
1071 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1072 smp_wmb();
1073 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1077 s->coalesced_flush_in_progress = false;
1080 static void do_kvm_cpu_synchronize_state(void *_env)
1082 CPUState *env = _env;
1084 if (!env->kvm_vcpu_dirty) {
1085 kvm_arch_get_registers(env);
1086 env->kvm_vcpu_dirty = 1;
1090 void kvm_cpu_synchronize_state(CPUState *env)
1092 if (!env->kvm_vcpu_dirty) {
1093 run_on_cpu(env, do_kvm_cpu_synchronize_state, env);
1097 void kvm_cpu_synchronize_post_reset(CPUState *env)
1099 kvm_arch_put_registers(env, KVM_PUT_RESET_STATE);
1100 env->kvm_vcpu_dirty = 0;
1103 void kvm_cpu_synchronize_post_init(CPUState *env)
1105 kvm_arch_put_registers(env, KVM_PUT_FULL_STATE);
1106 env->kvm_vcpu_dirty = 0;
1109 int kvm_cpu_exec(CPUState *env)
1111 struct kvm_run *run = env->kvm_run;
1112 int ret, run_ret;
1114 DPRINTF("kvm_cpu_exec()\n");
1116 if (kvm_arch_process_async_events(env)) {
1117 env->exit_request = 0;
1118 return EXCP_HLT;
1121 cpu_single_env = env;
1123 do {
1124 if (env->kvm_vcpu_dirty) {
1125 kvm_arch_put_registers(env, KVM_PUT_RUNTIME_STATE);
1126 env->kvm_vcpu_dirty = 0;
1129 kvm_arch_pre_run(env, run);
1130 if (env->exit_request) {
1131 DPRINTF("interrupt exit requested\n");
1133 * KVM requires us to reenter the kernel after IO exits to complete
1134 * instruction emulation. This self-signal will ensure that we
1135 * leave ASAP again.
1137 qemu_cpu_kick_self();
1139 cpu_single_env = NULL;
1140 qemu_mutex_unlock_iothread();
1142 run_ret = kvm_vcpu_ioctl(env, KVM_RUN, 0);
1144 qemu_mutex_lock_iothread();
1145 cpu_single_env = env;
1146 kvm_arch_post_run(env, run);
1148 kvm_flush_coalesced_mmio_buffer();
1150 if (run_ret < 0) {
1151 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1152 DPRINTF("io window exit\n");
1153 ret = EXCP_INTERRUPT;
1154 break;
1156 fprintf(stderr, "error: kvm run failed %s\n",
1157 strerror(-run_ret));
1158 abort();
1161 switch (run->exit_reason) {
1162 case KVM_EXIT_IO:
1163 DPRINTF("handle_io\n");
1164 kvm_handle_io(run->io.port,
1165 (uint8_t *)run + run->io.data_offset,
1166 run->io.direction,
1167 run->io.size,
1168 run->io.count);
1169 ret = 0;
1170 break;
1171 case KVM_EXIT_MMIO:
1172 DPRINTF("handle_mmio\n");
1173 cpu_physical_memory_rw(run->mmio.phys_addr,
1174 run->mmio.data,
1175 run->mmio.len,
1176 run->mmio.is_write);
1177 ret = 0;
1178 break;
1179 case KVM_EXIT_IRQ_WINDOW_OPEN:
1180 DPRINTF("irq_window_open\n");
1181 ret = EXCP_INTERRUPT;
1182 break;
1183 case KVM_EXIT_SHUTDOWN:
1184 DPRINTF("shutdown\n");
1185 qemu_system_reset_request();
1186 ret = EXCP_INTERRUPT;
1187 break;
1188 case KVM_EXIT_UNKNOWN:
1189 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1190 (uint64_t)run->hw.hardware_exit_reason);
1191 ret = -1;
1192 break;
1193 case KVM_EXIT_INTERNAL_ERROR:
1194 ret = kvm_handle_internal_error(env, run);
1195 break;
1196 default:
1197 DPRINTF("kvm_arch_handle_exit\n");
1198 ret = kvm_arch_handle_exit(env, run);
1199 break;
1201 } while (ret == 0);
1203 if (ret < 0) {
1204 cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);
1205 vm_stop(RUN_STATE_INTERNAL_ERROR);
1208 env->exit_request = 0;
1209 cpu_single_env = NULL;
1210 return ret;
1213 int kvm_ioctl(KVMState *s, int type, ...)
1215 int ret;
1216 void *arg;
1217 va_list ap;
1219 va_start(ap, type);
1220 arg = va_arg(ap, void *);
1221 va_end(ap);
1223 ret = ioctl(s->fd, type, arg);
1224 if (ret == -1) {
1225 ret = -errno;
1227 return ret;
1230 int kvm_vm_ioctl(KVMState *s, int type, ...)
1232 int ret;
1233 void *arg;
1234 va_list ap;
1236 va_start(ap, type);
1237 arg = va_arg(ap, void *);
1238 va_end(ap);
1240 ret = ioctl(s->vmfd, type, arg);
1241 if (ret == -1) {
1242 ret = -errno;
1244 return ret;
1247 int kvm_vcpu_ioctl(CPUState *env, int type, ...)
1249 int ret;
1250 void *arg;
1251 va_list ap;
1253 va_start(ap, type);
1254 arg = va_arg(ap, void *);
1255 va_end(ap);
1257 ret = ioctl(env->kvm_fd, type, arg);
1258 if (ret == -1) {
1259 ret = -errno;
1261 return ret;
1264 int kvm_has_sync_mmu(void)
1266 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1269 int kvm_has_vcpu_events(void)
1271 return kvm_state->vcpu_events;
1274 int kvm_has_robust_singlestep(void)
1276 return kvm_state->robust_singlestep;
1279 int kvm_has_debugregs(void)
1281 return kvm_state->debugregs;
1284 int kvm_has_xsave(void)
1286 return kvm_state->xsave;
1289 int kvm_has_xcrs(void)
1291 return kvm_state->xcrs;
1294 int kvm_has_many_ioeventfds(void)
1296 if (!kvm_enabled()) {
1297 return 0;
1299 return kvm_state->many_ioeventfds;
1302 int kvm_has_gsi_routing(void)
1304 #ifdef KVM_CAP_IRQ_ROUTING
1305 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
1306 #else
1307 return false;
1308 #endif
1311 int kvm_allows_irq0_override(void)
1313 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
1316 void kvm_setup_guest_memory(void *start, size_t size)
1318 if (!kvm_has_sync_mmu()) {
1319 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1321 if (ret) {
1322 perror("qemu_madvise");
1323 fprintf(stderr,
1324 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1325 exit(1);
1330 #ifdef KVM_CAP_SET_GUEST_DEBUG
1331 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *env,
1332 target_ulong pc)
1334 struct kvm_sw_breakpoint *bp;
1336 QTAILQ_FOREACH(bp, &env->kvm_state->kvm_sw_breakpoints, entry) {
1337 if (bp->pc == pc) {
1338 return bp;
1341 return NULL;
1344 int kvm_sw_breakpoints_active(CPUState *env)
1346 return !QTAILQ_EMPTY(&env->kvm_state->kvm_sw_breakpoints);
1349 struct kvm_set_guest_debug_data {
1350 struct kvm_guest_debug dbg;
1351 CPUState *env;
1352 int err;
1355 static void kvm_invoke_set_guest_debug(void *data)
1357 struct kvm_set_guest_debug_data *dbg_data = data;
1358 CPUState *env = dbg_data->env;
1360 dbg_data->err = kvm_vcpu_ioctl(env, KVM_SET_GUEST_DEBUG, &dbg_data->dbg);
1363 int kvm_update_guest_debug(CPUState *env, unsigned long reinject_trap)
1365 struct kvm_set_guest_debug_data data;
1367 data.dbg.control = reinject_trap;
1369 if (env->singlestep_enabled) {
1370 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
1372 kvm_arch_update_guest_debug(env, &data.dbg);
1373 data.env = env;
1375 run_on_cpu(env, kvm_invoke_set_guest_debug, &data);
1376 return data.err;
1379 int kvm_insert_breakpoint(CPUState *current_env, target_ulong addr,
1380 target_ulong len, int type)
1382 struct kvm_sw_breakpoint *bp;
1383 CPUState *env;
1384 int err;
1386 if (type == GDB_BREAKPOINT_SW) {
1387 bp = kvm_find_sw_breakpoint(current_env, addr);
1388 if (bp) {
1389 bp->use_count++;
1390 return 0;
1393 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
1394 if (!bp) {
1395 return -ENOMEM;
1398 bp->pc = addr;
1399 bp->use_count = 1;
1400 err = kvm_arch_insert_sw_breakpoint(current_env, bp);
1401 if (err) {
1402 g_free(bp);
1403 return err;
1406 QTAILQ_INSERT_HEAD(&current_env->kvm_state->kvm_sw_breakpoints,
1407 bp, entry);
1408 } else {
1409 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
1410 if (err) {
1411 return err;
1415 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1416 err = kvm_update_guest_debug(env, 0);
1417 if (err) {
1418 return err;
1421 return 0;
1424 int kvm_remove_breakpoint(CPUState *current_env, target_ulong addr,
1425 target_ulong len, int type)
1427 struct kvm_sw_breakpoint *bp;
1428 CPUState *env;
1429 int err;
1431 if (type == GDB_BREAKPOINT_SW) {
1432 bp = kvm_find_sw_breakpoint(current_env, addr);
1433 if (!bp) {
1434 return -ENOENT;
1437 if (bp->use_count > 1) {
1438 bp->use_count--;
1439 return 0;
1442 err = kvm_arch_remove_sw_breakpoint(current_env, bp);
1443 if (err) {
1444 return err;
1447 QTAILQ_REMOVE(&current_env->kvm_state->kvm_sw_breakpoints, bp, entry);
1448 g_free(bp);
1449 } else {
1450 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
1451 if (err) {
1452 return err;
1456 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1457 err = kvm_update_guest_debug(env, 0);
1458 if (err) {
1459 return err;
1462 return 0;
1465 void kvm_remove_all_breakpoints(CPUState *current_env)
1467 struct kvm_sw_breakpoint *bp, *next;
1468 KVMState *s = current_env->kvm_state;
1469 CPUState *env;
1471 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
1472 if (kvm_arch_remove_sw_breakpoint(current_env, bp) != 0) {
1473 /* Try harder to find a CPU that currently sees the breakpoint. */
1474 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1475 if (kvm_arch_remove_sw_breakpoint(env, bp) == 0) {
1476 break;
1481 kvm_arch_remove_all_hw_breakpoints();
1483 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1484 kvm_update_guest_debug(env, 0);
1488 #else /* !KVM_CAP_SET_GUEST_DEBUG */
1490 int kvm_update_guest_debug(CPUState *env, unsigned long reinject_trap)
1492 return -EINVAL;
1495 int kvm_insert_breakpoint(CPUState *current_env, target_ulong addr,
1496 target_ulong len, int type)
1498 return -EINVAL;
1501 int kvm_remove_breakpoint(CPUState *current_env, target_ulong addr,
1502 target_ulong len, int type)
1504 return -EINVAL;
1507 void kvm_remove_all_breakpoints(CPUState *current_env)
1510 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
1512 int kvm_set_signal_mask(CPUState *env, const sigset_t *sigset)
1514 struct kvm_signal_mask *sigmask;
1515 int r;
1517 if (!sigset) {
1518 return kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, NULL);
1521 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
1523 sigmask->len = 8;
1524 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
1525 r = kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, sigmask);
1526 g_free(sigmask);
1528 return r;
1531 int kvm_set_ioeventfd_mmio_long(int fd, uint32_t addr, uint32_t val, bool assign)
1533 int ret;
1534 struct kvm_ioeventfd iofd;
1536 iofd.datamatch = val;
1537 iofd.addr = addr;
1538 iofd.len = 4;
1539 iofd.flags = KVM_IOEVENTFD_FLAG_DATAMATCH;
1540 iofd.fd = fd;
1542 if (!kvm_enabled()) {
1543 return -ENOSYS;
1546 if (!assign) {
1547 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1550 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
1552 if (ret < 0) {
1553 return -errno;
1556 return 0;
1559 int kvm_set_ioeventfd_pio_word(int fd, uint16_t addr, uint16_t val, bool assign)
1561 struct kvm_ioeventfd kick = {
1562 .datamatch = val,
1563 .addr = addr,
1564 .len = 2,
1565 .flags = KVM_IOEVENTFD_FLAG_DATAMATCH | KVM_IOEVENTFD_FLAG_PIO,
1566 .fd = fd,
1568 int r;
1569 if (!kvm_enabled()) {
1570 return -ENOSYS;
1572 if (!assign) {
1573 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1575 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
1576 if (r < 0) {
1577 return r;
1579 return 0;
1582 int kvm_on_sigbus_vcpu(CPUState *env, int code, void *addr)
1584 return kvm_arch_on_sigbus_vcpu(env, code, addr);
1587 int kvm_on_sigbus(int code, void *addr)
1589 return kvm_arch_on_sigbus(code, addr);