vmsvga: don't process more than 1024 fifo commands at once
[qemu.git] / kvm-all.c
1 /*
2 * QEMU KVM support
3 *
4 * Copyright IBM, Corp. 2008
5 * Red Hat, Inc. 2008
6 *
7 * Authors:
8 * Anthony Liguori <aliguori@us.ibm.com>
9 * Glauber Costa <gcosta@redhat.com>
10 *
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.
13 *
14 */
15
16 #include "qemu/osdep.h"
17 #include <sys/ioctl.h>
18 #include <sys/mman.h>
19
20 #include <linux/kvm.h>
21
22 #include "qemu-common.h"
23 #include "qemu/atomic.h"
24 #include "qemu/option.h"
25 #include "qemu/config-file.h"
26 #include "qemu/error-report.h"
27 #include "hw/hw.h"
28 #include "hw/pci/msi.h"
29 #include "hw/s390x/adapter.h"
30 #include "exec/gdbstub.h"
31 #include "sysemu/kvm_int.h"
32 #include "qemu/bswap.h"
33 #include "exec/memory.h"
34 #include "exec/ram_addr.h"
35 #include "exec/address-spaces.h"
36 #include "qemu/event_notifier.h"
37 #include "trace.h"
38 #include "hw/irq.h"
39
40 #include "hw/boards.h"
41
42 /* This check must be after config-host.h is included */
43 #ifdef CONFIG_EVENTFD
44 #include <sys/eventfd.h>
45 #endif
46
47 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
48 * need to use the real host PAGE_SIZE, as that's what KVM will use.
49 */
50 #define PAGE_SIZE getpagesize()
51
52 //#define DEBUG_KVM
53
54 #ifdef DEBUG_KVM
55 #define DPRINTF(fmt, ...) \
56 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
57 #else
58 #define DPRINTF(fmt, ...) \
59 do { } while (0)
60 #endif
61
62 #define KVM_MSI_HASHTAB_SIZE 256
63
64 struct KVMParkedVcpu {
65 unsigned long vcpu_id;
66 int kvm_fd;
67 QLIST_ENTRY(KVMParkedVcpu) node;
68 };
69
70 struct KVMState
71 {
72 AccelState parent_obj;
73
74 int nr_slots;
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 vcpu_events;
82 int robust_singlestep;
83 int debugregs;
84 #ifdef KVM_CAP_SET_GUEST_DEBUG
85 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
86 #endif
87 int many_ioeventfds;
88 int intx_set_mask;
89 /* The man page (and posix) say ioctl numbers are signed int, but
90 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
91 * unsigned, and treating them as signed here can break things */
92 unsigned irq_set_ioctl;
93 unsigned int sigmask_len;
94 GHashTable *gsimap;
95 #ifdef KVM_CAP_IRQ_ROUTING
96 struct kvm_irq_routing *irq_routes;
97 int nr_allocated_irq_routes;
98 unsigned long *used_gsi_bitmap;
99 unsigned int gsi_count;
100 QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
101 #endif
102 KVMMemoryListener memory_listener;
103 QLIST_HEAD(, KVMParkedVcpu) kvm_parked_vcpus;
104 };
105
106 KVMState *kvm_state;
107 bool kvm_kernel_irqchip;
108 bool kvm_split_irqchip;
109 bool kvm_async_interrupts_allowed;
110 bool kvm_halt_in_kernel_allowed;
111 bool kvm_eventfds_allowed;
112 bool kvm_irqfds_allowed;
113 bool kvm_resamplefds_allowed;
114 bool kvm_msi_via_irqfd_allowed;
115 bool kvm_gsi_routing_allowed;
116 bool kvm_gsi_direct_mapping;
117 bool kvm_allowed;
118 bool kvm_readonly_mem_allowed;
119 bool kvm_vm_attributes_allowed;
120 bool kvm_direct_msi_allowed;
121 bool kvm_ioeventfd_any_length_allowed;
122
123 static const KVMCapabilityInfo kvm_required_capabilites[] = {
124 KVM_CAP_INFO(USER_MEMORY),
125 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
126 KVM_CAP_LAST_INFO
127 };
128
129 static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
130 {
131 KVMState *s = kvm_state;
132 int i;
133
134 for (i = 0; i < s->nr_slots; i++) {
135 if (kml->slots[i].memory_size == 0) {
136 return &kml->slots[i];
137 }
138 }
139
140 return NULL;
141 }
142
143 bool kvm_has_free_slot(MachineState *ms)
144 {
145 KVMState *s = KVM_STATE(ms->accelerator);
146
147 return kvm_get_free_slot(&s->memory_listener);
148 }
149
150 static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
151 {
152 KVMSlot *slot = kvm_get_free_slot(kml);
153
154 if (slot) {
155 return slot;
156 }
157
158 fprintf(stderr, "%s: no free slot available\n", __func__);
159 abort();
160 }
161
162 static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
163 hwaddr start_addr,
164 hwaddr end_addr)
165 {
166 KVMState *s = kvm_state;
167 int i;
168
169 for (i = 0; i < s->nr_slots; i++) {
170 KVMSlot *mem = &kml->slots[i];
171
172 if (start_addr == mem->start_addr &&
173 end_addr == mem->start_addr + mem->memory_size) {
174 return mem;
175 }
176 }
177
178 return NULL;
179 }
180
181 /*
182 * Find overlapping slot with lowest start address
183 */
184 static KVMSlot *kvm_lookup_overlapping_slot(KVMMemoryListener *kml,
185 hwaddr start_addr,
186 hwaddr end_addr)
187 {
188 KVMState *s = kvm_state;
189 KVMSlot *found = NULL;
190 int i;
191
192 for (i = 0; i < s->nr_slots; i++) {
193 KVMSlot *mem = &kml->slots[i];
194
195 if (mem->memory_size == 0 ||
196 (found && found->start_addr < mem->start_addr)) {
197 continue;
198 }
199
200 if (end_addr > mem->start_addr &&
201 start_addr < mem->start_addr + mem->memory_size) {
202 found = mem;
203 }
204 }
205
206 return found;
207 }
208
209 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
210 hwaddr *phys_addr)
211 {
212 KVMMemoryListener *kml = &s->memory_listener;
213 int i;
214
215 for (i = 0; i < s->nr_slots; i++) {
216 KVMSlot *mem = &kml->slots[i];
217
218 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
219 *phys_addr = mem->start_addr + (ram - mem->ram);
220 return 1;
221 }
222 }
223
224 return 0;
225 }
226
227 static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot)
228 {
229 KVMState *s = kvm_state;
230 struct kvm_userspace_memory_region mem;
231
232 mem.slot = slot->slot | (kml->as_id << 16);
233 mem.guest_phys_addr = slot->start_addr;
234 mem.userspace_addr = (unsigned long)slot->ram;
235 mem.flags = slot->flags;
236
237 if (slot->memory_size && mem.flags & KVM_MEM_READONLY) {
238 /* Set the slot size to 0 before setting the slot to the desired
239 * value. This is needed based on KVM commit 75d61fbc. */
240 mem.memory_size = 0;
241 kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
242 }
243 mem.memory_size = slot->memory_size;
244 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
245 }
246
247 int kvm_destroy_vcpu(CPUState *cpu)
248 {
249 KVMState *s = kvm_state;
250 long mmap_size;
251 struct KVMParkedVcpu *vcpu = NULL;
252 int ret = 0;
253
254 DPRINTF("kvm_destroy_vcpu\n");
255
256 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
257 if (mmap_size < 0) {
258 ret = mmap_size;
259 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
260 goto err;
261 }
262
263 ret = munmap(cpu->kvm_run, mmap_size);
264 if (ret < 0) {
265 goto err;
266 }
267
268 vcpu = g_malloc0(sizeof(*vcpu));
269 vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
270 vcpu->kvm_fd = cpu->kvm_fd;
271 QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
272 err:
273 return ret;
274 }
275
276 static int kvm_get_vcpu(KVMState *s, unsigned long vcpu_id)
277 {
278 struct KVMParkedVcpu *cpu;
279
280 QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
281 if (cpu->vcpu_id == vcpu_id) {
282 int kvm_fd;
283
284 QLIST_REMOVE(cpu, node);
285 kvm_fd = cpu->kvm_fd;
286 g_free(cpu);
287 return kvm_fd;
288 }
289 }
290
291 return kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)vcpu_id);
292 }
293
294 int kvm_init_vcpu(CPUState *cpu)
295 {
296 KVMState *s = kvm_state;
297 long mmap_size;
298 int ret;
299
300 DPRINTF("kvm_init_vcpu\n");
301
302 ret = kvm_get_vcpu(s, kvm_arch_vcpu_id(cpu));
303 if (ret < 0) {
304 DPRINTF("kvm_create_vcpu failed\n");
305 goto err;
306 }
307
308 cpu->kvm_fd = ret;
309 cpu->kvm_state = s;
310 cpu->kvm_vcpu_dirty = true;
311
312 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
313 if (mmap_size < 0) {
314 ret = mmap_size;
315 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
316 goto err;
317 }
318
319 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
320 cpu->kvm_fd, 0);
321 if (cpu->kvm_run == MAP_FAILED) {
322 ret = -errno;
323 DPRINTF("mmap'ing vcpu state failed\n");
324 goto err;
325 }
326
327 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
328 s->coalesced_mmio_ring =
329 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
330 }
331
332 ret = kvm_arch_init_vcpu(cpu);
333 err:
334 return ret;
335 }
336
337 /*
338 * dirty pages logging control
339 */
340
341 static int kvm_mem_flags(MemoryRegion *mr)
342 {
343 bool readonly = mr->readonly || memory_region_is_romd(mr);
344 int flags = 0;
345
346 if (memory_region_get_dirty_log_mask(mr) != 0) {
347 flags |= KVM_MEM_LOG_DIRTY_PAGES;
348 }
349 if (readonly && kvm_readonly_mem_allowed) {
350 flags |= KVM_MEM_READONLY;
351 }
352 return flags;
353 }
354
355 static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
356 MemoryRegion *mr)
357 {
358 int old_flags;
359
360 old_flags = mem->flags;
361 mem->flags = kvm_mem_flags(mr);
362
363 /* If nothing changed effectively, no need to issue ioctl */
364 if (mem->flags == old_flags) {
365 return 0;
366 }
367
368 return kvm_set_user_memory_region(kml, mem);
369 }
370
371 static int kvm_section_update_flags(KVMMemoryListener *kml,
372 MemoryRegionSection *section)
373 {
374 hwaddr phys_addr = section->offset_within_address_space;
375 ram_addr_t size = int128_get64(section->size);
376 KVMSlot *mem = kvm_lookup_matching_slot(kml, phys_addr, phys_addr + size);
377
378 if (mem == NULL) {
379 return 0;
380 } else {
381 return kvm_slot_update_flags(kml, mem, section->mr);
382 }
383 }
384
385 static void kvm_log_start(MemoryListener *listener,
386 MemoryRegionSection *section,
387 int old, int new)
388 {
389 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
390 int r;
391
392 if (old != 0) {
393 return;
394 }
395
396 r = kvm_section_update_flags(kml, section);
397 if (r < 0) {
398 abort();
399 }
400 }
401
402 static void kvm_log_stop(MemoryListener *listener,
403 MemoryRegionSection *section,
404 int old, int new)
405 {
406 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
407 int r;
408
409 if (new != 0) {
410 return;
411 }
412
413 r = kvm_section_update_flags(kml, section);
414 if (r < 0) {
415 abort();
416 }
417 }
418
419 /* get kvm's dirty pages bitmap and update qemu's */
420 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
421 unsigned long *bitmap)
422 {
423 ram_addr_t start = section->offset_within_region +
424 memory_region_get_ram_addr(section->mr);
425 ram_addr_t pages = int128_get64(section->size) / getpagesize();
426
427 cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
428 return 0;
429 }
430
431 #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
432
433 /**
434 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
435 * This function updates qemu's dirty bitmap using
436 * memory_region_set_dirty(). This means all bits are set
437 * to dirty.
438 *
439 * @start_add: start of logged region.
440 * @end_addr: end of logged region.
441 */
442 static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
443 MemoryRegionSection *section)
444 {
445 KVMState *s = kvm_state;
446 unsigned long size, allocated_size = 0;
447 struct kvm_dirty_log d = {};
448 KVMSlot *mem;
449 int ret = 0;
450 hwaddr start_addr = section->offset_within_address_space;
451 hwaddr end_addr = start_addr + int128_get64(section->size);
452
453 d.dirty_bitmap = NULL;
454 while (start_addr < end_addr) {
455 mem = kvm_lookup_overlapping_slot(kml, start_addr, end_addr);
456 if (mem == NULL) {
457 break;
458 }
459
460 /* XXX bad kernel interface alert
461 * For dirty bitmap, kernel allocates array of size aligned to
462 * bits-per-long. But for case when the kernel is 64bits and
463 * the userspace is 32bits, userspace can't align to the same
464 * bits-per-long, since sizeof(long) is different between kernel
465 * and user space. This way, userspace will provide buffer which
466 * may be 4 bytes less than the kernel will use, resulting in
467 * userspace memory corruption (which is not detectable by valgrind
468 * too, in most cases).
469 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
470 * a hope that sizeof(long) won't become >8 any time soon.
471 */
472 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
473 /*HOST_LONG_BITS*/ 64) / 8;
474 if (!d.dirty_bitmap) {
475 d.dirty_bitmap = g_malloc(size);
476 } else if (size > allocated_size) {
477 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
478 }
479 allocated_size = size;
480 memset(d.dirty_bitmap, 0, allocated_size);
481
482 d.slot = mem->slot | (kml->as_id << 16);
483 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
484 DPRINTF("ioctl failed %d\n", errno);
485 ret = -1;
486 break;
487 }
488
489 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
490 start_addr = mem->start_addr + mem->memory_size;
491 }
492 g_free(d.dirty_bitmap);
493
494 return ret;
495 }
496
497 static void kvm_coalesce_mmio_region(MemoryListener *listener,
498 MemoryRegionSection *secion,
499 hwaddr start, hwaddr size)
500 {
501 KVMState *s = kvm_state;
502
503 if (s->coalesced_mmio) {
504 struct kvm_coalesced_mmio_zone zone;
505
506 zone.addr = start;
507 zone.size = size;
508 zone.pad = 0;
509
510 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
511 }
512 }
513
514 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
515 MemoryRegionSection *secion,
516 hwaddr start, hwaddr size)
517 {
518 KVMState *s = kvm_state;
519
520 if (s->coalesced_mmio) {
521 struct kvm_coalesced_mmio_zone zone;
522
523 zone.addr = start;
524 zone.size = size;
525 zone.pad = 0;
526
527 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
528 }
529 }
530
531 int kvm_check_extension(KVMState *s, unsigned int extension)
532 {
533 int ret;
534
535 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
536 if (ret < 0) {
537 ret = 0;
538 }
539
540 return ret;
541 }
542
543 int kvm_vm_check_extension(KVMState *s, unsigned int extension)
544 {
545 int ret;
546
547 ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
548 if (ret < 0) {
549 /* VM wide version not implemented, use global one instead */
550 ret = kvm_check_extension(s, extension);
551 }
552
553 return ret;
554 }
555
556 static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
557 {
558 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
559 /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
560 * endianness, but the memory core hands them in target endianness.
561 * For example, PPC is always treated as big-endian even if running
562 * on KVM and on PPC64LE. Correct here.
563 */
564 switch (size) {
565 case 2:
566 val = bswap16(val);
567 break;
568 case 4:
569 val = bswap32(val);
570 break;
571 }
572 #endif
573 return val;
574 }
575
576 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
577 bool assign, uint32_t size, bool datamatch)
578 {
579 int ret;
580 struct kvm_ioeventfd iofd = {
581 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
582 .addr = addr,
583 .len = size,
584 .flags = 0,
585 .fd = fd,
586 };
587
588 if (!kvm_enabled()) {
589 return -ENOSYS;
590 }
591
592 if (datamatch) {
593 iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
594 }
595 if (!assign) {
596 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
597 }
598
599 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
600
601 if (ret < 0) {
602 return -errno;
603 }
604
605 return 0;
606 }
607
608 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
609 bool assign, uint32_t size, bool datamatch)
610 {
611 struct kvm_ioeventfd kick = {
612 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
613 .addr = addr,
614 .flags = KVM_IOEVENTFD_FLAG_PIO,
615 .len = size,
616 .fd = fd,
617 };
618 int r;
619 if (!kvm_enabled()) {
620 return -ENOSYS;
621 }
622 if (datamatch) {
623 kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
624 }
625 if (!assign) {
626 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
627 }
628 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
629 if (r < 0) {
630 return r;
631 }
632 return 0;
633 }
634
635
636 static int kvm_check_many_ioeventfds(void)
637 {
638 /* Userspace can use ioeventfd for io notification. This requires a host
639 * that supports eventfd(2) and an I/O thread; since eventfd does not
640 * support SIGIO it cannot interrupt the vcpu.
641 *
642 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
643 * can avoid creating too many ioeventfds.
644 */
645 #if defined(CONFIG_EVENTFD)
646 int ioeventfds[7];
647 int i, ret = 0;
648 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
649 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
650 if (ioeventfds[i] < 0) {
651 break;
652 }
653 ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
654 if (ret < 0) {
655 close(ioeventfds[i]);
656 break;
657 }
658 }
659
660 /* Decide whether many devices are supported or not */
661 ret = i == ARRAY_SIZE(ioeventfds);
662
663 while (i-- > 0) {
664 kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
665 close(ioeventfds[i]);
666 }
667 return ret;
668 #else
669 return 0;
670 #endif
671 }
672
673 static const KVMCapabilityInfo *
674 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
675 {
676 while (list->name) {
677 if (!kvm_check_extension(s, list->value)) {
678 return list;
679 }
680 list++;
681 }
682 return NULL;
683 }
684
685 static void kvm_set_phys_mem(KVMMemoryListener *kml,
686 MemoryRegionSection *section, bool add)
687 {
688 KVMState *s = kvm_state;
689 KVMSlot *mem, old;
690 int err;
691 MemoryRegion *mr = section->mr;
692 bool writeable = !mr->readonly && !mr->rom_device;
693 hwaddr start_addr = section->offset_within_address_space;
694 ram_addr_t size = int128_get64(section->size);
695 void *ram = NULL;
696 unsigned delta;
697
698 /* kvm works in page size chunks, but the function may be called
699 with sub-page size and unaligned start address. Pad the start
700 address to next and truncate size to previous page boundary. */
701 delta = qemu_real_host_page_size - (start_addr & ~qemu_real_host_page_mask);
702 delta &= ~qemu_real_host_page_mask;
703 if (delta > size) {
704 return;
705 }
706 start_addr += delta;
707 size -= delta;
708 size &= qemu_real_host_page_mask;
709 if (!size || (start_addr & ~qemu_real_host_page_mask)) {
710 return;
711 }
712
713 if (!memory_region_is_ram(mr)) {
714 if (writeable || !kvm_readonly_mem_allowed) {
715 return;
716 } else if (!mr->romd_mode) {
717 /* If the memory device is not in romd_mode, then we actually want
718 * to remove the kvm memory slot so all accesses will trap. */
719 add = false;
720 }
721 }
722
723 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
724
725 while (1) {
726 mem = kvm_lookup_overlapping_slot(kml, start_addr, start_addr + size);
727 if (!mem) {
728 break;
729 }
730
731 if (add && start_addr >= mem->start_addr &&
732 (start_addr + size <= mem->start_addr + mem->memory_size) &&
733 (ram - start_addr == mem->ram - mem->start_addr)) {
734 /* The new slot fits into the existing one and comes with
735 * identical parameters - update flags and done. */
736 kvm_slot_update_flags(kml, mem, mr);
737 return;
738 }
739
740 old = *mem;
741
742 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
743 kvm_physical_sync_dirty_bitmap(kml, section);
744 }
745
746 /* unregister the overlapping slot */
747 mem->memory_size = 0;
748 err = kvm_set_user_memory_region(kml, mem);
749 if (err) {
750 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
751 __func__, strerror(-err));
752 abort();
753 }
754
755 /* Workaround for older KVM versions: we can't join slots, even not by
756 * unregistering the previous ones and then registering the larger
757 * slot. We have to maintain the existing fragmentation. Sigh.
758 *
759 * This workaround assumes that the new slot starts at the same
760 * address as the first existing one. If not or if some overlapping
761 * slot comes around later, we will fail (not seen in practice so far)
762 * - and actually require a recent KVM version. */
763 if (s->broken_set_mem_region &&
764 old.start_addr == start_addr && old.memory_size < size && add) {
765 mem = kvm_alloc_slot(kml);
766 mem->memory_size = old.memory_size;
767 mem->start_addr = old.start_addr;
768 mem->ram = old.ram;
769 mem->flags = kvm_mem_flags(mr);
770
771 err = kvm_set_user_memory_region(kml, mem);
772 if (err) {
773 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
774 strerror(-err));
775 abort();
776 }
777
778 start_addr += old.memory_size;
779 ram += old.memory_size;
780 size -= old.memory_size;
781 continue;
782 }
783
784 /* register prefix slot */
785 if (old.start_addr < start_addr) {
786 mem = kvm_alloc_slot(kml);
787 mem->memory_size = start_addr - old.start_addr;
788 mem->start_addr = old.start_addr;
789 mem->ram = old.ram;
790 mem->flags = kvm_mem_flags(mr);
791
792 err = kvm_set_user_memory_region(kml, mem);
793 if (err) {
794 fprintf(stderr, "%s: error registering prefix slot: %s\n",
795 __func__, strerror(-err));
796 #ifdef TARGET_PPC
797 fprintf(stderr, "%s: This is probably because your kernel's " \
798 "PAGE_SIZE is too big. Please try to use 4k " \
799 "PAGE_SIZE!\n", __func__);
800 #endif
801 abort();
802 }
803 }
804
805 /* register suffix slot */
806 if (old.start_addr + old.memory_size > start_addr + size) {
807 ram_addr_t size_delta;
808
809 mem = kvm_alloc_slot(kml);
810 mem->start_addr = start_addr + size;
811 size_delta = mem->start_addr - old.start_addr;
812 mem->memory_size = old.memory_size - size_delta;
813 mem->ram = old.ram + size_delta;
814 mem->flags = kvm_mem_flags(mr);
815
816 err = kvm_set_user_memory_region(kml, mem);
817 if (err) {
818 fprintf(stderr, "%s: error registering suffix slot: %s\n",
819 __func__, strerror(-err));
820 abort();
821 }
822 }
823 }
824
825 /* in case the KVM bug workaround already "consumed" the new slot */
826 if (!size) {
827 return;
828 }
829 if (!add) {
830 return;
831 }
832 mem = kvm_alloc_slot(kml);
833 mem->memory_size = size;
834 mem->start_addr = start_addr;
835 mem->ram = ram;
836 mem->flags = kvm_mem_flags(mr);
837
838 err = kvm_set_user_memory_region(kml, mem);
839 if (err) {
840 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
841 strerror(-err));
842 abort();
843 }
844 }
845
846 static void kvm_region_add(MemoryListener *listener,
847 MemoryRegionSection *section)
848 {
849 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
850
851 memory_region_ref(section->mr);
852 kvm_set_phys_mem(kml, section, true);
853 }
854
855 static void kvm_region_del(MemoryListener *listener,
856 MemoryRegionSection *section)
857 {
858 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
859
860 kvm_set_phys_mem(kml, section, false);
861 memory_region_unref(section->mr);
862 }
863
864 static void kvm_log_sync(MemoryListener *listener,
865 MemoryRegionSection *section)
866 {
867 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
868 int r;
869
870 r = kvm_physical_sync_dirty_bitmap(kml, section);
871 if (r < 0) {
872 abort();
873 }
874 }
875
876 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
877 MemoryRegionSection *section,
878 bool match_data, uint64_t data,
879 EventNotifier *e)
880 {
881 int fd = event_notifier_get_fd(e);
882 int r;
883
884 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
885 data, true, int128_get64(section->size),
886 match_data);
887 if (r < 0) {
888 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
889 __func__, strerror(-r));
890 abort();
891 }
892 }
893
894 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
895 MemoryRegionSection *section,
896 bool match_data, uint64_t data,
897 EventNotifier *e)
898 {
899 int fd = event_notifier_get_fd(e);
900 int r;
901
902 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
903 data, false, int128_get64(section->size),
904 match_data);
905 if (r < 0) {
906 abort();
907 }
908 }
909
910 static void kvm_io_ioeventfd_add(MemoryListener *listener,
911 MemoryRegionSection *section,
912 bool match_data, uint64_t data,
913 EventNotifier *e)
914 {
915 int fd = event_notifier_get_fd(e);
916 int r;
917
918 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
919 data, true, int128_get64(section->size),
920 match_data);
921 if (r < 0) {
922 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
923 __func__, strerror(-r));
924 abort();
925 }
926 }
927
928 static void kvm_io_ioeventfd_del(MemoryListener *listener,
929 MemoryRegionSection *section,
930 bool match_data, uint64_t data,
931 EventNotifier *e)
932
933 {
934 int fd = event_notifier_get_fd(e);
935 int r;
936
937 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
938 data, false, int128_get64(section->size),
939 match_data);
940 if (r < 0) {
941 abort();
942 }
943 }
944
945 void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
946 AddressSpace *as, int as_id)
947 {
948 int i;
949
950 kml->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
951 kml->as_id = as_id;
952
953 for (i = 0; i < s->nr_slots; i++) {
954 kml->slots[i].slot = i;
955 }
956
957 kml->listener.region_add = kvm_region_add;
958 kml->listener.region_del = kvm_region_del;
959 kml->listener.log_start = kvm_log_start;
960 kml->listener.log_stop = kvm_log_stop;
961 kml->listener.log_sync = kvm_log_sync;
962 kml->listener.priority = 10;
963
964 memory_listener_register(&kml->listener, as);
965 }
966
967 static MemoryListener kvm_io_listener = {
968 .eventfd_add = kvm_io_ioeventfd_add,
969 .eventfd_del = kvm_io_ioeventfd_del,
970 .priority = 10,
971 };
972
973 static void kvm_handle_interrupt(CPUState *cpu, int mask)
974 {
975 cpu->interrupt_request |= mask;
976
977 if (!qemu_cpu_is_self(cpu)) {
978 qemu_cpu_kick(cpu);
979 }
980 }
981
982 int kvm_set_irq(KVMState *s, int irq, int level)
983 {
984 struct kvm_irq_level event;
985 int ret;
986
987 assert(kvm_async_interrupts_enabled());
988
989 event.level = level;
990 event.irq = irq;
991 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
992 if (ret < 0) {
993 perror("kvm_set_irq");
994 abort();
995 }
996
997 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
998 }
999
1000 #ifdef KVM_CAP_IRQ_ROUTING
1001 typedef struct KVMMSIRoute {
1002 struct kvm_irq_routing_entry kroute;
1003 QTAILQ_ENTRY(KVMMSIRoute) entry;
1004 } KVMMSIRoute;
1005
1006 static void set_gsi(KVMState *s, unsigned int gsi)
1007 {
1008 set_bit(gsi, s->used_gsi_bitmap);
1009 }
1010
1011 static void clear_gsi(KVMState *s, unsigned int gsi)
1012 {
1013 clear_bit(gsi, s->used_gsi_bitmap);
1014 }
1015
1016 void kvm_init_irq_routing(KVMState *s)
1017 {
1018 int gsi_count, i;
1019
1020 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
1021 if (gsi_count > 0) {
1022 /* Round up so we can search ints using ffs */
1023 s->used_gsi_bitmap = bitmap_new(gsi_count);
1024 s->gsi_count = gsi_count;
1025 }
1026
1027 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
1028 s->nr_allocated_irq_routes = 0;
1029
1030 if (!kvm_direct_msi_allowed) {
1031 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
1032 QTAILQ_INIT(&s->msi_hashtab[i]);
1033 }
1034 }
1035
1036 kvm_arch_init_irq_routing(s);
1037 }
1038
1039 void kvm_irqchip_commit_routes(KVMState *s)
1040 {
1041 int ret;
1042
1043 s->irq_routes->flags = 0;
1044 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1045 assert(ret == 0);
1046 }
1047
1048 static void kvm_add_routing_entry(KVMState *s,
1049 struct kvm_irq_routing_entry *entry)
1050 {
1051 struct kvm_irq_routing_entry *new;
1052 int n, size;
1053
1054 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1055 n = s->nr_allocated_irq_routes * 2;
1056 if (n < 64) {
1057 n = 64;
1058 }
1059 size = sizeof(struct kvm_irq_routing);
1060 size += n * sizeof(*new);
1061 s->irq_routes = g_realloc(s->irq_routes, size);
1062 s->nr_allocated_irq_routes = n;
1063 }
1064 n = s->irq_routes->nr++;
1065 new = &s->irq_routes->entries[n];
1066
1067 *new = *entry;
1068
1069 set_gsi(s, entry->gsi);
1070 }
1071
1072 static int kvm_update_routing_entry(KVMState *s,
1073 struct kvm_irq_routing_entry *new_entry)
1074 {
1075 struct kvm_irq_routing_entry *entry;
1076 int n;
1077
1078 for (n = 0; n < s->irq_routes->nr; n++) {
1079 entry = &s->irq_routes->entries[n];
1080 if (entry->gsi != new_entry->gsi) {
1081 continue;
1082 }
1083
1084 if(!memcmp(entry, new_entry, sizeof *entry)) {
1085 return 0;
1086 }
1087
1088 *entry = *new_entry;
1089
1090 kvm_irqchip_commit_routes(s);
1091
1092 return 0;
1093 }
1094
1095 return -ESRCH;
1096 }
1097
1098 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1099 {
1100 struct kvm_irq_routing_entry e = {};
1101
1102 assert(pin < s->gsi_count);
1103
1104 e.gsi = irq;
1105 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1106 e.flags = 0;
1107 e.u.irqchip.irqchip = irqchip;
1108 e.u.irqchip.pin = pin;
1109 kvm_add_routing_entry(s, &e);
1110 }
1111
1112 void kvm_irqchip_release_virq(KVMState *s, int virq)
1113 {
1114 struct kvm_irq_routing_entry *e;
1115 int i;
1116
1117 if (kvm_gsi_direct_mapping()) {
1118 return;
1119 }
1120
1121 for (i = 0; i < s->irq_routes->nr; i++) {
1122 e = &s->irq_routes->entries[i];
1123 if (e->gsi == virq) {
1124 s->irq_routes->nr--;
1125 *e = s->irq_routes->entries[s->irq_routes->nr];
1126 }
1127 }
1128 clear_gsi(s, virq);
1129 }
1130
1131 static unsigned int kvm_hash_msi(uint32_t data)
1132 {
1133 /* This is optimized for IA32 MSI layout. However, no other arch shall
1134 * repeat the mistake of not providing a direct MSI injection API. */
1135 return data & 0xff;
1136 }
1137
1138 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1139 {
1140 KVMMSIRoute *route, *next;
1141 unsigned int hash;
1142
1143 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1144 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1145 kvm_irqchip_release_virq(s, route->kroute.gsi);
1146 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1147 g_free(route);
1148 }
1149 }
1150 }
1151
1152 static int kvm_irqchip_get_virq(KVMState *s)
1153 {
1154 int next_virq;
1155
1156 /*
1157 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1158 * GSI numbers are more than the number of IRQ route. Allocating a GSI
1159 * number can succeed even though a new route entry cannot be added.
1160 * When this happens, flush dynamic MSI entries to free IRQ route entries.
1161 */
1162 if (!kvm_direct_msi_allowed && s->irq_routes->nr == s->gsi_count) {
1163 kvm_flush_dynamic_msi_routes(s);
1164 }
1165
1166 /* Return the lowest unused GSI in the bitmap */
1167 next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
1168 if (next_virq >= s->gsi_count) {
1169 return -ENOSPC;
1170 } else {
1171 return next_virq;
1172 }
1173 }
1174
1175 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1176 {
1177 unsigned int hash = kvm_hash_msi(msg.data);
1178 KVMMSIRoute *route;
1179
1180 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1181 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1182 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1183 route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1184 return route;
1185 }
1186 }
1187 return NULL;
1188 }
1189
1190 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1191 {
1192 struct kvm_msi msi;
1193 KVMMSIRoute *route;
1194
1195 if (kvm_direct_msi_allowed) {
1196 msi.address_lo = (uint32_t)msg.address;
1197 msi.address_hi = msg.address >> 32;
1198 msi.data = le32_to_cpu(msg.data);
1199 msi.flags = 0;
1200 memset(msi.pad, 0, sizeof(msi.pad));
1201
1202 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1203 }
1204
1205 route = kvm_lookup_msi_route(s, msg);
1206 if (!route) {
1207 int virq;
1208
1209 virq = kvm_irqchip_get_virq(s);
1210 if (virq < 0) {
1211 return virq;
1212 }
1213
1214 route = g_malloc0(sizeof(KVMMSIRoute));
1215 route->kroute.gsi = virq;
1216 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1217 route->kroute.flags = 0;
1218 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1219 route->kroute.u.msi.address_hi = msg.address >> 32;
1220 route->kroute.u.msi.data = le32_to_cpu(msg.data);
1221
1222 kvm_add_routing_entry(s, &route->kroute);
1223 kvm_irqchip_commit_routes(s);
1224
1225 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1226 entry);
1227 }
1228
1229 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1230
1231 return kvm_set_irq(s, route->kroute.gsi, 1);
1232 }
1233
1234 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg, PCIDevice *dev)
1235 {
1236 struct kvm_irq_routing_entry kroute = {};
1237 int virq;
1238
1239 if (kvm_gsi_direct_mapping()) {
1240 return kvm_arch_msi_data_to_gsi(msg.data);
1241 }
1242
1243 if (!kvm_gsi_routing_enabled()) {
1244 return -ENOSYS;
1245 }
1246
1247 virq = kvm_irqchip_get_virq(s);
1248 if (virq < 0) {
1249 return virq;
1250 }
1251
1252 kroute.gsi = virq;
1253 kroute.type = KVM_IRQ_ROUTING_MSI;
1254 kroute.flags = 0;
1255 kroute.u.msi.address_lo = (uint32_t)msg.address;
1256 kroute.u.msi.address_hi = msg.address >> 32;
1257 kroute.u.msi.data = le32_to_cpu(msg.data);
1258 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1259 kvm_irqchip_release_virq(s, virq);
1260 return -EINVAL;
1261 }
1262
1263 kvm_add_routing_entry(s, &kroute);
1264 kvm_irqchip_commit_routes(s);
1265
1266 return virq;
1267 }
1268
1269 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
1270 PCIDevice *dev)
1271 {
1272 struct kvm_irq_routing_entry kroute = {};
1273
1274 if (kvm_gsi_direct_mapping()) {
1275 return 0;
1276 }
1277
1278 if (!kvm_irqchip_in_kernel()) {
1279 return -ENOSYS;
1280 }
1281
1282 kroute.gsi = virq;
1283 kroute.type = KVM_IRQ_ROUTING_MSI;
1284 kroute.flags = 0;
1285 kroute.u.msi.address_lo = (uint32_t)msg.address;
1286 kroute.u.msi.address_hi = msg.address >> 32;
1287 kroute.u.msi.data = le32_to_cpu(msg.data);
1288 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1289 return -EINVAL;
1290 }
1291
1292 return kvm_update_routing_entry(s, &kroute);
1293 }
1294
1295 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int rfd, int virq,
1296 bool assign)
1297 {
1298 struct kvm_irqfd irqfd = {
1299 .fd = fd,
1300 .gsi = virq,
1301 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1302 };
1303
1304 if (rfd != -1) {
1305 irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1306 irqfd.resamplefd = rfd;
1307 }
1308
1309 if (!kvm_irqfds_enabled()) {
1310 return -ENOSYS;
1311 }
1312
1313 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1314 }
1315
1316 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1317 {
1318 struct kvm_irq_routing_entry kroute = {};
1319 int virq;
1320
1321 if (!kvm_gsi_routing_enabled()) {
1322 return -ENOSYS;
1323 }
1324
1325 virq = kvm_irqchip_get_virq(s);
1326 if (virq < 0) {
1327 return virq;
1328 }
1329
1330 kroute.gsi = virq;
1331 kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1332 kroute.flags = 0;
1333 kroute.u.adapter.summary_addr = adapter->summary_addr;
1334 kroute.u.adapter.ind_addr = adapter->ind_addr;
1335 kroute.u.adapter.summary_offset = adapter->summary_offset;
1336 kroute.u.adapter.ind_offset = adapter->ind_offset;
1337 kroute.u.adapter.adapter_id = adapter->adapter_id;
1338
1339 kvm_add_routing_entry(s, &kroute);
1340
1341 return virq;
1342 }
1343
1344 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1345 {
1346 struct kvm_irq_routing_entry kroute = {};
1347 int virq;
1348
1349 if (!kvm_gsi_routing_enabled()) {
1350 return -ENOSYS;
1351 }
1352 if (!kvm_check_extension(s, KVM_CAP_HYPERV_SYNIC)) {
1353 return -ENOSYS;
1354 }
1355 virq = kvm_irqchip_get_virq(s);
1356 if (virq < 0) {
1357 return virq;
1358 }
1359
1360 kroute.gsi = virq;
1361 kroute.type = KVM_IRQ_ROUTING_HV_SINT;
1362 kroute.flags = 0;
1363 kroute.u.hv_sint.vcpu = vcpu;
1364 kroute.u.hv_sint.sint = sint;
1365
1366 kvm_add_routing_entry(s, &kroute);
1367 kvm_irqchip_commit_routes(s);
1368
1369 return virq;
1370 }
1371
1372 #else /* !KVM_CAP_IRQ_ROUTING */
1373
1374 void kvm_init_irq_routing(KVMState *s)
1375 {
1376 }
1377
1378 void kvm_irqchip_release_virq(KVMState *s, int virq)
1379 {
1380 }
1381
1382 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1383 {
1384 abort();
1385 }
1386
1387 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1388 {
1389 return -ENOSYS;
1390 }
1391
1392 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1393 {
1394 return -ENOSYS;
1395 }
1396
1397 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1398 {
1399 return -ENOSYS;
1400 }
1401
1402 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1403 {
1404 abort();
1405 }
1406
1407 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1408 {
1409 return -ENOSYS;
1410 }
1411 #endif /* !KVM_CAP_IRQ_ROUTING */
1412
1413 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1414 EventNotifier *rn, int virq)
1415 {
1416 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n),
1417 rn ? event_notifier_get_fd(rn) : -1, virq, true);
1418 }
1419
1420 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1421 int virq)
1422 {
1423 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), -1, virq,
1424 false);
1425 }
1426
1427 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1428 EventNotifier *rn, qemu_irq irq)
1429 {
1430 gpointer key, gsi;
1431 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1432
1433 if (!found) {
1434 return -ENXIO;
1435 }
1436 return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
1437 }
1438
1439 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
1440 qemu_irq irq)
1441 {
1442 gpointer key, gsi;
1443 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1444
1445 if (!found) {
1446 return -ENXIO;
1447 }
1448 return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
1449 }
1450
1451 void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
1452 {
1453 g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
1454 }
1455
1456 static void kvm_irqchip_create(MachineState *machine, KVMState *s)
1457 {
1458 int ret;
1459
1460 if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
1461 ;
1462 } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
1463 ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
1464 if (ret < 0) {
1465 fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
1466 exit(1);
1467 }
1468 } else {
1469 return;
1470 }
1471
1472 /* First probe and see if there's a arch-specific hook to create the
1473 * in-kernel irqchip for us */
1474 ret = kvm_arch_irqchip_create(machine, s);
1475 if (ret == 0) {
1476 if (machine_kernel_irqchip_split(machine)) {
1477 perror("Split IRQ chip mode not supported.");
1478 exit(1);
1479 } else {
1480 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1481 }
1482 }
1483 if (ret < 0) {
1484 fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
1485 exit(1);
1486 }
1487
1488 kvm_kernel_irqchip = true;
1489 /* If we have an in-kernel IRQ chip then we must have asynchronous
1490 * interrupt delivery (though the reverse is not necessarily true)
1491 */
1492 kvm_async_interrupts_allowed = true;
1493 kvm_halt_in_kernel_allowed = true;
1494
1495 kvm_init_irq_routing(s);
1496
1497 s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
1498 }
1499
1500 /* Find number of supported CPUs using the recommended
1501 * procedure from the kernel API documentation to cope with
1502 * older kernels that may be missing capabilities.
1503 */
1504 static int kvm_recommended_vcpus(KVMState *s)
1505 {
1506 int ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
1507 return (ret) ? ret : 4;
1508 }
1509
1510 static int kvm_max_vcpus(KVMState *s)
1511 {
1512 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1513 return (ret) ? ret : kvm_recommended_vcpus(s);
1514 }
1515
1516 bool kvm_vcpu_id_is_valid(int vcpu_id)
1517 {
1518 KVMState *s = KVM_STATE(current_machine->accelerator);
1519 return vcpu_id >= 0 && vcpu_id < kvm_max_vcpus(s);
1520 }
1521
1522 static int kvm_init(MachineState *ms)
1523 {
1524 MachineClass *mc = MACHINE_GET_CLASS(ms);
1525 static const char upgrade_note[] =
1526 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1527 "(see http://sourceforge.net/projects/kvm).\n";
1528 struct {
1529 const char *name;
1530 int num;
1531 } num_cpus[] = {
1532 { "SMP", smp_cpus },
1533 { "hotpluggable", max_cpus },
1534 { NULL, }
1535 }, *nc = num_cpus;
1536 int soft_vcpus_limit, hard_vcpus_limit;
1537 KVMState *s;
1538 const KVMCapabilityInfo *missing_cap;
1539 int ret;
1540 int type = 0;
1541 const char *kvm_type;
1542
1543 s = KVM_STATE(ms->accelerator);
1544
1545 /*
1546 * On systems where the kernel can support different base page
1547 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1548 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1549 * page size for the system though.
1550 */
1551 assert(TARGET_PAGE_SIZE <= getpagesize());
1552
1553 s->sigmask_len = 8;
1554
1555 #ifdef KVM_CAP_SET_GUEST_DEBUG
1556 QTAILQ_INIT(&s->kvm_sw_breakpoints);
1557 #endif
1558 QLIST_INIT(&s->kvm_parked_vcpus);
1559 s->vmfd = -1;
1560 s->fd = qemu_open("/dev/kvm", O_RDWR);
1561 if (s->fd == -1) {
1562 fprintf(stderr, "Could not access KVM kernel module: %m\n");
1563 ret = -errno;
1564 goto err;
1565 }
1566
1567 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1568 if (ret < KVM_API_VERSION) {
1569 if (ret >= 0) {
1570 ret = -EINVAL;
1571 }
1572 fprintf(stderr, "kvm version too old\n");
1573 goto err;
1574 }
1575
1576 if (ret > KVM_API_VERSION) {
1577 ret = -EINVAL;
1578 fprintf(stderr, "kvm version not supported\n");
1579 goto err;
1580 }
1581
1582 s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
1583
1584 /* If unspecified, use the default value */
1585 if (!s->nr_slots) {
1586 s->nr_slots = 32;
1587 }
1588
1589 /* check the vcpu limits */
1590 soft_vcpus_limit = kvm_recommended_vcpus(s);
1591 hard_vcpus_limit = kvm_max_vcpus(s);
1592
1593 while (nc->name) {
1594 if (nc->num > soft_vcpus_limit) {
1595 fprintf(stderr,
1596 "Warning: Number of %s cpus requested (%d) exceeds "
1597 "the recommended cpus supported by KVM (%d)\n",
1598 nc->name, nc->num, soft_vcpus_limit);
1599
1600 if (nc->num > hard_vcpus_limit) {
1601 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
1602 "the maximum cpus supported by KVM (%d)\n",
1603 nc->name, nc->num, hard_vcpus_limit);
1604 exit(1);
1605 }
1606 }
1607 nc++;
1608 }
1609
1610 kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1611 if (mc->kvm_type) {
1612 type = mc->kvm_type(kvm_type);
1613 } else if (kvm_type) {
1614 ret = -EINVAL;
1615 fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1616 goto err;
1617 }
1618
1619 do {
1620 ret = kvm_ioctl(s, KVM_CREATE_VM, type);
1621 } while (ret == -EINTR);
1622
1623 if (ret < 0) {
1624 fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
1625 strerror(-ret));
1626
1627 #ifdef TARGET_S390X
1628 if (ret == -EINVAL) {
1629 fprintf(stderr,
1630 "Host kernel setup problem detected. Please verify:\n");
1631 fprintf(stderr, "- for kernels supporting the switch_amode or"
1632 " user_mode parameters, whether\n");
1633 fprintf(stderr,
1634 " user space is running in primary address space\n");
1635 fprintf(stderr,
1636 "- for kernels supporting the vm.allocate_pgste sysctl, "
1637 "whether it is enabled\n");
1638 }
1639 #endif
1640 goto err;
1641 }
1642
1643 s->vmfd = ret;
1644 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1645 if (!missing_cap) {
1646 missing_cap =
1647 kvm_check_extension_list(s, kvm_arch_required_capabilities);
1648 }
1649 if (missing_cap) {
1650 ret = -EINVAL;
1651 fprintf(stderr, "kvm does not support %s\n%s",
1652 missing_cap->name, upgrade_note);
1653 goto err;
1654 }
1655
1656 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1657
1658 s->broken_set_mem_region = 1;
1659 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
1660 if (ret > 0) {
1661 s->broken_set_mem_region = 0;
1662 }
1663
1664 #ifdef KVM_CAP_VCPU_EVENTS
1665 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1666 #endif
1667
1668 s->robust_singlestep =
1669 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1670
1671 #ifdef KVM_CAP_DEBUGREGS
1672 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1673 #endif
1674
1675 #ifdef KVM_CAP_IRQ_ROUTING
1676 kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1677 #endif
1678
1679 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1680
1681 s->irq_set_ioctl = KVM_IRQ_LINE;
1682 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1683 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1684 }
1685
1686 #ifdef KVM_CAP_READONLY_MEM
1687 kvm_readonly_mem_allowed =
1688 (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1689 #endif
1690
1691 kvm_eventfds_allowed =
1692 (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
1693
1694 kvm_irqfds_allowed =
1695 (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
1696
1697 kvm_resamplefds_allowed =
1698 (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
1699
1700 kvm_vm_attributes_allowed =
1701 (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
1702
1703 kvm_ioeventfd_any_length_allowed =
1704 (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
1705
1706 ret = kvm_arch_init(ms, s);
1707 if (ret < 0) {
1708 goto err;
1709 }
1710
1711 if (machine_kernel_irqchip_allowed(ms)) {
1712 kvm_irqchip_create(ms, s);
1713 }
1714
1715 kvm_state = s;
1716
1717 if (kvm_eventfds_allowed) {
1718 s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
1719 s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
1720 }
1721 s->memory_listener.listener.coalesced_mmio_add = kvm_coalesce_mmio_region;
1722 s->memory_listener.listener.coalesced_mmio_del = kvm_uncoalesce_mmio_region;
1723
1724 kvm_memory_listener_register(s, &s->memory_listener,
1725 &address_space_memory, 0);
1726 memory_listener_register(&kvm_io_listener,
1727 &address_space_io);
1728
1729 s->many_ioeventfds = kvm_check_many_ioeventfds();
1730
1731 cpu_interrupt_handler = kvm_handle_interrupt;
1732
1733 return 0;
1734
1735 err:
1736 assert(ret < 0);
1737 if (s->vmfd >= 0) {
1738 close(s->vmfd);
1739 }
1740 if (s->fd != -1) {
1741 close(s->fd);
1742 }
1743 g_free(s->memory_listener.slots);
1744
1745 return ret;
1746 }
1747
1748 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
1749 {
1750 s->sigmask_len = sigmask_len;
1751 }
1752
1753 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
1754 int size, uint32_t count)
1755 {
1756 int i;
1757 uint8_t *ptr = data;
1758
1759 for (i = 0; i < count; i++) {
1760 address_space_rw(&address_space_io, port, attrs,
1761 ptr, size,
1762 direction == KVM_EXIT_IO_OUT);
1763 ptr += size;
1764 }
1765 }
1766
1767 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
1768 {
1769 fprintf(stderr, "KVM internal error. Suberror: %d\n",
1770 run->internal.suberror);
1771
1772 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1773 int i;
1774
1775 for (i = 0; i < run->internal.ndata; ++i) {
1776 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1777 i, (uint64_t)run->internal.data[i]);
1778 }
1779 }
1780 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1781 fprintf(stderr, "emulation failure\n");
1782 if (!kvm_arch_stop_on_emulation_error(cpu)) {
1783 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1784 return EXCP_INTERRUPT;
1785 }
1786 }
1787 /* FIXME: Should trigger a qmp message to let management know
1788 * something went wrong.
1789 */
1790 return -1;
1791 }
1792
1793 void kvm_flush_coalesced_mmio_buffer(void)
1794 {
1795 KVMState *s = kvm_state;
1796
1797 if (s->coalesced_flush_in_progress) {
1798 return;
1799 }
1800
1801 s->coalesced_flush_in_progress = true;
1802
1803 if (s->coalesced_mmio_ring) {
1804 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1805 while (ring->first != ring->last) {
1806 struct kvm_coalesced_mmio *ent;
1807
1808 ent = &ring->coalesced_mmio[ring->first];
1809
1810 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1811 smp_wmb();
1812 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1813 }
1814 }
1815
1816 s->coalesced_flush_in_progress = false;
1817 }
1818
1819 static void do_kvm_cpu_synchronize_state(void *arg)
1820 {
1821 CPUState *cpu = arg;
1822
1823 if (!cpu->kvm_vcpu_dirty) {
1824 kvm_arch_get_registers(cpu);
1825 cpu->kvm_vcpu_dirty = true;
1826 }
1827 }
1828
1829 void kvm_cpu_synchronize_state(CPUState *cpu)
1830 {
1831 if (!cpu->kvm_vcpu_dirty) {
1832 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, cpu);
1833 }
1834 }
1835
1836 static void do_kvm_cpu_synchronize_post_reset(void *arg)
1837 {
1838 CPUState *cpu = arg;
1839
1840 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1841 cpu->kvm_vcpu_dirty = false;
1842 }
1843
1844 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
1845 {
1846 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, cpu);
1847 }
1848
1849 static void do_kvm_cpu_synchronize_post_init(void *arg)
1850 {
1851 CPUState *cpu = arg;
1852
1853 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1854 cpu->kvm_vcpu_dirty = false;
1855 }
1856
1857 void kvm_cpu_synchronize_post_init(CPUState *cpu)
1858 {
1859 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, cpu);
1860 }
1861
1862 int kvm_cpu_exec(CPUState *cpu)
1863 {
1864 struct kvm_run *run = cpu->kvm_run;
1865 int ret, run_ret;
1866
1867 DPRINTF("kvm_cpu_exec()\n");
1868
1869 if (kvm_arch_process_async_events(cpu)) {
1870 cpu->exit_request = 0;
1871 return EXCP_HLT;
1872 }
1873
1874 qemu_mutex_unlock_iothread();
1875
1876 do {
1877 MemTxAttrs attrs;
1878
1879 if (cpu->kvm_vcpu_dirty) {
1880 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1881 cpu->kvm_vcpu_dirty = false;
1882 }
1883
1884 kvm_arch_pre_run(cpu, run);
1885 if (cpu->exit_request) {
1886 DPRINTF("interrupt exit requested\n");
1887 /*
1888 * KVM requires us to reenter the kernel after IO exits to complete
1889 * instruction emulation. This self-signal will ensure that we
1890 * leave ASAP again.
1891 */
1892 qemu_cpu_kick_self();
1893 }
1894
1895 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
1896
1897 attrs = kvm_arch_post_run(cpu, run);
1898
1899 if (run_ret < 0) {
1900 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1901 DPRINTF("io window exit\n");
1902 ret = EXCP_INTERRUPT;
1903 break;
1904 }
1905 fprintf(stderr, "error: kvm run failed %s\n",
1906 strerror(-run_ret));
1907 #ifdef TARGET_PPC
1908 if (run_ret == -EBUSY) {
1909 fprintf(stderr,
1910 "This is probably because your SMT is enabled.\n"
1911 "VCPU can only run on primary threads with all "
1912 "secondary threads offline.\n");
1913 }
1914 #endif
1915 ret = -1;
1916 break;
1917 }
1918
1919 trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
1920 switch (run->exit_reason) {
1921 case KVM_EXIT_IO:
1922 DPRINTF("handle_io\n");
1923 /* Called outside BQL */
1924 kvm_handle_io(run->io.port, attrs,
1925 (uint8_t *)run + run->io.data_offset,
1926 run->io.direction,
1927 run->io.size,
1928 run->io.count);
1929 ret = 0;
1930 break;
1931 case KVM_EXIT_MMIO:
1932 DPRINTF("handle_mmio\n");
1933 /* Called outside BQL */
1934 address_space_rw(&address_space_memory,
1935 run->mmio.phys_addr, attrs,
1936 run->mmio.data,
1937 run->mmio.len,
1938 run->mmio.is_write);
1939 ret = 0;
1940 break;
1941 case KVM_EXIT_IRQ_WINDOW_OPEN:
1942 DPRINTF("irq_window_open\n");
1943 ret = EXCP_INTERRUPT;
1944 break;
1945 case KVM_EXIT_SHUTDOWN:
1946 DPRINTF("shutdown\n");
1947 qemu_system_reset_request();
1948 ret = EXCP_INTERRUPT;
1949 break;
1950 case KVM_EXIT_UNKNOWN:
1951 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1952 (uint64_t)run->hw.hardware_exit_reason);
1953 ret = -1;
1954 break;
1955 case KVM_EXIT_INTERNAL_ERROR:
1956 ret = kvm_handle_internal_error(cpu, run);
1957 break;
1958 case KVM_EXIT_SYSTEM_EVENT:
1959 switch (run->system_event.type) {
1960 case KVM_SYSTEM_EVENT_SHUTDOWN:
1961 qemu_system_shutdown_request();
1962 ret = EXCP_INTERRUPT;
1963 break;
1964 case KVM_SYSTEM_EVENT_RESET:
1965 qemu_system_reset_request();
1966 ret = EXCP_INTERRUPT;
1967 break;
1968 case KVM_SYSTEM_EVENT_CRASH:
1969 qemu_mutex_lock_iothread();
1970 qemu_system_guest_panicked();
1971 qemu_mutex_unlock_iothread();
1972 ret = 0;
1973 break;
1974 default:
1975 DPRINTF("kvm_arch_handle_exit\n");
1976 ret = kvm_arch_handle_exit(cpu, run);
1977 break;
1978 }
1979 break;
1980 default:
1981 DPRINTF("kvm_arch_handle_exit\n");
1982 ret = kvm_arch_handle_exit(cpu, run);
1983 break;
1984 }
1985 } while (ret == 0);
1986
1987 qemu_mutex_lock_iothread();
1988
1989 if (ret < 0) {
1990 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1991 vm_stop(RUN_STATE_INTERNAL_ERROR);
1992 }
1993
1994 cpu->exit_request = 0;
1995 return ret;
1996 }
1997
1998 int kvm_ioctl(KVMState *s, int type, ...)
1999 {
2000 int ret;
2001 void *arg;
2002 va_list ap;
2003
2004 va_start(ap, type);
2005 arg = va_arg(ap, void *);
2006 va_end(ap);
2007
2008 trace_kvm_ioctl(type, arg);
2009 ret = ioctl(s->fd, type, arg);
2010 if (ret == -1) {
2011 ret = -errno;
2012 }
2013 return ret;
2014 }
2015
2016 int kvm_vm_ioctl(KVMState *s, int type, ...)
2017 {
2018 int ret;
2019 void *arg;
2020 va_list ap;
2021
2022 va_start(ap, type);
2023 arg = va_arg(ap, void *);
2024 va_end(ap);
2025
2026 trace_kvm_vm_ioctl(type, arg);
2027 ret = ioctl(s->vmfd, type, arg);
2028 if (ret == -1) {
2029 ret = -errno;
2030 }
2031 return ret;
2032 }
2033
2034 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
2035 {
2036 int ret;
2037 void *arg;
2038 va_list ap;
2039
2040 va_start(ap, type);
2041 arg = va_arg(ap, void *);
2042 va_end(ap);
2043
2044 trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
2045 ret = ioctl(cpu->kvm_fd, type, arg);
2046 if (ret == -1) {
2047 ret = -errno;
2048 }
2049 return ret;
2050 }
2051
2052 int kvm_device_ioctl(int fd, int type, ...)
2053 {
2054 int ret;
2055 void *arg;
2056 va_list ap;
2057
2058 va_start(ap, type);
2059 arg = va_arg(ap, void *);
2060 va_end(ap);
2061
2062 trace_kvm_device_ioctl(fd, type, arg);
2063 ret = ioctl(fd, type, arg);
2064 if (ret == -1) {
2065 ret = -errno;
2066 }
2067 return ret;
2068 }
2069
2070 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
2071 {
2072 int ret;
2073 struct kvm_device_attr attribute = {
2074 .group = group,
2075 .attr = attr,
2076 };
2077
2078 if (!kvm_vm_attributes_allowed) {
2079 return 0;
2080 }
2081
2082 ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
2083 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2084 return ret ? 0 : 1;
2085 }
2086
2087 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
2088 {
2089 struct kvm_device_attr attribute = {
2090 .group = group,
2091 .attr = attr,
2092 .flags = 0,
2093 };
2094
2095 return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
2096 }
2097
2098 void kvm_device_access(int fd, int group, uint64_t attr,
2099 void *val, bool write)
2100 {
2101 struct kvm_device_attr kvmattr;
2102 int err;
2103
2104 kvmattr.flags = 0;
2105 kvmattr.group = group;
2106 kvmattr.attr = attr;
2107 kvmattr.addr = (uintptr_t)val;
2108
2109 err = kvm_device_ioctl(fd,
2110 write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
2111 &kvmattr);
2112 if (err < 0) {
2113 error_report("KVM_%s_DEVICE_ATTR failed: %s",
2114 write ? "SET" : "GET", strerror(-err));
2115 error_printf("Group %d attr 0x%016" PRIx64, group, attr);
2116 abort();
2117 }
2118 }
2119
2120 int kvm_has_sync_mmu(void)
2121 {
2122 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2123 }
2124
2125 int kvm_has_vcpu_events(void)
2126 {
2127 return kvm_state->vcpu_events;
2128 }
2129
2130 int kvm_has_robust_singlestep(void)
2131 {
2132 return kvm_state->robust_singlestep;
2133 }
2134
2135 int kvm_has_debugregs(void)
2136 {
2137 return kvm_state->debugregs;
2138 }
2139
2140 int kvm_has_many_ioeventfds(void)
2141 {
2142 if (!kvm_enabled()) {
2143 return 0;
2144 }
2145 return kvm_state->many_ioeventfds;
2146 }
2147
2148 int kvm_has_gsi_routing(void)
2149 {
2150 #ifdef KVM_CAP_IRQ_ROUTING
2151 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
2152 #else
2153 return false;
2154 #endif
2155 }
2156
2157 int kvm_has_intx_set_mask(void)
2158 {
2159 return kvm_state->intx_set_mask;
2160 }
2161
2162 void kvm_setup_guest_memory(void *start, size_t size)
2163 {
2164 if (!kvm_has_sync_mmu()) {
2165 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
2166
2167 if (ret) {
2168 perror("qemu_madvise");
2169 fprintf(stderr,
2170 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
2171 exit(1);
2172 }
2173 }
2174 }
2175
2176 #ifdef KVM_CAP_SET_GUEST_DEBUG
2177 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
2178 target_ulong pc)
2179 {
2180 struct kvm_sw_breakpoint *bp;
2181
2182 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
2183 if (bp->pc == pc) {
2184 return bp;
2185 }
2186 }
2187 return NULL;
2188 }
2189
2190 int kvm_sw_breakpoints_active(CPUState *cpu)
2191 {
2192 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
2193 }
2194
2195 struct kvm_set_guest_debug_data {
2196 struct kvm_guest_debug dbg;
2197 CPUState *cpu;
2198 int err;
2199 };
2200
2201 static void kvm_invoke_set_guest_debug(void *data)
2202 {
2203 struct kvm_set_guest_debug_data *dbg_data = data;
2204
2205 dbg_data->err = kvm_vcpu_ioctl(dbg_data->cpu, KVM_SET_GUEST_DEBUG,
2206 &dbg_data->dbg);
2207 }
2208
2209 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2210 {
2211 struct kvm_set_guest_debug_data data;
2212
2213 data.dbg.control = reinject_trap;
2214
2215 if (cpu->singlestep_enabled) {
2216 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2217 }
2218 kvm_arch_update_guest_debug(cpu, &data.dbg);
2219 data.cpu = cpu;
2220
2221 run_on_cpu(cpu, kvm_invoke_set_guest_debug, &data);
2222 return data.err;
2223 }
2224
2225 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2226 target_ulong len, int type)
2227 {
2228 struct kvm_sw_breakpoint *bp;
2229 int err;
2230
2231 if (type == GDB_BREAKPOINT_SW) {
2232 bp = kvm_find_sw_breakpoint(cpu, addr);
2233 if (bp) {
2234 bp->use_count++;
2235 return 0;
2236 }
2237
2238 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2239 bp->pc = addr;
2240 bp->use_count = 1;
2241 err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2242 if (err) {
2243 g_free(bp);
2244 return err;
2245 }
2246
2247 QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2248 } else {
2249 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2250 if (err) {
2251 return err;
2252 }
2253 }
2254
2255 CPU_FOREACH(cpu) {
2256 err = kvm_update_guest_debug(cpu, 0);
2257 if (err) {
2258 return err;
2259 }
2260 }
2261 return 0;
2262 }
2263
2264 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2265 target_ulong len, int type)
2266 {
2267 struct kvm_sw_breakpoint *bp;
2268 int err;
2269
2270 if (type == GDB_BREAKPOINT_SW) {
2271 bp = kvm_find_sw_breakpoint(cpu, addr);
2272 if (!bp) {
2273 return -ENOENT;
2274 }
2275
2276 if (bp->use_count > 1) {
2277 bp->use_count--;
2278 return 0;
2279 }
2280
2281 err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2282 if (err) {
2283 return err;
2284 }
2285
2286 QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2287 g_free(bp);
2288 } else {
2289 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2290 if (err) {
2291 return err;
2292 }
2293 }
2294
2295 CPU_FOREACH(cpu) {
2296 err = kvm_update_guest_debug(cpu, 0);
2297 if (err) {
2298 return err;
2299 }
2300 }
2301 return 0;
2302 }
2303
2304 void kvm_remove_all_breakpoints(CPUState *cpu)
2305 {
2306 struct kvm_sw_breakpoint *bp, *next;
2307 KVMState *s = cpu->kvm_state;
2308 CPUState *tmpcpu;
2309
2310 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2311 if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2312 /* Try harder to find a CPU that currently sees the breakpoint. */
2313 CPU_FOREACH(tmpcpu) {
2314 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2315 break;
2316 }
2317 }
2318 }
2319 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2320 g_free(bp);
2321 }
2322 kvm_arch_remove_all_hw_breakpoints();
2323
2324 CPU_FOREACH(cpu) {
2325 kvm_update_guest_debug(cpu, 0);
2326 }
2327 }
2328
2329 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2330
2331 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2332 {
2333 return -EINVAL;
2334 }
2335
2336 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2337 target_ulong len, int type)
2338 {
2339 return -EINVAL;
2340 }
2341
2342 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2343 target_ulong len, int type)
2344 {
2345 return -EINVAL;
2346 }
2347
2348 void kvm_remove_all_breakpoints(CPUState *cpu)
2349 {
2350 }
2351 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2352
2353 int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2354 {
2355 KVMState *s = kvm_state;
2356 struct kvm_signal_mask *sigmask;
2357 int r;
2358
2359 if (!sigset) {
2360 return kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, NULL);
2361 }
2362
2363 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2364
2365 sigmask->len = s->sigmask_len;
2366 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2367 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2368 g_free(sigmask);
2369
2370 return r;
2371 }
2372 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2373 {
2374 return kvm_arch_on_sigbus_vcpu(cpu, code, addr);
2375 }
2376
2377 int kvm_on_sigbus(int code, void *addr)
2378 {
2379 return kvm_arch_on_sigbus(code, addr);
2380 }
2381
2382 int kvm_create_device(KVMState *s, uint64_t type, bool test)
2383 {
2384 int ret;
2385 struct kvm_create_device create_dev;
2386
2387 create_dev.type = type;
2388 create_dev.fd = -1;
2389 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2390
2391 if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2392 return -ENOTSUP;
2393 }
2394
2395 ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2396 if (ret) {
2397 return ret;
2398 }
2399
2400 return test ? 0 : create_dev.fd;
2401 }
2402
2403 bool kvm_device_supported(int vmfd, uint64_t type)
2404 {
2405 struct kvm_create_device create_dev = {
2406 .type = type,
2407 .fd = -1,
2408 .flags = KVM_CREATE_DEVICE_TEST,
2409 };
2410
2411 if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
2412 return false;
2413 }
2414
2415 return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
2416 }
2417
2418 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2419 {
2420 struct kvm_one_reg reg;
2421 int r;
2422
2423 reg.id = id;
2424 reg.addr = (uintptr_t) source;
2425 r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
2426 if (r) {
2427 trace_kvm_failed_reg_set(id, strerror(-r));
2428 }
2429 return r;
2430 }
2431
2432 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2433 {
2434 struct kvm_one_reg reg;
2435 int r;
2436
2437 reg.id = id;
2438 reg.addr = (uintptr_t) target;
2439 r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
2440 if (r) {
2441 trace_kvm_failed_reg_get(id, strerror(-r));
2442 }
2443 return r;
2444 }
2445
2446 static void kvm_accel_class_init(ObjectClass *oc, void *data)
2447 {
2448 AccelClass *ac = ACCEL_CLASS(oc);
2449 ac->name = "KVM";
2450 ac->init_machine = kvm_init;
2451 ac->allowed = &kvm_allowed;
2452 }
2453
2454 static const TypeInfo kvm_accel_type = {
2455 .name = TYPE_KVM_ACCEL,
2456 .parent = TYPE_ACCEL,
2457 .class_init = kvm_accel_class_init,
2458 .instance_size = sizeof(KVMState),
2459 };
2460
2461 static void kvm_type_init(void)
2462 {
2463 type_register_static(&kvm_accel_type);
2464 }
2465
2466 type_init(kvm_type_init);