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