xref: /openbmc/qemu/accel/kvm/kvm-all.c (revision f96b157ebb93f94cd56ebbc99bc20982b8fd86ef)
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 <poll.h>
19 
20 #include <linux/kvm.h>
21 
22 #include "qemu/atomic.h"
23 #include "qemu/option.h"
24 #include "qemu/config-file.h"
25 #include "qemu/error-report.h"
26 #include "qapi/error.h"
27 #include "hw/pci/msi.h"
28 #include "hw/pci/msix.h"
29 #include "hw/s390x/adapter.h"
30 #include "gdbstub/enums.h"
31 #include "system/kvm_int.h"
32 #include "system/runstate.h"
33 #include "system/cpus.h"
34 #include "system/accel-blocker.h"
35 #include "accel/accel-ops.h"
36 #include "qemu/bswap.h"
37 #include "exec/tswap.h"
38 #include "system/memory.h"
39 #include "system/ram_addr.h"
40 #include "qemu/event_notifier.h"
41 #include "qemu/main-loop.h"
42 #include "trace.h"
43 #include "hw/irq.h"
44 #include "qapi/visitor.h"
45 #include "qapi/qapi-types-common.h"
46 #include "qapi/qapi-visit-common.h"
47 #include "system/reset.h"
48 #include "qemu/guest-random.h"
49 #include "system/hw_accel.h"
50 #include "kvm-cpus.h"
51 #include "system/dirtylimit.h"
52 #include "qemu/range.h"
53 
54 #include "hw/boards.h"
55 #include "system/stats.h"
56 
57 /* This check must be after config-host.h is included */
58 #ifdef CONFIG_EVENTFD
59 #include <sys/eventfd.h>
60 #endif
61 
62 #if defined(__i386__) || defined(__x86_64__) || defined(__aarch64__)
63 # define KVM_HAVE_MCE_INJECTION 1
64 #endif
65 
66 
67 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
68  * need to use the real host PAGE_SIZE, as that's what KVM will use.
69  */
70 #ifdef PAGE_SIZE
71 #undef PAGE_SIZE
72 #endif
73 #define PAGE_SIZE qemu_real_host_page_size()
74 
75 #ifndef KVM_GUESTDBG_BLOCKIRQ
76 #define KVM_GUESTDBG_BLOCKIRQ 0
77 #endif
78 
79 /* Default num of memslots to be allocated when VM starts */
80 #define  KVM_MEMSLOTS_NR_ALLOC_DEFAULT                      16
81 /* Default max allowed memslots if kernel reported nothing */
82 #define  KVM_MEMSLOTS_NR_MAX_DEFAULT                        32
83 
84 struct KVMParkedVcpu {
85     unsigned long vcpu_id;
86     int kvm_fd;
87     QLIST_ENTRY(KVMParkedVcpu) node;
88 };
89 
90 KVMState *kvm_state;
91 bool kvm_kernel_irqchip;
92 bool kvm_split_irqchip;
93 bool kvm_async_interrupts_allowed;
94 bool kvm_halt_in_kernel_allowed;
95 bool kvm_resamplefds_allowed;
96 bool kvm_msi_via_irqfd_allowed;
97 bool kvm_gsi_routing_allowed;
98 bool kvm_gsi_direct_mapping;
99 bool kvm_allowed;
100 bool kvm_readonly_mem_allowed;
101 bool kvm_vm_attributes_allowed;
102 bool kvm_msi_use_devid;
103 bool kvm_pre_fault_memory_supported;
104 static bool kvm_has_guest_debug;
105 static int kvm_sstep_flags;
106 static bool kvm_immediate_exit;
107 static uint64_t kvm_supported_memory_attributes;
108 static bool kvm_guest_memfd_supported;
109 static hwaddr kvm_max_slot_size = ~0;
110 
111 static const KVMCapabilityInfo kvm_required_capabilites[] = {
112     KVM_CAP_INFO(USER_MEMORY),
113     KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
114     KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS),
115     KVM_CAP_INFO(INTERNAL_ERROR_DATA),
116     KVM_CAP_INFO(IOEVENTFD),
117     KVM_CAP_INFO(IOEVENTFD_ANY_LENGTH),
118     KVM_CAP_LAST_INFO
119 };
120 
121 static NotifierList kvm_irqchip_change_notifiers =
122     NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers);
123 
124 struct KVMResampleFd {
125     int gsi;
126     EventNotifier *resample_event;
127     QLIST_ENTRY(KVMResampleFd) node;
128 };
129 typedef struct KVMResampleFd KVMResampleFd;
130 
131 /*
132  * Only used with split irqchip where we need to do the resample fd
133  * kick for the kernel from userspace.
134  */
135 static QLIST_HEAD(, KVMResampleFd) kvm_resample_fd_list =
136     QLIST_HEAD_INITIALIZER(kvm_resample_fd_list);
137 
138 static QemuMutex kml_slots_lock;
139 
140 #define kvm_slots_lock()    qemu_mutex_lock(&kml_slots_lock)
141 #define kvm_slots_unlock()  qemu_mutex_unlock(&kml_slots_lock)
142 
143 static void kvm_slot_init_dirty_bitmap(KVMSlot *mem);
144 
kvm_resample_fd_remove(int gsi)145 static inline void kvm_resample_fd_remove(int gsi)
146 {
147     KVMResampleFd *rfd;
148 
149     QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
150         if (rfd->gsi == gsi) {
151             QLIST_REMOVE(rfd, node);
152             g_free(rfd);
153             break;
154         }
155     }
156 }
157 
kvm_resample_fd_insert(int gsi,EventNotifier * event)158 static inline void kvm_resample_fd_insert(int gsi, EventNotifier *event)
159 {
160     KVMResampleFd *rfd = g_new0(KVMResampleFd, 1);
161 
162     rfd->gsi = gsi;
163     rfd->resample_event = event;
164 
165     QLIST_INSERT_HEAD(&kvm_resample_fd_list, rfd, node);
166 }
167 
kvm_resample_fd_notify(int gsi)168 void kvm_resample_fd_notify(int gsi)
169 {
170     KVMResampleFd *rfd;
171 
172     QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
173         if (rfd->gsi == gsi) {
174             event_notifier_set(rfd->resample_event);
175             trace_kvm_resample_fd_notify(gsi);
176             return;
177         }
178     }
179 }
180 
181 /**
182  * kvm_slots_grow(): Grow the slots[] array in the KVMMemoryListener
183  *
184  * @kml: The KVMMemoryListener* to grow the slots[] array
185  * @nr_slots_new: The new size of slots[] array
186  *
187  * Returns: True if the array grows larger, false otherwise.
188  */
kvm_slots_grow(KVMMemoryListener * kml,unsigned int nr_slots_new)189 static bool kvm_slots_grow(KVMMemoryListener *kml, unsigned int nr_slots_new)
190 {
191     unsigned int i, cur = kml->nr_slots_allocated;
192     KVMSlot *slots;
193 
194     if (nr_slots_new > kvm_state->nr_slots_max) {
195         nr_slots_new = kvm_state->nr_slots_max;
196     }
197 
198     if (cur >= nr_slots_new) {
199         /* Big enough, no need to grow, or we reached max */
200         return false;
201     }
202 
203     if (cur == 0) {
204         slots = g_new0(KVMSlot, nr_slots_new);
205     } else {
206         assert(kml->slots);
207         slots = g_renew(KVMSlot, kml->slots, nr_slots_new);
208         /*
209          * g_renew() doesn't initialize extended buffers, however kvm
210          * memslots require fields to be zero-initialized. E.g. pointers,
211          * memory_size field, etc.
212          */
213         memset(&slots[cur], 0x0, sizeof(slots[0]) * (nr_slots_new - cur));
214     }
215 
216     for (i = cur; i < nr_slots_new; i++) {
217         slots[i].slot = i;
218     }
219 
220     kml->slots = slots;
221     kml->nr_slots_allocated = nr_slots_new;
222     trace_kvm_slots_grow(cur, nr_slots_new);
223 
224     return true;
225 }
226 
kvm_slots_double(KVMMemoryListener * kml)227 static bool kvm_slots_double(KVMMemoryListener *kml)
228 {
229     return kvm_slots_grow(kml, kml->nr_slots_allocated * 2);
230 }
231 
kvm_get_max_memslots(void)232 unsigned int kvm_get_max_memslots(void)
233 {
234     KVMState *s = KVM_STATE(current_accel());
235 
236     return s->nr_slots_max;
237 }
238 
kvm_get_free_memslots(void)239 unsigned int kvm_get_free_memslots(void)
240 {
241     unsigned int used_slots = 0;
242     KVMState *s = kvm_state;
243     int i;
244 
245     kvm_slots_lock();
246     for (i = 0; i < s->nr_as; i++) {
247         if (!s->as[i].ml) {
248             continue;
249         }
250         used_slots = MAX(used_slots, s->as[i].ml->nr_slots_used);
251     }
252     kvm_slots_unlock();
253 
254     return s->nr_slots_max - used_slots;
255 }
256 
257 /* Called with KVMMemoryListener.slots_lock held */
kvm_get_free_slot(KVMMemoryListener * kml)258 static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
259 {
260     unsigned int n;
261     int i;
262 
263     for (i = 0; i < kml->nr_slots_allocated; i++) {
264         if (kml->slots[i].memory_size == 0) {
265             return &kml->slots[i];
266         }
267     }
268 
269     /*
270      * If no free slots, try to grow first by doubling.  Cache the old size
271      * here to avoid another round of search: if the grow succeeded, it
272      * means slots[] now must have the existing "n" slots occupied,
273      * followed by one or more free slots starting from slots[n].
274      */
275     n = kml->nr_slots_allocated;
276     if (kvm_slots_double(kml)) {
277         return &kml->slots[n];
278     }
279 
280     return NULL;
281 }
282 
283 /* Called with KVMMemoryListener.slots_lock held */
kvm_alloc_slot(KVMMemoryListener * kml)284 static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
285 {
286     KVMSlot *slot = kvm_get_free_slot(kml);
287 
288     if (slot) {
289         return slot;
290     }
291 
292     fprintf(stderr, "%s: no free slot available\n", __func__);
293     abort();
294 }
295 
kvm_lookup_matching_slot(KVMMemoryListener * kml,hwaddr start_addr,hwaddr size)296 static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
297                                          hwaddr start_addr,
298                                          hwaddr size)
299 {
300     int i;
301 
302     for (i = 0; i < kml->nr_slots_allocated; i++) {
303         KVMSlot *mem = &kml->slots[i];
304 
305         if (start_addr == mem->start_addr && size == mem->memory_size) {
306             return mem;
307         }
308     }
309 
310     return NULL;
311 }
312 
313 /*
314  * Calculate and align the start address and the size of the section.
315  * Return the size. If the size is 0, the aligned section is empty.
316  */
kvm_align_section(MemoryRegionSection * section,hwaddr * start)317 static hwaddr kvm_align_section(MemoryRegionSection *section,
318                                 hwaddr *start)
319 {
320     hwaddr size = int128_get64(section->size);
321     hwaddr delta, aligned;
322 
323     /* kvm works in page size chunks, but the function may be called
324        with sub-page size and unaligned start address. Pad the start
325        address to next and truncate size to previous page boundary. */
326     aligned = ROUND_UP(section->offset_within_address_space,
327                        qemu_real_host_page_size());
328     delta = aligned - section->offset_within_address_space;
329     *start = aligned;
330     if (delta > size) {
331         return 0;
332     }
333 
334     return (size - delta) & qemu_real_host_page_mask();
335 }
336 
kvm_physical_memory_addr_from_host(KVMState * s,void * ram,hwaddr * phys_addr)337 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
338                                        hwaddr *phys_addr)
339 {
340     KVMMemoryListener *kml = &s->memory_listener;
341     int i, ret = 0;
342 
343     kvm_slots_lock();
344     for (i = 0; i < kml->nr_slots_allocated; i++) {
345         KVMSlot *mem = &kml->slots[i];
346 
347         if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
348             *phys_addr = mem->start_addr + (ram - mem->ram);
349             ret = 1;
350             break;
351         }
352     }
353     kvm_slots_unlock();
354 
355     return ret;
356 }
357 
kvm_set_user_memory_region(KVMMemoryListener * kml,KVMSlot * slot,bool new)358 static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot, bool new)
359 {
360     KVMState *s = kvm_state;
361     struct kvm_userspace_memory_region2 mem;
362     int ret;
363 
364     mem.slot = slot->slot | (kml->as_id << 16);
365     mem.guest_phys_addr = slot->start_addr;
366     mem.userspace_addr = (unsigned long)slot->ram;
367     mem.flags = slot->flags;
368     mem.guest_memfd = slot->guest_memfd;
369     mem.guest_memfd_offset = slot->guest_memfd_offset;
370 
371     if (slot->memory_size && !new && (mem.flags ^ slot->old_flags) & KVM_MEM_READONLY) {
372         /* Set the slot size to 0 before setting the slot to the desired
373          * value. This is needed based on KVM commit 75d61fbc. */
374         mem.memory_size = 0;
375 
376         if (kvm_guest_memfd_supported) {
377             ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION2, &mem);
378         } else {
379             ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
380         }
381         if (ret < 0) {
382             goto err;
383         }
384     }
385     mem.memory_size = slot->memory_size;
386     if (kvm_guest_memfd_supported) {
387         ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION2, &mem);
388     } else {
389         ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
390     }
391     slot->old_flags = mem.flags;
392 err:
393     trace_kvm_set_user_memory(mem.slot >> 16, (uint16_t)mem.slot, mem.flags,
394                               mem.guest_phys_addr, mem.memory_size,
395                               mem.userspace_addr, mem.guest_memfd,
396                               mem.guest_memfd_offset, ret);
397     if (ret < 0) {
398         if (kvm_guest_memfd_supported) {
399                 error_report("%s: KVM_SET_USER_MEMORY_REGION2 failed, slot=%d,"
400                         " start=0x%" PRIx64 ", size=0x%" PRIx64 ","
401                         " flags=0x%" PRIx32 ", guest_memfd=%" PRId32 ","
402                         " guest_memfd_offset=0x%" PRIx64 ": %s",
403                         __func__, mem.slot, slot->start_addr,
404                         (uint64_t)mem.memory_size, mem.flags,
405                         mem.guest_memfd, (uint64_t)mem.guest_memfd_offset,
406                         strerror(errno));
407         } else {
408                 error_report("%s: KVM_SET_USER_MEMORY_REGION failed, slot=%d,"
409                             " start=0x%" PRIx64 ", size=0x%" PRIx64 ": %s",
410                             __func__, mem.slot, slot->start_addr,
411                             (uint64_t)mem.memory_size, strerror(errno));
412         }
413     }
414     return ret;
415 }
416 
kvm_park_vcpu(CPUState * cpu)417 void kvm_park_vcpu(CPUState *cpu)
418 {
419     struct KVMParkedVcpu *vcpu;
420 
421     trace_kvm_park_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
422 
423     vcpu = g_malloc0(sizeof(*vcpu));
424     vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
425     vcpu->kvm_fd = cpu->kvm_fd;
426     QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
427 }
428 
kvm_unpark_vcpu(KVMState * s,unsigned long vcpu_id)429 int kvm_unpark_vcpu(KVMState *s, unsigned long vcpu_id)
430 {
431     struct KVMParkedVcpu *cpu;
432     int kvm_fd = -ENOENT;
433 
434     QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
435         if (cpu->vcpu_id == vcpu_id) {
436             QLIST_REMOVE(cpu, node);
437             kvm_fd = cpu->kvm_fd;
438             g_free(cpu);
439             break;
440         }
441     }
442 
443     trace_kvm_unpark_vcpu(vcpu_id, kvm_fd > 0 ? "unparked" : "!found parked");
444 
445     return kvm_fd;
446 }
447 
kvm_reset_parked_vcpus(KVMState * s)448 static void kvm_reset_parked_vcpus(KVMState *s)
449 {
450     struct KVMParkedVcpu *cpu;
451 
452     QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
453         kvm_arch_reset_parked_vcpu(cpu->vcpu_id, cpu->kvm_fd);
454     }
455 }
456 
457 /**
458  * kvm_create_vcpu - Gets a parked KVM vCPU or creates a KVM vCPU
459  * @cpu: QOM CPUState object for which KVM vCPU has to be fetched/created.
460  *
461  * @returns: 0 when success, errno (<0) when failed.
462  */
kvm_create_vcpu(CPUState * cpu)463 static int kvm_create_vcpu(CPUState *cpu)
464 {
465     unsigned long vcpu_id = kvm_arch_vcpu_id(cpu);
466     KVMState *s = kvm_state;
467     int kvm_fd;
468 
469     /* check if the KVM vCPU already exist but is parked */
470     kvm_fd = kvm_unpark_vcpu(s, vcpu_id);
471     if (kvm_fd < 0) {
472         /* vCPU not parked: create a new KVM vCPU */
473         kvm_fd = kvm_vm_ioctl(s, KVM_CREATE_VCPU, vcpu_id);
474         if (kvm_fd < 0) {
475             error_report("KVM_CREATE_VCPU IOCTL failed for vCPU %lu", vcpu_id);
476             return kvm_fd;
477         }
478     }
479 
480     cpu->kvm_fd = kvm_fd;
481     cpu->kvm_state = s;
482     if (!s->guest_state_protected) {
483         cpu->vcpu_dirty = true;
484     }
485     cpu->dirty_pages = 0;
486     cpu->throttle_us_per_full = 0;
487 
488     trace_kvm_create_vcpu(cpu->cpu_index, vcpu_id, kvm_fd);
489 
490     return 0;
491 }
492 
kvm_create_and_park_vcpu(CPUState * cpu)493 int kvm_create_and_park_vcpu(CPUState *cpu)
494 {
495     int ret = 0;
496 
497     ret = kvm_create_vcpu(cpu);
498     if (!ret) {
499         kvm_park_vcpu(cpu);
500     }
501 
502     return ret;
503 }
504 
do_kvm_destroy_vcpu(CPUState * cpu)505 static int do_kvm_destroy_vcpu(CPUState *cpu)
506 {
507     KVMState *s = kvm_state;
508     int mmap_size;
509     int ret = 0;
510 
511     trace_kvm_destroy_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
512 
513     ret = kvm_arch_destroy_vcpu(cpu);
514     if (ret < 0) {
515         goto err;
516     }
517 
518     mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
519     if (mmap_size < 0) {
520         ret = mmap_size;
521         trace_kvm_failed_get_vcpu_mmap_size();
522         goto err;
523     }
524 
525     /* If I am the CPU that created coalesced_mmio_ring, then discard it */
526     if (s->coalesced_mmio_ring == (void *)cpu->kvm_run + PAGE_SIZE) {
527         s->coalesced_mmio_ring = NULL;
528     }
529 
530     ret = munmap(cpu->kvm_run, mmap_size);
531     if (ret < 0) {
532         goto err;
533     }
534     cpu->kvm_run = NULL;
535 
536     if (cpu->kvm_dirty_gfns) {
537         ret = munmap(cpu->kvm_dirty_gfns, s->kvm_dirty_ring_bytes);
538         if (ret < 0) {
539             goto err;
540         }
541         cpu->kvm_dirty_gfns = NULL;
542     }
543 
544     kvm_park_vcpu(cpu);
545 err:
546     return ret;
547 }
548 
kvm_destroy_vcpu(CPUState * cpu)549 void kvm_destroy_vcpu(CPUState *cpu)
550 {
551     if (do_kvm_destroy_vcpu(cpu) < 0) {
552         error_report("kvm_destroy_vcpu failed");
553         exit(EXIT_FAILURE);
554     }
555 }
556 
kvm_init_vcpu(CPUState * cpu,Error ** errp)557 int kvm_init_vcpu(CPUState *cpu, Error **errp)
558 {
559     KVMState *s = kvm_state;
560     int mmap_size;
561     int ret;
562 
563     trace_kvm_init_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
564 
565     ret = kvm_arch_pre_create_vcpu(cpu, errp);
566     if (ret < 0) {
567         goto err;
568     }
569 
570     ret = kvm_create_vcpu(cpu);
571     if (ret < 0) {
572         error_setg_errno(errp, -ret,
573                          "kvm_init_vcpu: kvm_create_vcpu failed (%lu)",
574                          kvm_arch_vcpu_id(cpu));
575         goto err;
576     }
577 
578     mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
579     if (mmap_size < 0) {
580         ret = mmap_size;
581         error_setg_errno(errp, -mmap_size,
582                          "kvm_init_vcpu: KVM_GET_VCPU_MMAP_SIZE failed");
583         goto err;
584     }
585 
586     cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
587                         cpu->kvm_fd, 0);
588     if (cpu->kvm_run == MAP_FAILED) {
589         ret = -errno;
590         error_setg_errno(errp, ret,
591                          "kvm_init_vcpu: mmap'ing vcpu state failed (%lu)",
592                          kvm_arch_vcpu_id(cpu));
593         goto err;
594     }
595 
596     if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
597         s->coalesced_mmio_ring =
598             (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
599     }
600 
601     if (s->kvm_dirty_ring_size) {
602         /* Use MAP_SHARED to share pages with the kernel */
603         cpu->kvm_dirty_gfns = mmap(NULL, s->kvm_dirty_ring_bytes,
604                                    PROT_READ | PROT_WRITE, MAP_SHARED,
605                                    cpu->kvm_fd,
606                                    PAGE_SIZE * KVM_DIRTY_LOG_PAGE_OFFSET);
607         if (cpu->kvm_dirty_gfns == MAP_FAILED) {
608             ret = -errno;
609             goto err;
610         }
611     }
612 
613     ret = kvm_arch_init_vcpu(cpu);
614     if (ret < 0) {
615         error_setg_errno(errp, -ret,
616                          "kvm_init_vcpu: kvm_arch_init_vcpu failed (%lu)",
617                          kvm_arch_vcpu_id(cpu));
618     }
619     cpu->kvm_vcpu_stats_fd = kvm_vcpu_ioctl(cpu, KVM_GET_STATS_FD, NULL);
620 
621 err:
622     return ret;
623 }
624 
kvm_close(void)625 void kvm_close(void)
626 {
627     CPUState *cpu;
628 
629     if (!kvm_state || kvm_state->fd == -1) {
630         return;
631     }
632 
633     CPU_FOREACH(cpu) {
634         cpu_remove_sync(cpu);
635         close(cpu->kvm_fd);
636         cpu->kvm_fd = -1;
637         close(cpu->kvm_vcpu_stats_fd);
638         cpu->kvm_vcpu_stats_fd = -1;
639     }
640 
641     if (kvm_state && kvm_state->fd != -1) {
642         close(kvm_state->vmfd);
643         kvm_state->vmfd = -1;
644         close(kvm_state->fd);
645         kvm_state->fd = -1;
646     }
647     kvm_state = NULL;
648 }
649 
650 /*
651  * dirty pages logging control
652  */
653 
kvm_mem_flags(MemoryRegion * mr)654 static int kvm_mem_flags(MemoryRegion *mr)
655 {
656     bool readonly = mr->readonly || memory_region_is_romd(mr);
657     int flags = 0;
658 
659     if (memory_region_get_dirty_log_mask(mr) != 0) {
660         flags |= KVM_MEM_LOG_DIRTY_PAGES;
661     }
662     if (readonly && kvm_readonly_mem_allowed) {
663         flags |= KVM_MEM_READONLY;
664     }
665     if (memory_region_has_guest_memfd(mr)) {
666         assert(kvm_guest_memfd_supported);
667         flags |= KVM_MEM_GUEST_MEMFD;
668     }
669     return flags;
670 }
671 
672 /* Called with KVMMemoryListener.slots_lock held */
kvm_slot_update_flags(KVMMemoryListener * kml,KVMSlot * mem,MemoryRegion * mr)673 static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
674                                  MemoryRegion *mr)
675 {
676     mem->flags = kvm_mem_flags(mr);
677 
678     /* If nothing changed effectively, no need to issue ioctl */
679     if (mem->flags == mem->old_flags) {
680         return 0;
681     }
682 
683     kvm_slot_init_dirty_bitmap(mem);
684     return kvm_set_user_memory_region(kml, mem, false);
685 }
686 
kvm_section_update_flags(KVMMemoryListener * kml,MemoryRegionSection * section)687 static int kvm_section_update_flags(KVMMemoryListener *kml,
688                                     MemoryRegionSection *section)
689 {
690     hwaddr start_addr, size, slot_size;
691     KVMSlot *mem;
692     int ret = 0;
693 
694     size = kvm_align_section(section, &start_addr);
695     if (!size) {
696         return 0;
697     }
698 
699     kvm_slots_lock();
700 
701     while (size && !ret) {
702         slot_size = MIN(kvm_max_slot_size, size);
703         mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
704         if (!mem) {
705             /* We don't have a slot if we want to trap every access. */
706             goto out;
707         }
708 
709         ret = kvm_slot_update_flags(kml, mem, section->mr);
710         start_addr += slot_size;
711         size -= slot_size;
712     }
713 
714 out:
715     kvm_slots_unlock();
716     return ret;
717 }
718 
kvm_log_start(MemoryListener * listener,MemoryRegionSection * section,int old,int new)719 static void kvm_log_start(MemoryListener *listener,
720                           MemoryRegionSection *section,
721                           int old, int new)
722 {
723     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
724     int r;
725 
726     if (old != 0) {
727         return;
728     }
729 
730     r = kvm_section_update_flags(kml, section);
731     if (r < 0) {
732         abort();
733     }
734 }
735 
kvm_log_stop(MemoryListener * listener,MemoryRegionSection * section,int old,int new)736 static void kvm_log_stop(MemoryListener *listener,
737                           MemoryRegionSection *section,
738                           int old, int new)
739 {
740     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
741     int r;
742 
743     if (new != 0) {
744         return;
745     }
746 
747     r = kvm_section_update_flags(kml, section);
748     if (r < 0) {
749         abort();
750     }
751 }
752 
753 /* get kvm's dirty pages bitmap and update qemu's */
kvm_slot_sync_dirty_pages(KVMSlot * slot)754 static void kvm_slot_sync_dirty_pages(KVMSlot *slot)
755 {
756     ram_addr_t start = slot->ram_start_offset;
757     ram_addr_t pages = slot->memory_size / qemu_real_host_page_size();
758 
759     cpu_physical_memory_set_dirty_lebitmap(slot->dirty_bmap, start, pages);
760 }
761 
kvm_slot_reset_dirty_pages(KVMSlot * slot)762 static void kvm_slot_reset_dirty_pages(KVMSlot *slot)
763 {
764     memset(slot->dirty_bmap, 0, slot->dirty_bmap_size);
765 }
766 
767 #define ALIGN(x, y)  (((x)+(y)-1) & ~((y)-1))
768 
769 /* Allocate the dirty bitmap for a slot  */
kvm_slot_init_dirty_bitmap(KVMSlot * mem)770 static void kvm_slot_init_dirty_bitmap(KVMSlot *mem)
771 {
772     if (!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) || mem->dirty_bmap) {
773         return;
774     }
775 
776     /*
777      * XXX bad kernel interface alert
778      * For dirty bitmap, kernel allocates array of size aligned to
779      * bits-per-long.  But for case when the kernel is 64bits and
780      * the userspace is 32bits, userspace can't align to the same
781      * bits-per-long, since sizeof(long) is different between kernel
782      * and user space.  This way, userspace will provide buffer which
783      * may be 4 bytes less than the kernel will use, resulting in
784      * userspace memory corruption (which is not detectable by valgrind
785      * too, in most cases).
786      * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
787      * a hope that sizeof(long) won't become >8 any time soon.
788      *
789      * Note: the granule of kvm dirty log is qemu_real_host_page_size.
790      * And mem->memory_size is aligned to it (otherwise this mem can't
791      * be registered to KVM).
792      */
793     hwaddr bitmap_size = ALIGN(mem->memory_size / qemu_real_host_page_size(),
794                                         /*HOST_LONG_BITS*/ 64) / 8;
795     mem->dirty_bmap = g_malloc0(bitmap_size);
796     mem->dirty_bmap_size = bitmap_size;
797 }
798 
799 /*
800  * Sync dirty bitmap from kernel to KVMSlot.dirty_bmap, return true if
801  * succeeded, false otherwise
802  */
kvm_slot_get_dirty_log(KVMState * s,KVMSlot * slot)803 static bool kvm_slot_get_dirty_log(KVMState *s, KVMSlot *slot)
804 {
805     struct kvm_dirty_log d = {};
806     int ret;
807 
808     d.dirty_bitmap = slot->dirty_bmap;
809     d.slot = slot->slot | (slot->as_id << 16);
810     ret = kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d);
811 
812     if (ret == -ENOENT) {
813         /* kernel does not have dirty bitmap in this slot */
814         ret = 0;
815     }
816     if (ret) {
817         error_report_once("%s: KVM_GET_DIRTY_LOG failed with %d",
818                           __func__, ret);
819     }
820     return ret == 0;
821 }
822 
823 /* Should be with all slots_lock held for the address spaces. */
kvm_dirty_ring_mark_page(KVMState * s,uint32_t as_id,uint32_t slot_id,uint64_t offset)824 static void kvm_dirty_ring_mark_page(KVMState *s, uint32_t as_id,
825                                      uint32_t slot_id, uint64_t offset)
826 {
827     KVMMemoryListener *kml;
828     KVMSlot *mem;
829 
830     if (as_id >= s->nr_as) {
831         return;
832     }
833 
834     kml = s->as[as_id].ml;
835     mem = &kml->slots[slot_id];
836 
837     if (!mem->memory_size || offset >=
838         (mem->memory_size / qemu_real_host_page_size())) {
839         return;
840     }
841 
842     set_bit(offset, mem->dirty_bmap);
843 }
844 
dirty_gfn_is_dirtied(struct kvm_dirty_gfn * gfn)845 static bool dirty_gfn_is_dirtied(struct kvm_dirty_gfn *gfn)
846 {
847     /*
848      * Read the flags before the value.  Pairs with barrier in
849      * KVM's kvm_dirty_ring_push() function.
850      */
851     return qatomic_load_acquire(&gfn->flags) == KVM_DIRTY_GFN_F_DIRTY;
852 }
853 
dirty_gfn_set_collected(struct kvm_dirty_gfn * gfn)854 static void dirty_gfn_set_collected(struct kvm_dirty_gfn *gfn)
855 {
856     /*
857      * Use a store-release so that the CPU that executes KVM_RESET_DIRTY_RINGS
858      * sees the full content of the ring:
859      *
860      * CPU0                     CPU1                         CPU2
861      * ------------------------------------------------------------------------------
862      *                                                       fill gfn0
863      *                                                       store-rel flags for gfn0
864      * load-acq flags for gfn0
865      * store-rel RESET for gfn0
866      *                          ioctl(RESET_RINGS)
867      *                            load-acq flags for gfn0
868      *                            check if flags have RESET
869      *
870      * The synchronization goes from CPU2 to CPU0 to CPU1.
871      */
872     qatomic_store_release(&gfn->flags, KVM_DIRTY_GFN_F_RESET);
873 }
874 
875 /*
876  * Should be with all slots_lock held for the address spaces.  It returns the
877  * dirty page we've collected on this dirty ring.
878  */
kvm_dirty_ring_reap_one(KVMState * s,CPUState * cpu)879 static uint32_t kvm_dirty_ring_reap_one(KVMState *s, CPUState *cpu)
880 {
881     struct kvm_dirty_gfn *dirty_gfns = cpu->kvm_dirty_gfns, *cur;
882     uint32_t ring_size = s->kvm_dirty_ring_size;
883     uint32_t count = 0, fetch = cpu->kvm_fetch_index;
884 
885     /*
886      * It's possible that we race with vcpu creation code where the vcpu is
887      * put onto the vcpus list but not yet initialized the dirty ring
888      * structures.  If so, skip it.
889      */
890     if (!cpu->created) {
891         return 0;
892     }
893 
894     assert(dirty_gfns && ring_size);
895     trace_kvm_dirty_ring_reap_vcpu(cpu->cpu_index);
896 
897     while (true) {
898         cur = &dirty_gfns[fetch % ring_size];
899         if (!dirty_gfn_is_dirtied(cur)) {
900             break;
901         }
902         kvm_dirty_ring_mark_page(s, cur->slot >> 16, cur->slot & 0xffff,
903                                  cur->offset);
904         dirty_gfn_set_collected(cur);
905         trace_kvm_dirty_ring_page(cpu->cpu_index, fetch, cur->offset);
906         fetch++;
907         count++;
908     }
909     cpu->kvm_fetch_index = fetch;
910     cpu->dirty_pages += count;
911 
912     return count;
913 }
914 
915 /* Must be with slots_lock held */
kvm_dirty_ring_reap_locked(KVMState * s,CPUState * cpu)916 static uint64_t kvm_dirty_ring_reap_locked(KVMState *s, CPUState* cpu)
917 {
918     int ret;
919     uint64_t total = 0;
920     int64_t stamp;
921 
922     stamp = get_clock();
923 
924     if (cpu) {
925         total = kvm_dirty_ring_reap_one(s, cpu);
926     } else {
927         CPU_FOREACH(cpu) {
928             total += kvm_dirty_ring_reap_one(s, cpu);
929         }
930     }
931 
932     if (total) {
933         ret = kvm_vm_ioctl(s, KVM_RESET_DIRTY_RINGS);
934         assert(ret == total);
935     }
936 
937     stamp = get_clock() - stamp;
938 
939     if (total) {
940         trace_kvm_dirty_ring_reap(total, stamp / 1000);
941     }
942 
943     return total;
944 }
945 
946 /*
947  * Currently for simplicity, we must hold BQL before calling this.  We can
948  * consider to drop the BQL if we're clear with all the race conditions.
949  */
kvm_dirty_ring_reap(KVMState * s,CPUState * cpu)950 static uint64_t kvm_dirty_ring_reap(KVMState *s, CPUState *cpu)
951 {
952     uint64_t total;
953 
954     /*
955      * We need to lock all kvm slots for all address spaces here,
956      * because:
957      *
958      * (1) We need to mark dirty for dirty bitmaps in multiple slots
959      *     and for tons of pages, so it's better to take the lock here
960      *     once rather than once per page.  And more importantly,
961      *
962      * (2) We must _NOT_ publish dirty bits to the other threads
963      *     (e.g., the migration thread) via the kvm memory slot dirty
964      *     bitmaps before correctly re-protect those dirtied pages.
965      *     Otherwise we can have potential risk of data corruption if
966      *     the page data is read in the other thread before we do
967      *     reset below.
968      */
969     kvm_slots_lock();
970     total = kvm_dirty_ring_reap_locked(s, cpu);
971     kvm_slots_unlock();
972 
973     return total;
974 }
975 
do_kvm_cpu_synchronize_kick(CPUState * cpu,run_on_cpu_data arg)976 static void do_kvm_cpu_synchronize_kick(CPUState *cpu, run_on_cpu_data arg)
977 {
978     /* No need to do anything */
979 }
980 
981 /*
982  * Kick all vcpus out in a synchronized way.  When returned, we
983  * guarantee that every vcpu has been kicked and at least returned to
984  * userspace once.
985  */
kvm_cpu_synchronize_kick_all(void)986 static void kvm_cpu_synchronize_kick_all(void)
987 {
988     CPUState *cpu;
989 
990     CPU_FOREACH(cpu) {
991         run_on_cpu(cpu, do_kvm_cpu_synchronize_kick, RUN_ON_CPU_NULL);
992     }
993 }
994 
995 /*
996  * Flush all the existing dirty pages to the KVM slot buffers.  When
997  * this call returns, we guarantee that all the touched dirty pages
998  * before calling this function have been put into the per-kvmslot
999  * dirty bitmap.
1000  *
1001  * This function must be called with BQL held.
1002  */
kvm_dirty_ring_flush(void)1003 static void kvm_dirty_ring_flush(void)
1004 {
1005     trace_kvm_dirty_ring_flush(0);
1006     /*
1007      * The function needs to be serialized.  Since this function
1008      * should always be with BQL held, serialization is guaranteed.
1009      * However, let's be sure of it.
1010      */
1011     assert(bql_locked());
1012     /*
1013      * First make sure to flush the hardware buffers by kicking all
1014      * vcpus out in a synchronous way.
1015      */
1016     kvm_cpu_synchronize_kick_all();
1017     kvm_dirty_ring_reap(kvm_state, NULL);
1018     trace_kvm_dirty_ring_flush(1);
1019 }
1020 
1021 /**
1022  * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
1023  *
1024  * This function will first try to fetch dirty bitmap from the kernel,
1025  * and then updates qemu's dirty bitmap.
1026  *
1027  * NOTE: caller must be with kml->slots_lock held.
1028  *
1029  * @kml: the KVM memory listener object
1030  * @section: the memory section to sync the dirty bitmap with
1031  */
kvm_physical_sync_dirty_bitmap(KVMMemoryListener * kml,MemoryRegionSection * section)1032 static void kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
1033                                            MemoryRegionSection *section)
1034 {
1035     KVMState *s = kvm_state;
1036     KVMSlot *mem;
1037     hwaddr start_addr, size;
1038     hwaddr slot_size;
1039 
1040     size = kvm_align_section(section, &start_addr);
1041     while (size) {
1042         slot_size = MIN(kvm_max_slot_size, size);
1043         mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
1044         if (!mem) {
1045             /* We don't have a slot if we want to trap every access. */
1046             return;
1047         }
1048         if (kvm_slot_get_dirty_log(s, mem)) {
1049             kvm_slot_sync_dirty_pages(mem);
1050         }
1051         start_addr += slot_size;
1052         size -= slot_size;
1053     }
1054 }
1055 
1056 /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
1057 #define KVM_CLEAR_LOG_SHIFT  6
1058 #define KVM_CLEAR_LOG_ALIGN  (qemu_real_host_page_size() << KVM_CLEAR_LOG_SHIFT)
1059 #define KVM_CLEAR_LOG_MASK   (-KVM_CLEAR_LOG_ALIGN)
1060 
kvm_log_clear_one_slot(KVMSlot * mem,int as_id,uint64_t start,uint64_t size)1061 static int kvm_log_clear_one_slot(KVMSlot *mem, int as_id, uint64_t start,
1062                                   uint64_t size)
1063 {
1064     KVMState *s = kvm_state;
1065     uint64_t end, bmap_start, start_delta, bmap_npages;
1066     struct kvm_clear_dirty_log d;
1067     unsigned long *bmap_clear = NULL, psize = qemu_real_host_page_size();
1068     int ret;
1069 
1070     /*
1071      * We need to extend either the start or the size or both to
1072      * satisfy the KVM interface requirement.  Firstly, do the start
1073      * page alignment on 64 host pages
1074      */
1075     bmap_start = start & KVM_CLEAR_LOG_MASK;
1076     start_delta = start - bmap_start;
1077     bmap_start /= psize;
1078 
1079     /*
1080      * The kernel interface has restriction on the size too, that either:
1081      *
1082      * (1) the size is 64 host pages aligned (just like the start), or
1083      * (2) the size fills up until the end of the KVM memslot.
1084      */
1085     bmap_npages = DIV_ROUND_UP(size + start_delta, KVM_CLEAR_LOG_ALIGN)
1086         << KVM_CLEAR_LOG_SHIFT;
1087     end = mem->memory_size / psize;
1088     if (bmap_npages > end - bmap_start) {
1089         bmap_npages = end - bmap_start;
1090     }
1091     start_delta /= psize;
1092 
1093     /*
1094      * Prepare the bitmap to clear dirty bits.  Here we must guarantee
1095      * that we won't clear any unknown dirty bits otherwise we might
1096      * accidentally clear some set bits which are not yet synced from
1097      * the kernel into QEMU's bitmap, then we'll lose track of the
1098      * guest modifications upon those pages (which can directly lead
1099      * to guest data loss or panic after migration).
1100      *
1101      * Layout of the KVMSlot.dirty_bmap:
1102      *
1103      *                   |<-------- bmap_npages -----------..>|
1104      *                                                     [1]
1105      *                     start_delta         size
1106      *  |----------------|-------------|------------------|------------|
1107      *  ^                ^             ^                               ^
1108      *  |                |             |                               |
1109      * start          bmap_start     (start)                         end
1110      * of memslot                                             of memslot
1111      *
1112      * [1] bmap_npages can be aligned to either 64 pages or the end of slot
1113      */
1114 
1115     assert(bmap_start % BITS_PER_LONG == 0);
1116     /* We should never do log_clear before log_sync */
1117     assert(mem->dirty_bmap);
1118     if (start_delta || bmap_npages - size / psize) {
1119         /* Slow path - we need to manipulate a temp bitmap */
1120         bmap_clear = bitmap_new(bmap_npages);
1121         bitmap_copy_with_src_offset(bmap_clear, mem->dirty_bmap,
1122                                     bmap_start, start_delta + size / psize);
1123         /*
1124          * We need to fill the holes at start because that was not
1125          * specified by the caller and we extended the bitmap only for
1126          * 64 pages alignment
1127          */
1128         bitmap_clear(bmap_clear, 0, start_delta);
1129         d.dirty_bitmap = bmap_clear;
1130     } else {
1131         /*
1132          * Fast path - both start and size align well with BITS_PER_LONG
1133          * (or the end of memory slot)
1134          */
1135         d.dirty_bitmap = mem->dirty_bmap + BIT_WORD(bmap_start);
1136     }
1137 
1138     d.first_page = bmap_start;
1139     /* It should never overflow.  If it happens, say something */
1140     assert(bmap_npages <= UINT32_MAX);
1141     d.num_pages = bmap_npages;
1142     d.slot = mem->slot | (as_id << 16);
1143 
1144     ret = kvm_vm_ioctl(s, KVM_CLEAR_DIRTY_LOG, &d);
1145     if (ret < 0 && ret != -ENOENT) {
1146         error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
1147                      "start=0x%"PRIx64", size=0x%"PRIx32", errno=%d",
1148                      __func__, d.slot, (uint64_t)d.first_page,
1149                      (uint32_t)d.num_pages, ret);
1150     } else {
1151         ret = 0;
1152         trace_kvm_clear_dirty_log(d.slot, d.first_page, d.num_pages);
1153     }
1154 
1155     /*
1156      * After we have updated the remote dirty bitmap, we update the
1157      * cached bitmap as well for the memslot, then if another user
1158      * clears the same region we know we shouldn't clear it again on
1159      * the remote otherwise it's data loss as well.
1160      */
1161     bitmap_clear(mem->dirty_bmap, bmap_start + start_delta,
1162                  size / psize);
1163     /* This handles the NULL case well */
1164     g_free(bmap_clear);
1165     return ret;
1166 }
1167 
1168 
1169 /**
1170  * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
1171  *
1172  * NOTE: this will be a no-op if we haven't enabled manual dirty log
1173  * protection in the host kernel because in that case this operation
1174  * will be done within log_sync().
1175  *
1176  * @kml:     the kvm memory listener
1177  * @section: the memory range to clear dirty bitmap
1178  */
kvm_physical_log_clear(KVMMemoryListener * kml,MemoryRegionSection * section)1179 static int kvm_physical_log_clear(KVMMemoryListener *kml,
1180                                   MemoryRegionSection *section)
1181 {
1182     KVMState *s = kvm_state;
1183     uint64_t start, size, offset, count;
1184     KVMSlot *mem;
1185     int ret = 0, i;
1186 
1187     if (!s->manual_dirty_log_protect) {
1188         /* No need to do explicit clear */
1189         return ret;
1190     }
1191 
1192     start = section->offset_within_address_space;
1193     size = int128_get64(section->size);
1194 
1195     if (!size) {
1196         /* Nothing more we can do... */
1197         return ret;
1198     }
1199 
1200     kvm_slots_lock();
1201 
1202     for (i = 0; i < kml->nr_slots_allocated; i++) {
1203         mem = &kml->slots[i];
1204         /* Discard slots that are empty or do not overlap the section */
1205         if (!mem->memory_size ||
1206             mem->start_addr > start + size - 1 ||
1207             start > mem->start_addr + mem->memory_size - 1) {
1208             continue;
1209         }
1210 
1211         if (start >= mem->start_addr) {
1212             /* The slot starts before section or is aligned to it.  */
1213             offset = start - mem->start_addr;
1214             count = MIN(mem->memory_size - offset, size);
1215         } else {
1216             /* The slot starts after section.  */
1217             offset = 0;
1218             count = MIN(mem->memory_size, size - (mem->start_addr - start));
1219         }
1220         ret = kvm_log_clear_one_slot(mem, kml->as_id, offset, count);
1221         if (ret < 0) {
1222             break;
1223         }
1224     }
1225 
1226     kvm_slots_unlock();
1227 
1228     return ret;
1229 }
1230 
kvm_coalesce_mmio_region(MemoryListener * listener,MemoryRegionSection * secion,hwaddr start,hwaddr size)1231 static void kvm_coalesce_mmio_region(MemoryListener *listener,
1232                                      MemoryRegionSection *secion,
1233                                      hwaddr start, hwaddr size)
1234 {
1235     KVMState *s = kvm_state;
1236 
1237     if (s->coalesced_mmio) {
1238         struct kvm_coalesced_mmio_zone zone;
1239 
1240         zone.addr = start;
1241         zone.size = size;
1242         zone.pad = 0;
1243 
1244         (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
1245     }
1246 }
1247 
kvm_uncoalesce_mmio_region(MemoryListener * listener,MemoryRegionSection * secion,hwaddr start,hwaddr size)1248 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
1249                                        MemoryRegionSection *secion,
1250                                        hwaddr start, hwaddr size)
1251 {
1252     KVMState *s = kvm_state;
1253 
1254     if (s->coalesced_mmio) {
1255         struct kvm_coalesced_mmio_zone zone;
1256 
1257         zone.addr = start;
1258         zone.size = size;
1259         zone.pad = 0;
1260 
1261         (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
1262     }
1263 }
1264 
kvm_coalesce_pio_add(MemoryListener * listener,MemoryRegionSection * section,hwaddr start,hwaddr size)1265 static void kvm_coalesce_pio_add(MemoryListener *listener,
1266                                 MemoryRegionSection *section,
1267                                 hwaddr start, hwaddr size)
1268 {
1269     KVMState *s = kvm_state;
1270 
1271     if (s->coalesced_pio) {
1272         struct kvm_coalesced_mmio_zone zone;
1273 
1274         zone.addr = start;
1275         zone.size = size;
1276         zone.pio = 1;
1277 
1278         (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
1279     }
1280 }
1281 
kvm_coalesce_pio_del(MemoryListener * listener,MemoryRegionSection * section,hwaddr start,hwaddr size)1282 static void kvm_coalesce_pio_del(MemoryListener *listener,
1283                                 MemoryRegionSection *section,
1284                                 hwaddr start, hwaddr size)
1285 {
1286     KVMState *s = kvm_state;
1287 
1288     if (s->coalesced_pio) {
1289         struct kvm_coalesced_mmio_zone zone;
1290 
1291         zone.addr = start;
1292         zone.size = size;
1293         zone.pio = 1;
1294 
1295         (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
1296      }
1297 }
1298 
kvm_check_extension(KVMState * s,unsigned int extension)1299 int kvm_check_extension(KVMState *s, unsigned int extension)
1300 {
1301     int ret;
1302 
1303     ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
1304     if (ret < 0) {
1305         ret = 0;
1306     }
1307 
1308     return ret;
1309 }
1310 
kvm_vm_check_extension(KVMState * s,unsigned int extension)1311 int kvm_vm_check_extension(KVMState *s, unsigned int extension)
1312 {
1313     int ret;
1314 
1315     ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
1316     if (ret < 0) {
1317         /* VM wide version not implemented, use global one instead */
1318         ret = kvm_check_extension(s, extension);
1319     }
1320 
1321     return ret;
1322 }
1323 
1324 /*
1325  * We track the poisoned pages to be able to:
1326  * - replace them on VM reset
1327  * - block a migration for a VM with a poisoned page
1328  */
1329 typedef struct HWPoisonPage {
1330     ram_addr_t ram_addr;
1331     QLIST_ENTRY(HWPoisonPage) list;
1332 } HWPoisonPage;
1333 
1334 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
1335     QLIST_HEAD_INITIALIZER(hwpoison_page_list);
1336 
kvm_unpoison_all(void * param)1337 static void kvm_unpoison_all(void *param)
1338 {
1339     HWPoisonPage *page, *next_page;
1340 
1341     QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
1342         QLIST_REMOVE(page, list);
1343         qemu_ram_remap(page->ram_addr);
1344         g_free(page);
1345     }
1346 }
1347 
kvm_hwpoison_page_add(ram_addr_t ram_addr)1348 void kvm_hwpoison_page_add(ram_addr_t ram_addr)
1349 {
1350     HWPoisonPage *page;
1351 
1352     QLIST_FOREACH(page, &hwpoison_page_list, list) {
1353         if (page->ram_addr == ram_addr) {
1354             return;
1355         }
1356     }
1357     page = g_new(HWPoisonPage, 1);
1358     page->ram_addr = ram_addr;
1359     QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
1360 }
1361 
kvm_hwpoisoned_mem(void)1362 bool kvm_hwpoisoned_mem(void)
1363 {
1364     return !QLIST_EMPTY(&hwpoison_page_list);
1365 }
1366 
adjust_ioeventfd_endianness(uint32_t val,uint32_t size)1367 static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
1368 {
1369     if (target_needs_bswap()) {
1370         /*
1371          * The kernel expects ioeventfd values in HOST_BIG_ENDIAN
1372          * endianness, but the memory core hands them in target endianness.
1373          * For example, PPC is always treated as big-endian even if running
1374          * on KVM and on PPC64LE.  Correct here, swapping back.
1375          */
1376         switch (size) {
1377         case 2:
1378             val = bswap16(val);
1379             break;
1380         case 4:
1381             val = bswap32(val);
1382             break;
1383         }
1384     }
1385     return val;
1386 }
1387 
kvm_set_ioeventfd_mmio(int fd,hwaddr addr,uint32_t val,bool assign,uint32_t size,bool datamatch)1388 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
1389                                   bool assign, uint32_t size, bool datamatch)
1390 {
1391     int ret;
1392     struct kvm_ioeventfd iofd = {
1393         .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
1394         .addr = addr,
1395         .len = size,
1396         .flags = 0,
1397         .fd = fd,
1398     };
1399 
1400     trace_kvm_set_ioeventfd_mmio(fd, (uint64_t)addr, val, assign, size,
1401                                  datamatch);
1402     if (!kvm_enabled()) {
1403         return -ENOSYS;
1404     }
1405 
1406     if (datamatch) {
1407         iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
1408     }
1409     if (!assign) {
1410         iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1411     }
1412 
1413     ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
1414 
1415     if (ret < 0) {
1416         return -errno;
1417     }
1418 
1419     return 0;
1420 }
1421 
kvm_set_ioeventfd_pio(int fd,uint16_t addr,uint16_t val,bool assign,uint32_t size,bool datamatch)1422 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
1423                                  bool assign, uint32_t size, bool datamatch)
1424 {
1425     struct kvm_ioeventfd kick = {
1426         .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
1427         .addr = addr,
1428         .flags = KVM_IOEVENTFD_FLAG_PIO,
1429         .len = size,
1430         .fd = fd,
1431     };
1432     int r;
1433     trace_kvm_set_ioeventfd_pio(fd, addr, val, assign, size, datamatch);
1434     if (!kvm_enabled()) {
1435         return -ENOSYS;
1436     }
1437     if (datamatch) {
1438         kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
1439     }
1440     if (!assign) {
1441         kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1442     }
1443     r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
1444     if (r < 0) {
1445         return r;
1446     }
1447     return 0;
1448 }
1449 
1450 
1451 static const KVMCapabilityInfo *
kvm_check_extension_list(KVMState * s,const KVMCapabilityInfo * list)1452 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
1453 {
1454     while (list->name) {
1455         if (!kvm_check_extension(s, list->value)) {
1456             return list;
1457         }
1458         list++;
1459     }
1460     return NULL;
1461 }
1462 
kvm_set_max_memslot_size(hwaddr max_slot_size)1463 void kvm_set_max_memslot_size(hwaddr max_slot_size)
1464 {
1465     g_assert(
1466         ROUND_UP(max_slot_size, qemu_real_host_page_size()) == max_slot_size
1467     );
1468     kvm_max_slot_size = max_slot_size;
1469 }
1470 
kvm_set_memory_attributes(hwaddr start,uint64_t size,uint64_t attr)1471 static int kvm_set_memory_attributes(hwaddr start, uint64_t size, uint64_t attr)
1472 {
1473     struct kvm_memory_attributes attrs;
1474     int r;
1475 
1476     assert((attr & kvm_supported_memory_attributes) == attr);
1477     attrs.attributes = attr;
1478     attrs.address = start;
1479     attrs.size = size;
1480     attrs.flags = 0;
1481 
1482     r = kvm_vm_ioctl(kvm_state, KVM_SET_MEMORY_ATTRIBUTES, &attrs);
1483     if (r) {
1484         error_report("failed to set memory (0x%" HWADDR_PRIx "+0x%" PRIx64 ") "
1485                      "with attr 0x%" PRIx64 " error '%s'",
1486                      start, size, attr, strerror(errno));
1487     }
1488     return r;
1489 }
1490 
kvm_set_memory_attributes_private(hwaddr start,uint64_t size)1491 int kvm_set_memory_attributes_private(hwaddr start, uint64_t size)
1492 {
1493     return kvm_set_memory_attributes(start, size, KVM_MEMORY_ATTRIBUTE_PRIVATE);
1494 }
1495 
kvm_set_memory_attributes_shared(hwaddr start,uint64_t size)1496 int kvm_set_memory_attributes_shared(hwaddr start, uint64_t size)
1497 {
1498     return kvm_set_memory_attributes(start, size, 0);
1499 }
1500 
1501 /* Called with KVMMemoryListener.slots_lock held */
kvm_set_phys_mem(KVMMemoryListener * kml,MemoryRegionSection * section,bool add)1502 static void kvm_set_phys_mem(KVMMemoryListener *kml,
1503                              MemoryRegionSection *section, bool add)
1504 {
1505     KVMSlot *mem;
1506     int err;
1507     MemoryRegion *mr = section->mr;
1508     bool writable = !mr->readonly && !mr->rom_device;
1509     hwaddr start_addr, size, slot_size, mr_offset;
1510     ram_addr_t ram_start_offset;
1511     void *ram;
1512 
1513     if (!memory_region_is_ram(mr)) {
1514         if (writable || !kvm_readonly_mem_allowed) {
1515             return;
1516         } else if (!mr->romd_mode) {
1517             /* If the memory device is not in romd_mode, then we actually want
1518              * to remove the kvm memory slot so all accesses will trap. */
1519             add = false;
1520         }
1521     }
1522 
1523     size = kvm_align_section(section, &start_addr);
1524     if (!size) {
1525         return;
1526     }
1527 
1528     /* The offset of the kvmslot within the memory region */
1529     mr_offset = section->offset_within_region + start_addr -
1530         section->offset_within_address_space;
1531 
1532     /* use aligned delta to align the ram address and offset */
1533     ram = memory_region_get_ram_ptr(mr) + mr_offset;
1534     ram_start_offset = memory_region_get_ram_addr(mr) + mr_offset;
1535 
1536     if (!add) {
1537         do {
1538             slot_size = MIN(kvm_max_slot_size, size);
1539             mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
1540             if (!mem) {
1541                 return;
1542             }
1543             if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1544                 /*
1545                  * NOTE: We should be aware of the fact that here we're only
1546                  * doing a best effort to sync dirty bits.  No matter whether
1547                  * we're using dirty log or dirty ring, we ignored two facts:
1548                  *
1549                  * (1) dirty bits can reside in hardware buffers (PML)
1550                  *
1551                  * (2) after we collected dirty bits here, pages can be dirtied
1552                  * again before we do the final KVM_SET_USER_MEMORY_REGION to
1553                  * remove the slot.
1554                  *
1555                  * Not easy.  Let's cross the fingers until it's fixed.
1556                  */
1557                 if (kvm_state->kvm_dirty_ring_size) {
1558                     kvm_dirty_ring_reap_locked(kvm_state, NULL);
1559                     if (kvm_state->kvm_dirty_ring_with_bitmap) {
1560                         kvm_slot_sync_dirty_pages(mem);
1561                         kvm_slot_get_dirty_log(kvm_state, mem);
1562                     }
1563                 } else {
1564                     kvm_slot_get_dirty_log(kvm_state, mem);
1565                 }
1566                 kvm_slot_sync_dirty_pages(mem);
1567             }
1568 
1569             /* unregister the slot */
1570             g_free(mem->dirty_bmap);
1571             mem->dirty_bmap = NULL;
1572             mem->memory_size = 0;
1573             mem->flags = 0;
1574             err = kvm_set_user_memory_region(kml, mem, false);
1575             if (err) {
1576                 fprintf(stderr, "%s: error unregistering slot: %s\n",
1577                         __func__, strerror(-err));
1578                 abort();
1579             }
1580             start_addr += slot_size;
1581             size -= slot_size;
1582             kml->nr_slots_used--;
1583         } while (size);
1584         return;
1585     }
1586 
1587     /* register the new slot */
1588     do {
1589         slot_size = MIN(kvm_max_slot_size, size);
1590         mem = kvm_alloc_slot(kml);
1591         mem->as_id = kml->as_id;
1592         mem->memory_size = slot_size;
1593         mem->start_addr = start_addr;
1594         mem->ram_start_offset = ram_start_offset;
1595         mem->ram = ram;
1596         mem->flags = kvm_mem_flags(mr);
1597         mem->guest_memfd = mr->ram_block->guest_memfd;
1598         mem->guest_memfd_offset = (uint8_t*)ram - mr->ram_block->host;
1599 
1600         kvm_slot_init_dirty_bitmap(mem);
1601         err = kvm_set_user_memory_region(kml, mem, true);
1602         if (err) {
1603             fprintf(stderr, "%s: error registering slot: %s\n", __func__,
1604                     strerror(-err));
1605             abort();
1606         }
1607 
1608         if (memory_region_has_guest_memfd(mr)) {
1609             err = kvm_set_memory_attributes_private(start_addr, slot_size);
1610             if (err) {
1611                 error_report("%s: failed to set memory attribute private: %s",
1612                              __func__, strerror(-err));
1613                 exit(1);
1614             }
1615         }
1616 
1617         start_addr += slot_size;
1618         ram_start_offset += slot_size;
1619         ram += slot_size;
1620         size -= slot_size;
1621         kml->nr_slots_used++;
1622     } while (size);
1623 }
1624 
kvm_dirty_ring_reaper_thread(void * data)1625 static void *kvm_dirty_ring_reaper_thread(void *data)
1626 {
1627     KVMState *s = data;
1628     struct KVMDirtyRingReaper *r = &s->reaper;
1629 
1630     rcu_register_thread();
1631 
1632     trace_kvm_dirty_ring_reaper("init");
1633 
1634     while (true) {
1635         r->reaper_state = KVM_DIRTY_RING_REAPER_WAIT;
1636         trace_kvm_dirty_ring_reaper("wait");
1637         /*
1638          * TODO: provide a smarter timeout rather than a constant?
1639          */
1640         sleep(1);
1641 
1642         /* keep sleeping so that dirtylimit not be interfered by reaper */
1643         if (dirtylimit_in_service()) {
1644             continue;
1645         }
1646 
1647         trace_kvm_dirty_ring_reaper("wakeup");
1648         r->reaper_state = KVM_DIRTY_RING_REAPER_REAPING;
1649 
1650         bql_lock();
1651         kvm_dirty_ring_reap(s, NULL);
1652         bql_unlock();
1653 
1654         r->reaper_iteration++;
1655     }
1656 
1657     g_assert_not_reached();
1658 }
1659 
kvm_dirty_ring_reaper_init(KVMState * s)1660 static void kvm_dirty_ring_reaper_init(KVMState *s)
1661 {
1662     struct KVMDirtyRingReaper *r = &s->reaper;
1663 
1664     qemu_thread_create(&r->reaper_thr, "kvm-reaper",
1665                        kvm_dirty_ring_reaper_thread,
1666                        s, QEMU_THREAD_JOINABLE);
1667 }
1668 
kvm_dirty_ring_init(KVMState * s)1669 static int kvm_dirty_ring_init(KVMState *s)
1670 {
1671     uint32_t ring_size = s->kvm_dirty_ring_size;
1672     uint64_t ring_bytes = ring_size * sizeof(struct kvm_dirty_gfn);
1673     unsigned int capability = KVM_CAP_DIRTY_LOG_RING;
1674     int ret;
1675 
1676     s->kvm_dirty_ring_size = 0;
1677     s->kvm_dirty_ring_bytes = 0;
1678 
1679     /* Bail if the dirty ring size isn't specified */
1680     if (!ring_size) {
1681         return 0;
1682     }
1683 
1684     /*
1685      * Read the max supported pages. Fall back to dirty logging mode
1686      * if the dirty ring isn't supported.
1687      */
1688     ret = kvm_vm_check_extension(s, capability);
1689     if (ret <= 0) {
1690         capability = KVM_CAP_DIRTY_LOG_RING_ACQ_REL;
1691         ret = kvm_vm_check_extension(s, capability);
1692     }
1693 
1694     if (ret <= 0) {
1695         warn_report("KVM dirty ring not available, using bitmap method");
1696         return 0;
1697     }
1698 
1699     if (ring_bytes > ret) {
1700         error_report("KVM dirty ring size %" PRIu32 " too big "
1701                      "(maximum is %ld).  Please use a smaller value.",
1702                      ring_size, (long)ret / sizeof(struct kvm_dirty_gfn));
1703         return -EINVAL;
1704     }
1705 
1706     ret = kvm_vm_enable_cap(s, capability, 0, ring_bytes);
1707     if (ret) {
1708         error_report("Enabling of KVM dirty ring failed: %s. "
1709                      "Suggested minimum value is 1024.", strerror(-ret));
1710         return -EIO;
1711     }
1712 
1713     /* Enable the backup bitmap if it is supported */
1714     ret = kvm_vm_check_extension(s, KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP);
1715     if (ret > 0) {
1716         ret = kvm_vm_enable_cap(s, KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP, 0);
1717         if (ret) {
1718             error_report("Enabling of KVM dirty ring's backup bitmap failed: "
1719                          "%s. ", strerror(-ret));
1720             return -EIO;
1721         }
1722 
1723         s->kvm_dirty_ring_with_bitmap = true;
1724     }
1725 
1726     s->kvm_dirty_ring_size = ring_size;
1727     s->kvm_dirty_ring_bytes = ring_bytes;
1728 
1729     return 0;
1730 }
1731 
kvm_region_add(MemoryListener * listener,MemoryRegionSection * section)1732 static void kvm_region_add(MemoryListener *listener,
1733                            MemoryRegionSection *section)
1734 {
1735     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1736     KVMMemoryUpdate *update;
1737 
1738     update = g_new0(KVMMemoryUpdate, 1);
1739     update->section = *section;
1740 
1741     QSIMPLEQ_INSERT_TAIL(&kml->transaction_add, update, next);
1742 }
1743 
kvm_region_del(MemoryListener * listener,MemoryRegionSection * section)1744 static void kvm_region_del(MemoryListener *listener,
1745                            MemoryRegionSection *section)
1746 {
1747     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1748     KVMMemoryUpdate *update;
1749 
1750     update = g_new0(KVMMemoryUpdate, 1);
1751     update->section = *section;
1752 
1753     QSIMPLEQ_INSERT_TAIL(&kml->transaction_del, update, next);
1754 }
1755 
kvm_region_commit(MemoryListener * listener)1756 static void kvm_region_commit(MemoryListener *listener)
1757 {
1758     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener,
1759                                           listener);
1760     KVMMemoryUpdate *u1, *u2;
1761     bool need_inhibit = false;
1762 
1763     if (QSIMPLEQ_EMPTY(&kml->transaction_add) &&
1764         QSIMPLEQ_EMPTY(&kml->transaction_del)) {
1765         return;
1766     }
1767 
1768     /*
1769      * We have to be careful when regions to add overlap with ranges to remove.
1770      * We have to simulate atomic KVM memslot updates by making sure no ioctl()
1771      * is currently active.
1772      *
1773      * The lists are order by addresses, so it's easy to find overlaps.
1774      */
1775     u1 = QSIMPLEQ_FIRST(&kml->transaction_del);
1776     u2 = QSIMPLEQ_FIRST(&kml->transaction_add);
1777     while (u1 && u2) {
1778         Range r1, r2;
1779 
1780         range_init_nofail(&r1, u1->section.offset_within_address_space,
1781                           int128_get64(u1->section.size));
1782         range_init_nofail(&r2, u2->section.offset_within_address_space,
1783                           int128_get64(u2->section.size));
1784 
1785         if (range_overlaps_range(&r1, &r2)) {
1786             need_inhibit = true;
1787             break;
1788         }
1789         if (range_lob(&r1) < range_lob(&r2)) {
1790             u1 = QSIMPLEQ_NEXT(u1, next);
1791         } else {
1792             u2 = QSIMPLEQ_NEXT(u2, next);
1793         }
1794     }
1795 
1796     kvm_slots_lock();
1797     if (need_inhibit) {
1798         accel_ioctl_inhibit_begin();
1799     }
1800 
1801     /* Remove all memslots before adding the new ones. */
1802     while (!QSIMPLEQ_EMPTY(&kml->transaction_del)) {
1803         u1 = QSIMPLEQ_FIRST(&kml->transaction_del);
1804         QSIMPLEQ_REMOVE_HEAD(&kml->transaction_del, next);
1805 
1806         kvm_set_phys_mem(kml, &u1->section, false);
1807         memory_region_unref(u1->section.mr);
1808 
1809         g_free(u1);
1810     }
1811     while (!QSIMPLEQ_EMPTY(&kml->transaction_add)) {
1812         u1 = QSIMPLEQ_FIRST(&kml->transaction_add);
1813         QSIMPLEQ_REMOVE_HEAD(&kml->transaction_add, next);
1814 
1815         memory_region_ref(u1->section.mr);
1816         kvm_set_phys_mem(kml, &u1->section, true);
1817 
1818         g_free(u1);
1819     }
1820 
1821     if (need_inhibit) {
1822         accel_ioctl_inhibit_end();
1823     }
1824     kvm_slots_unlock();
1825 }
1826 
kvm_log_sync(MemoryListener * listener,MemoryRegionSection * section)1827 static void kvm_log_sync(MemoryListener *listener,
1828                          MemoryRegionSection *section)
1829 {
1830     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1831 
1832     kvm_slots_lock();
1833     kvm_physical_sync_dirty_bitmap(kml, section);
1834     kvm_slots_unlock();
1835 }
1836 
kvm_log_sync_global(MemoryListener * l,bool last_stage)1837 static void kvm_log_sync_global(MemoryListener *l, bool last_stage)
1838 {
1839     KVMMemoryListener *kml = container_of(l, KVMMemoryListener, listener);
1840     KVMState *s = kvm_state;
1841     KVMSlot *mem;
1842     int i;
1843 
1844     /* Flush all kernel dirty addresses into KVMSlot dirty bitmap */
1845     kvm_dirty_ring_flush();
1846 
1847     kvm_slots_lock();
1848     for (i = 0; i < kml->nr_slots_allocated; i++) {
1849         mem = &kml->slots[i];
1850         if (mem->memory_size && mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1851             kvm_slot_sync_dirty_pages(mem);
1852 
1853             if (s->kvm_dirty_ring_with_bitmap && last_stage &&
1854                 kvm_slot_get_dirty_log(s, mem)) {
1855                 kvm_slot_sync_dirty_pages(mem);
1856             }
1857 
1858             /*
1859              * This is not needed by KVM_GET_DIRTY_LOG because the
1860              * ioctl will unconditionally overwrite the whole region.
1861              * However kvm dirty ring has no such side effect.
1862              */
1863             kvm_slot_reset_dirty_pages(mem);
1864         }
1865     }
1866     kvm_slots_unlock();
1867 }
1868 
kvm_log_clear(MemoryListener * listener,MemoryRegionSection * section)1869 static void kvm_log_clear(MemoryListener *listener,
1870                           MemoryRegionSection *section)
1871 {
1872     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1873     int r;
1874 
1875     r = kvm_physical_log_clear(kml, section);
1876     if (r < 0) {
1877         error_report_once("%s: kvm log clear failed: mr=%s "
1878                           "offset=%"HWADDR_PRIx" size=%"PRIx64, __func__,
1879                           section->mr->name, section->offset_within_region,
1880                           int128_get64(section->size));
1881         abort();
1882     }
1883 }
1884 
kvm_mem_ioeventfd_add(MemoryListener * listener,MemoryRegionSection * section,bool match_data,uint64_t data,EventNotifier * e)1885 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
1886                                   MemoryRegionSection *section,
1887                                   bool match_data, uint64_t data,
1888                                   EventNotifier *e)
1889 {
1890     int fd = event_notifier_get_fd(e);
1891     int r;
1892 
1893     r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
1894                                data, true, int128_get64(section->size),
1895                                match_data);
1896     if (r < 0) {
1897         fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1898                 __func__, strerror(-r), -r);
1899         abort();
1900     }
1901 }
1902 
kvm_mem_ioeventfd_del(MemoryListener * listener,MemoryRegionSection * section,bool match_data,uint64_t data,EventNotifier * e)1903 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
1904                                   MemoryRegionSection *section,
1905                                   bool match_data, uint64_t data,
1906                                   EventNotifier *e)
1907 {
1908     int fd = event_notifier_get_fd(e);
1909     int r;
1910 
1911     r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
1912                                data, false, int128_get64(section->size),
1913                                match_data);
1914     if (r < 0) {
1915         fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1916                 __func__, strerror(-r), -r);
1917         abort();
1918     }
1919 }
1920 
kvm_io_ioeventfd_add(MemoryListener * listener,MemoryRegionSection * section,bool match_data,uint64_t data,EventNotifier * e)1921 static void kvm_io_ioeventfd_add(MemoryListener *listener,
1922                                  MemoryRegionSection *section,
1923                                  bool match_data, uint64_t data,
1924                                  EventNotifier *e)
1925 {
1926     int fd = event_notifier_get_fd(e);
1927     int r;
1928 
1929     r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
1930                               data, true, int128_get64(section->size),
1931                               match_data);
1932     if (r < 0) {
1933         fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1934                 __func__, strerror(-r), -r);
1935         abort();
1936     }
1937 }
1938 
kvm_io_ioeventfd_del(MemoryListener * listener,MemoryRegionSection * section,bool match_data,uint64_t data,EventNotifier * e)1939 static void kvm_io_ioeventfd_del(MemoryListener *listener,
1940                                  MemoryRegionSection *section,
1941                                  bool match_data, uint64_t data,
1942                                  EventNotifier *e)
1943 
1944 {
1945     int fd = event_notifier_get_fd(e);
1946     int r;
1947 
1948     r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
1949                               data, false, int128_get64(section->size),
1950                               match_data);
1951     if (r < 0) {
1952         fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1953                 __func__, strerror(-r), -r);
1954         abort();
1955     }
1956 }
1957 
kvm_memory_listener_register(KVMState * s,KVMMemoryListener * kml,AddressSpace * as,int as_id,const char * name)1958 void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
1959                                   AddressSpace *as, int as_id, const char *name)
1960 {
1961     int i;
1962 
1963     kml->as_id = as_id;
1964 
1965     kvm_slots_grow(kml, KVM_MEMSLOTS_NR_ALLOC_DEFAULT);
1966 
1967     QSIMPLEQ_INIT(&kml->transaction_add);
1968     QSIMPLEQ_INIT(&kml->transaction_del);
1969 
1970     kml->listener.region_add = kvm_region_add;
1971     kml->listener.region_del = kvm_region_del;
1972     kml->listener.commit = kvm_region_commit;
1973     kml->listener.log_start = kvm_log_start;
1974     kml->listener.log_stop = kvm_log_stop;
1975     kml->listener.priority = MEMORY_LISTENER_PRIORITY_ACCEL;
1976     kml->listener.name = name;
1977 
1978     if (s->kvm_dirty_ring_size) {
1979         kml->listener.log_sync_global = kvm_log_sync_global;
1980     } else {
1981         kml->listener.log_sync = kvm_log_sync;
1982         kml->listener.log_clear = kvm_log_clear;
1983     }
1984 
1985     memory_listener_register(&kml->listener, as);
1986 
1987     for (i = 0; i < s->nr_as; ++i) {
1988         if (!s->as[i].as) {
1989             s->as[i].as = as;
1990             s->as[i].ml = kml;
1991             break;
1992         }
1993     }
1994 }
1995 
1996 static MemoryListener kvm_io_listener = {
1997     .name = "kvm-io",
1998     .coalesced_io_add = kvm_coalesce_pio_add,
1999     .coalesced_io_del = kvm_coalesce_pio_del,
2000     .eventfd_add = kvm_io_ioeventfd_add,
2001     .eventfd_del = kvm_io_ioeventfd_del,
2002     .priority = MEMORY_LISTENER_PRIORITY_DEV_BACKEND,
2003 };
2004 
kvm_set_irq(KVMState * s,int irq,int level)2005 int kvm_set_irq(KVMState *s, int irq, int level)
2006 {
2007     struct kvm_irq_level event;
2008     int ret;
2009 
2010     assert(kvm_async_interrupts_enabled());
2011 
2012     event.level = level;
2013     event.irq = irq;
2014     ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
2015     if (ret < 0) {
2016         perror("kvm_set_irq");
2017         abort();
2018     }
2019 
2020     return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
2021 }
2022 
2023 #ifdef KVM_CAP_IRQ_ROUTING
2024 typedef struct KVMMSIRoute {
2025     struct kvm_irq_routing_entry kroute;
2026     QTAILQ_ENTRY(KVMMSIRoute) entry;
2027 } KVMMSIRoute;
2028 
set_gsi(KVMState * s,unsigned int gsi)2029 static void set_gsi(KVMState *s, unsigned int gsi)
2030 {
2031     set_bit(gsi, s->used_gsi_bitmap);
2032 }
2033 
clear_gsi(KVMState * s,unsigned int gsi)2034 static void clear_gsi(KVMState *s, unsigned int gsi)
2035 {
2036     clear_bit(gsi, s->used_gsi_bitmap);
2037 }
2038 
kvm_init_irq_routing(KVMState * s)2039 void kvm_init_irq_routing(KVMState *s)
2040 {
2041     int gsi_count;
2042 
2043     gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
2044     if (gsi_count > 0) {
2045         /* Round up so we can search ints using ffs */
2046         s->used_gsi_bitmap = bitmap_new(gsi_count);
2047         s->gsi_count = gsi_count;
2048     }
2049 
2050     s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
2051     s->nr_allocated_irq_routes = 0;
2052 
2053     kvm_arch_init_irq_routing(s);
2054 }
2055 
kvm_irqchip_commit_routes(KVMState * s)2056 void kvm_irqchip_commit_routes(KVMState *s)
2057 {
2058     int ret;
2059 
2060     if (kvm_gsi_direct_mapping()) {
2061         return;
2062     }
2063 
2064     if (!kvm_gsi_routing_enabled()) {
2065         return;
2066     }
2067 
2068     s->irq_routes->flags = 0;
2069     trace_kvm_irqchip_commit_routes();
2070     ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
2071     assert(ret == 0);
2072 }
2073 
kvm_add_routing_entry(KVMState * s,struct kvm_irq_routing_entry * entry)2074 void kvm_add_routing_entry(KVMState *s,
2075                            struct kvm_irq_routing_entry *entry)
2076 {
2077     struct kvm_irq_routing_entry *new;
2078     int n, size;
2079 
2080     if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
2081         n = s->nr_allocated_irq_routes * 2;
2082         if (n < 64) {
2083             n = 64;
2084         }
2085         size = sizeof(struct kvm_irq_routing);
2086         size += n * sizeof(*new);
2087         s->irq_routes = g_realloc(s->irq_routes, size);
2088         s->nr_allocated_irq_routes = n;
2089     }
2090     n = s->irq_routes->nr++;
2091     new = &s->irq_routes->entries[n];
2092 
2093     *new = *entry;
2094 
2095     set_gsi(s, entry->gsi);
2096 }
2097 
kvm_update_routing_entry(KVMState * s,struct kvm_irq_routing_entry * new_entry)2098 static int kvm_update_routing_entry(KVMState *s,
2099                                     struct kvm_irq_routing_entry *new_entry)
2100 {
2101     struct kvm_irq_routing_entry *entry;
2102     int n;
2103 
2104     for (n = 0; n < s->irq_routes->nr; n++) {
2105         entry = &s->irq_routes->entries[n];
2106         if (entry->gsi != new_entry->gsi) {
2107             continue;
2108         }
2109 
2110         if(!memcmp(entry, new_entry, sizeof *entry)) {
2111             return 0;
2112         }
2113 
2114         *entry = *new_entry;
2115 
2116         return 0;
2117     }
2118 
2119     return -ESRCH;
2120 }
2121 
kvm_irqchip_add_irq_route(KVMState * s,int irq,int irqchip,int pin)2122 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
2123 {
2124     struct kvm_irq_routing_entry e = {};
2125 
2126     assert(pin < s->gsi_count);
2127 
2128     e.gsi = irq;
2129     e.type = KVM_IRQ_ROUTING_IRQCHIP;
2130     e.flags = 0;
2131     e.u.irqchip.irqchip = irqchip;
2132     e.u.irqchip.pin = pin;
2133     kvm_add_routing_entry(s, &e);
2134 }
2135 
kvm_irqchip_release_virq(KVMState * s,int virq)2136 void kvm_irqchip_release_virq(KVMState *s, int virq)
2137 {
2138     struct kvm_irq_routing_entry *e;
2139     int i;
2140 
2141     if (kvm_gsi_direct_mapping()) {
2142         return;
2143     }
2144 
2145     for (i = 0; i < s->irq_routes->nr; i++) {
2146         e = &s->irq_routes->entries[i];
2147         if (e->gsi == virq) {
2148             s->irq_routes->nr--;
2149             *e = s->irq_routes->entries[s->irq_routes->nr];
2150         }
2151     }
2152     clear_gsi(s, virq);
2153     kvm_arch_release_virq_post(virq);
2154     trace_kvm_irqchip_release_virq(virq);
2155 }
2156 
kvm_irqchip_add_change_notifier(Notifier * n)2157 void kvm_irqchip_add_change_notifier(Notifier *n)
2158 {
2159     notifier_list_add(&kvm_irqchip_change_notifiers, n);
2160 }
2161 
kvm_irqchip_remove_change_notifier(Notifier * n)2162 void kvm_irqchip_remove_change_notifier(Notifier *n)
2163 {
2164     notifier_remove(n);
2165 }
2166 
kvm_irqchip_change_notify(void)2167 void kvm_irqchip_change_notify(void)
2168 {
2169     notifier_list_notify(&kvm_irqchip_change_notifiers, NULL);
2170 }
2171 
kvm_irqchip_get_virq(KVMState * s)2172 int kvm_irqchip_get_virq(KVMState *s)
2173 {
2174     int next_virq;
2175 
2176     /* Return the lowest unused GSI in the bitmap */
2177     next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
2178     if (next_virq >= s->gsi_count) {
2179         return -ENOSPC;
2180     } else {
2181         return next_virq;
2182     }
2183 }
2184 
kvm_irqchip_send_msi(KVMState * s,MSIMessage msg)2185 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
2186 {
2187     struct kvm_msi msi;
2188 
2189     msi.address_lo = (uint32_t)msg.address;
2190     msi.address_hi = msg.address >> 32;
2191     msi.data = le32_to_cpu(msg.data);
2192     msi.flags = 0;
2193     memset(msi.pad, 0, sizeof(msi.pad));
2194 
2195     return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
2196 }
2197 
kvm_irqchip_add_msi_route(KVMRouteChange * c,int vector,PCIDevice * dev)2198 int kvm_irqchip_add_msi_route(KVMRouteChange *c, int vector, PCIDevice *dev)
2199 {
2200     struct kvm_irq_routing_entry kroute = {};
2201     int virq;
2202     KVMState *s = c->s;
2203     MSIMessage msg = {0, 0};
2204 
2205     if (pci_available && dev) {
2206         msg = pci_get_msi_message(dev, vector);
2207     }
2208 
2209     if (kvm_gsi_direct_mapping()) {
2210         return kvm_arch_msi_data_to_gsi(msg.data);
2211     }
2212 
2213     if (!kvm_gsi_routing_enabled()) {
2214         return -ENOSYS;
2215     }
2216 
2217     virq = kvm_irqchip_get_virq(s);
2218     if (virq < 0) {
2219         return virq;
2220     }
2221 
2222     kroute.gsi = virq;
2223     kroute.type = KVM_IRQ_ROUTING_MSI;
2224     kroute.flags = 0;
2225     kroute.u.msi.address_lo = (uint32_t)msg.address;
2226     kroute.u.msi.address_hi = msg.address >> 32;
2227     kroute.u.msi.data = le32_to_cpu(msg.data);
2228     if (pci_available && kvm_msi_devid_required()) {
2229         kroute.flags = KVM_MSI_VALID_DEVID;
2230         kroute.u.msi.devid = pci_requester_id(dev);
2231     }
2232     if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
2233         kvm_irqchip_release_virq(s, virq);
2234         return -EINVAL;
2235     }
2236 
2237     if (s->irq_routes->nr < s->gsi_count) {
2238         trace_kvm_irqchip_add_msi_route(dev ? dev->name : (char *)"N/A",
2239                                         vector, virq);
2240 
2241         kvm_add_routing_entry(s, &kroute);
2242         kvm_arch_add_msi_route_post(&kroute, vector, dev);
2243         c->changes++;
2244     } else {
2245         kvm_irqchip_release_virq(s, virq);
2246         return -ENOSPC;
2247     }
2248 
2249     return virq;
2250 }
2251 
kvm_irqchip_update_msi_route(KVMState * s,int virq,MSIMessage msg,PCIDevice * dev)2252 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
2253                                  PCIDevice *dev)
2254 {
2255     struct kvm_irq_routing_entry kroute = {};
2256 
2257     if (kvm_gsi_direct_mapping()) {
2258         return 0;
2259     }
2260 
2261     if (!kvm_irqchip_in_kernel()) {
2262         return -ENOSYS;
2263     }
2264 
2265     kroute.gsi = virq;
2266     kroute.type = KVM_IRQ_ROUTING_MSI;
2267     kroute.flags = 0;
2268     kroute.u.msi.address_lo = (uint32_t)msg.address;
2269     kroute.u.msi.address_hi = msg.address >> 32;
2270     kroute.u.msi.data = le32_to_cpu(msg.data);
2271     if (pci_available && kvm_msi_devid_required()) {
2272         kroute.flags = KVM_MSI_VALID_DEVID;
2273         kroute.u.msi.devid = pci_requester_id(dev);
2274     }
2275     if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
2276         return -EINVAL;
2277     }
2278 
2279     trace_kvm_irqchip_update_msi_route(virq);
2280 
2281     return kvm_update_routing_entry(s, &kroute);
2282 }
2283 
kvm_irqchip_assign_irqfd(KVMState * s,EventNotifier * event,EventNotifier * resample,int virq,bool assign)2284 static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
2285                                     EventNotifier *resample, int virq,
2286                                     bool assign)
2287 {
2288     int fd = event_notifier_get_fd(event);
2289     int rfd = resample ? event_notifier_get_fd(resample) : -1;
2290 
2291     struct kvm_irqfd irqfd = {
2292         .fd = fd,
2293         .gsi = virq,
2294         .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
2295     };
2296 
2297     if (rfd != -1) {
2298         assert(assign);
2299         if (kvm_irqchip_is_split()) {
2300             /*
2301              * When the slow irqchip (e.g. IOAPIC) is in the
2302              * userspace, KVM kernel resamplefd will not work because
2303              * the EOI of the interrupt will be delivered to userspace
2304              * instead, so the KVM kernel resamplefd kick will be
2305              * skipped.  The userspace here mimics what the kernel
2306              * provides with resamplefd, remember the resamplefd and
2307              * kick it when we receive EOI of this IRQ.
2308              *
2309              * This is hackery because IOAPIC is mostly bypassed
2310              * (except EOI broadcasts) when irqfd is used.  However
2311              * this can bring much performance back for split irqchip
2312              * with INTx IRQs (for VFIO, this gives 93% perf of the
2313              * full fast path, which is 46% perf boost comparing to
2314              * the INTx slow path).
2315              */
2316             kvm_resample_fd_insert(virq, resample);
2317         } else {
2318             irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
2319             irqfd.resamplefd = rfd;
2320         }
2321     } else if (!assign) {
2322         if (kvm_irqchip_is_split()) {
2323             kvm_resample_fd_remove(virq);
2324         }
2325     }
2326 
2327     return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
2328 }
2329 
2330 #else /* !KVM_CAP_IRQ_ROUTING */
2331 
kvm_init_irq_routing(KVMState * s)2332 void kvm_init_irq_routing(KVMState *s)
2333 {
2334 }
2335 
kvm_irqchip_release_virq(KVMState * s,int virq)2336 void kvm_irqchip_release_virq(KVMState *s, int virq)
2337 {
2338 }
2339 
kvm_irqchip_send_msi(KVMState * s,MSIMessage msg)2340 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
2341 {
2342     abort();
2343 }
2344 
kvm_irqchip_add_msi_route(KVMRouteChange * c,int vector,PCIDevice * dev)2345 int kvm_irqchip_add_msi_route(KVMRouteChange *c, int vector, PCIDevice *dev)
2346 {
2347     return -ENOSYS;
2348 }
2349 
kvm_irqchip_add_adapter_route(KVMState * s,AdapterInfo * adapter)2350 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
2351 {
2352     return -ENOSYS;
2353 }
2354 
kvm_irqchip_add_hv_sint_route(KVMState * s,uint32_t vcpu,uint32_t sint)2355 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
2356 {
2357     return -ENOSYS;
2358 }
2359 
kvm_irqchip_assign_irqfd(KVMState * s,EventNotifier * event,EventNotifier * resample,int virq,bool assign)2360 static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
2361                                     EventNotifier *resample, int virq,
2362                                     bool assign)
2363 {
2364     abort();
2365 }
2366 
kvm_irqchip_update_msi_route(KVMState * s,int virq,MSIMessage msg)2367 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
2368 {
2369     return -ENOSYS;
2370 }
2371 #endif /* !KVM_CAP_IRQ_ROUTING */
2372 
kvm_irqchip_add_irqfd_notifier_gsi(KVMState * s,EventNotifier * n,EventNotifier * rn,int virq)2373 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
2374                                        EventNotifier *rn, int virq)
2375 {
2376     return kvm_irqchip_assign_irqfd(s, n, rn, virq, true);
2377 }
2378 
kvm_irqchip_remove_irqfd_notifier_gsi(KVMState * s,EventNotifier * n,int virq)2379 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
2380                                           int virq)
2381 {
2382     return kvm_irqchip_assign_irqfd(s, n, NULL, virq, false);
2383 }
2384 
kvm_irqchip_add_irqfd_notifier(KVMState * s,EventNotifier * n,EventNotifier * rn,qemu_irq irq)2385 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
2386                                    EventNotifier *rn, qemu_irq irq)
2387 {
2388     gpointer key, gsi;
2389     gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
2390 
2391     if (!found) {
2392         return -ENXIO;
2393     }
2394     return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
2395 }
2396 
kvm_irqchip_remove_irqfd_notifier(KVMState * s,EventNotifier * n,qemu_irq irq)2397 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
2398                                       qemu_irq irq)
2399 {
2400     gpointer key, gsi;
2401     gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
2402 
2403     if (!found) {
2404         return -ENXIO;
2405     }
2406     return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
2407 }
2408 
kvm_irqchip_set_qemuirq_gsi(KVMState * s,qemu_irq irq,int gsi)2409 void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
2410 {
2411     g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
2412 }
2413 
kvm_irqchip_create(KVMState * s)2414 static void kvm_irqchip_create(KVMState *s)
2415 {
2416     int ret;
2417 
2418     assert(s->kernel_irqchip_split != ON_OFF_AUTO_AUTO);
2419     if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
2420         ;
2421     } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
2422         ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
2423         if (ret < 0) {
2424             fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
2425             exit(1);
2426         }
2427     } else {
2428         return;
2429     }
2430 
2431     if (kvm_check_extension(s, KVM_CAP_IRQFD) <= 0) {
2432         fprintf(stderr, "kvm: irqfd not implemented\n");
2433         exit(1);
2434     }
2435 
2436     /* First probe and see if there's a arch-specific hook to create the
2437      * in-kernel irqchip for us */
2438     ret = kvm_arch_irqchip_create(s);
2439     if (ret == 0) {
2440         if (s->kernel_irqchip_split == ON_OFF_AUTO_ON) {
2441             error_report("Split IRQ chip mode not supported.");
2442             exit(1);
2443         } else {
2444             ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
2445         }
2446     }
2447     if (ret < 0) {
2448         fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
2449         exit(1);
2450     }
2451 
2452     kvm_kernel_irqchip = true;
2453     /* If we have an in-kernel IRQ chip then we must have asynchronous
2454      * interrupt delivery (though the reverse is not necessarily true)
2455      */
2456     kvm_async_interrupts_allowed = true;
2457     kvm_halt_in_kernel_allowed = true;
2458 
2459     kvm_init_irq_routing(s);
2460 
2461     s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
2462 }
2463 
2464 /* Find number of supported CPUs using the recommended
2465  * procedure from the kernel API documentation to cope with
2466  * older kernels that may be missing capabilities.
2467  */
kvm_recommended_vcpus(KVMState * s)2468 static int kvm_recommended_vcpus(KVMState *s)
2469 {
2470     int ret = kvm_vm_check_extension(s, KVM_CAP_NR_VCPUS);
2471     return (ret) ? ret : 4;
2472 }
2473 
kvm_max_vcpus(KVMState * s)2474 static int kvm_max_vcpus(KVMState *s)
2475 {
2476     int ret = kvm_vm_check_extension(s, KVM_CAP_MAX_VCPUS);
2477     return (ret) ? ret : kvm_recommended_vcpus(s);
2478 }
2479 
kvm_max_vcpu_id(KVMState * s)2480 static int kvm_max_vcpu_id(KVMState *s)
2481 {
2482     int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
2483     return (ret) ? ret : kvm_max_vcpus(s);
2484 }
2485 
kvm_vcpu_id_is_valid(int vcpu_id)2486 bool kvm_vcpu_id_is_valid(int vcpu_id)
2487 {
2488     KVMState *s = KVM_STATE(current_accel());
2489     return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
2490 }
2491 
kvm_dirty_ring_enabled(void)2492 bool kvm_dirty_ring_enabled(void)
2493 {
2494     return kvm_state && kvm_state->kvm_dirty_ring_size;
2495 }
2496 
2497 static void query_stats_cb(StatsResultList **result, StatsTarget target,
2498                            strList *names, strList *targets, Error **errp);
2499 static void query_stats_schemas_cb(StatsSchemaList **result, Error **errp);
2500 
kvm_dirty_ring_size(void)2501 uint32_t kvm_dirty_ring_size(void)
2502 {
2503     return kvm_state->kvm_dirty_ring_size;
2504 }
2505 
do_kvm_create_vm(KVMState * s,int type)2506 static int do_kvm_create_vm(KVMState *s, int type)
2507 {
2508     int ret;
2509 
2510     do {
2511         ret = kvm_ioctl(s, KVM_CREATE_VM, type);
2512     } while (ret == -EINTR);
2513 
2514     if (ret < 0) {
2515         error_report("ioctl(KVM_CREATE_VM) failed: %s", strerror(-ret));
2516 
2517 #ifdef TARGET_S390X
2518         if (ret == -EINVAL) {
2519             error_printf("Host kernel setup problem detected."
2520                          " Please verify:\n");
2521             error_printf("- for kernels supporting the"
2522                         " switch_amode or user_mode parameters, whether");
2523             error_printf(" user space is running in primary address space\n");
2524             error_printf("- for kernels supporting the vm.allocate_pgste"
2525                          " sysctl, whether it is enabled\n");
2526         }
2527 #elif defined(TARGET_PPC)
2528         if (ret == -EINVAL) {
2529             error_printf("PPC KVM module is not loaded. Try modprobe kvm_%s.\n",
2530                          (type == 2) ? "pr" : "hv");
2531         }
2532 #endif
2533     }
2534 
2535     return ret;
2536 }
2537 
find_kvm_machine_type(MachineState * ms)2538 static int find_kvm_machine_type(MachineState *ms)
2539 {
2540     MachineClass *mc = MACHINE_GET_CLASS(ms);
2541     int type;
2542 
2543     if (object_property_find(OBJECT(current_machine), "kvm-type")) {
2544         g_autofree char *kvm_type;
2545         kvm_type = object_property_get_str(OBJECT(current_machine),
2546                                            "kvm-type",
2547                                            &error_abort);
2548         type = mc->kvm_type(ms, kvm_type);
2549     } else if (mc->kvm_type) {
2550         type = mc->kvm_type(ms, NULL);
2551     } else {
2552         type = kvm_arch_get_default_type(ms);
2553     }
2554     return type;
2555 }
2556 
kvm_setup_dirty_ring(KVMState * s)2557 static int kvm_setup_dirty_ring(KVMState *s)
2558 {
2559     uint64_t dirty_log_manual_caps;
2560     int ret;
2561 
2562     /*
2563      * Enable KVM dirty ring if supported, otherwise fall back to
2564      * dirty logging mode
2565      */
2566     ret = kvm_dirty_ring_init(s);
2567     if (ret < 0) {
2568         return ret;
2569     }
2570 
2571     /*
2572      * KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is not needed when dirty ring is
2573      * enabled.  More importantly, KVM_DIRTY_LOG_INITIALLY_SET will assume no
2574      * page is wr-protected initially, which is against how kvm dirty ring is
2575      * usage - kvm dirty ring requires all pages are wr-protected at the very
2576      * beginning.  Enabling this feature for dirty ring causes data corruption.
2577      *
2578      * TODO: Without KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 and kvm clear dirty log,
2579      * we may expect a higher stall time when starting the migration.  In the
2580      * future we can enable KVM_CLEAR_DIRTY_LOG to work with dirty ring too:
2581      * instead of clearing dirty bit, it can be a way to explicitly wr-protect
2582      * guest pages.
2583      */
2584     if (!s->kvm_dirty_ring_size) {
2585         dirty_log_manual_caps =
2586             kvm_check_extension(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
2587         dirty_log_manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
2588                                   KVM_DIRTY_LOG_INITIALLY_SET);
2589         s->manual_dirty_log_protect = dirty_log_manual_caps;
2590         if (dirty_log_manual_caps) {
2591             ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0,
2592                                     dirty_log_manual_caps);
2593             if (ret) {
2594                 warn_report("Trying to enable capability %"PRIu64" of "
2595                             "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
2596                             "Falling back to the legacy mode. ",
2597                             dirty_log_manual_caps);
2598                 s->manual_dirty_log_protect = 0;
2599             }
2600         }
2601     }
2602 
2603     return 0;
2604 }
2605 
kvm_init(AccelState * as,MachineState * ms)2606 static int kvm_init(AccelState *as, MachineState *ms)
2607 {
2608     MachineClass *mc = MACHINE_GET_CLASS(ms);
2609     static const char upgrade_note[] =
2610         "Please upgrade to at least kernel 4.5.\n";
2611     const struct {
2612         const char *name;
2613         int num;
2614     } num_cpus[] = {
2615         { "SMP",          ms->smp.cpus },
2616         { "hotpluggable", ms->smp.max_cpus },
2617         { /* end of list */ }
2618     }, *nc = num_cpus;
2619     int soft_vcpus_limit, hard_vcpus_limit;
2620     KVMState *s = KVM_STATE(as);
2621     const KVMCapabilityInfo *missing_cap;
2622     int ret;
2623     int type;
2624 
2625     qemu_mutex_init(&kml_slots_lock);
2626 
2627     /*
2628      * On systems where the kernel can support different base page
2629      * sizes, host page size may be different from TARGET_PAGE_SIZE,
2630      * even with KVM.  TARGET_PAGE_SIZE is assumed to be the minimum
2631      * page size for the system though.
2632      */
2633     assert(TARGET_PAGE_SIZE <= qemu_real_host_page_size());
2634 
2635     s->sigmask_len = 8;
2636     accel_blocker_init();
2637 
2638 #ifdef TARGET_KVM_HAVE_GUEST_DEBUG
2639     QTAILQ_INIT(&s->kvm_sw_breakpoints);
2640 #endif
2641     QLIST_INIT(&s->kvm_parked_vcpus);
2642     s->fd = qemu_open_old(s->device ?: "/dev/kvm", O_RDWR);
2643     if (s->fd == -1) {
2644         error_report("Could not access KVM kernel module: %m");
2645         ret = -errno;
2646         goto err;
2647     }
2648 
2649     ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
2650     if (ret < KVM_API_VERSION) {
2651         if (ret >= 0) {
2652             ret = -EINVAL;
2653         }
2654         error_report("kvm version too old");
2655         goto err;
2656     }
2657 
2658     if (ret > KVM_API_VERSION) {
2659         ret = -EINVAL;
2660         error_report("kvm version not supported");
2661         goto err;
2662     }
2663 
2664     kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
2665     s->nr_slots_max = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
2666 
2667     /* If unspecified, use the default value */
2668     if (!s->nr_slots_max) {
2669         s->nr_slots_max = KVM_MEMSLOTS_NR_MAX_DEFAULT;
2670     }
2671 
2672     type = find_kvm_machine_type(ms);
2673     if (type < 0) {
2674         ret = -EINVAL;
2675         goto err;
2676     }
2677 
2678     ret = do_kvm_create_vm(s, type);
2679     if (ret < 0) {
2680         goto err;
2681     }
2682 
2683     s->vmfd = ret;
2684 
2685     s->nr_as = kvm_vm_check_extension(s, KVM_CAP_MULTI_ADDRESS_SPACE);
2686     if (s->nr_as <= 1) {
2687         s->nr_as = 1;
2688     }
2689     s->as = g_new0(struct KVMAs, s->nr_as);
2690 
2691     /* check the vcpu limits */
2692     soft_vcpus_limit = kvm_recommended_vcpus(s);
2693     hard_vcpus_limit = kvm_max_vcpus(s);
2694 
2695     while (nc->name) {
2696         if (nc->num > soft_vcpus_limit) {
2697             warn_report("Number of %s cpus requested (%d) exceeds "
2698                         "the recommended cpus supported by KVM (%d)",
2699                         nc->name, nc->num, soft_vcpus_limit);
2700 
2701             if (nc->num > hard_vcpus_limit) {
2702                 error_report("Number of %s cpus requested (%d) exceeds "
2703                              "the maximum cpus supported by KVM (%d)",
2704                              nc->name, nc->num, hard_vcpus_limit);
2705                 exit(1);
2706             }
2707         }
2708         nc++;
2709     }
2710 
2711     missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
2712     if (!missing_cap) {
2713         missing_cap =
2714             kvm_check_extension_list(s, kvm_arch_required_capabilities);
2715     }
2716     if (missing_cap) {
2717         ret = -EINVAL;
2718         error_report("kvm does not support %s", missing_cap->name);
2719         error_printf("%s", upgrade_note);
2720         goto err;
2721     }
2722 
2723     s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
2724     s->coalesced_pio = s->coalesced_mmio &&
2725                        kvm_check_extension(s, KVM_CAP_COALESCED_PIO);
2726 
2727     ret = kvm_setup_dirty_ring(s);
2728     if (ret < 0) {
2729         goto err;
2730     }
2731 
2732 #ifdef KVM_CAP_VCPU_EVENTS
2733     s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
2734 #endif
2735     s->max_nested_state_len = kvm_check_extension(s, KVM_CAP_NESTED_STATE);
2736 
2737     s->irq_set_ioctl = KVM_IRQ_LINE;
2738     if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
2739         s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
2740     }
2741 
2742     kvm_readonly_mem_allowed =
2743         (kvm_vm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
2744 
2745     kvm_resamplefds_allowed =
2746         (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
2747 
2748     kvm_vm_attributes_allowed =
2749         (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
2750 
2751 #ifdef TARGET_KVM_HAVE_GUEST_DEBUG
2752     kvm_has_guest_debug =
2753         (kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG) > 0);
2754 #endif
2755 
2756     kvm_sstep_flags = 0;
2757     if (kvm_has_guest_debug) {
2758         kvm_sstep_flags = SSTEP_ENABLE;
2759 
2760 #if defined TARGET_KVM_HAVE_GUEST_DEBUG
2761         int guest_debug_flags =
2762             kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG2);
2763 
2764         if (guest_debug_flags & KVM_GUESTDBG_BLOCKIRQ) {
2765             kvm_sstep_flags |= SSTEP_NOIRQ;
2766         }
2767 #endif
2768     }
2769 
2770     kvm_state = s;
2771 
2772     ret = kvm_arch_init(ms, s);
2773     if (ret < 0) {
2774         goto err;
2775     }
2776 
2777     kvm_supported_memory_attributes = kvm_vm_check_extension(s, KVM_CAP_MEMORY_ATTRIBUTES);
2778     kvm_guest_memfd_supported =
2779         kvm_check_extension(s, KVM_CAP_GUEST_MEMFD) &&
2780         kvm_check_extension(s, KVM_CAP_USER_MEMORY2) &&
2781         (kvm_supported_memory_attributes & KVM_MEMORY_ATTRIBUTE_PRIVATE);
2782     kvm_pre_fault_memory_supported = kvm_vm_check_extension(s, KVM_CAP_PRE_FAULT_MEMORY);
2783 
2784     if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
2785         s->kernel_irqchip_split = mc->default_kernel_irqchip_split ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
2786     }
2787 
2788     qemu_register_reset(kvm_unpoison_all, NULL);
2789 
2790     if (s->kernel_irqchip_allowed) {
2791         kvm_irqchip_create(s);
2792     }
2793 
2794     s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
2795     s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
2796     s->memory_listener.listener.coalesced_io_add = kvm_coalesce_mmio_region;
2797     s->memory_listener.listener.coalesced_io_del = kvm_uncoalesce_mmio_region;
2798 
2799     kvm_memory_listener_register(s, &s->memory_listener,
2800                                  &address_space_memory, 0, "kvm-memory");
2801     memory_listener_register(&kvm_io_listener,
2802                              &address_space_io);
2803 
2804     s->sync_mmu = !!kvm_vm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2805     if (!s->sync_mmu) {
2806         ret = ram_block_discard_disable(true);
2807         assert(!ret);
2808     }
2809 
2810     if (s->kvm_dirty_ring_size) {
2811         kvm_dirty_ring_reaper_init(s);
2812     }
2813 
2814     if (kvm_check_extension(kvm_state, KVM_CAP_BINARY_STATS_FD)) {
2815         add_stats_callbacks(STATS_PROVIDER_KVM, query_stats_cb,
2816                             query_stats_schemas_cb);
2817     }
2818 
2819     return 0;
2820 
2821 err:
2822     assert(ret < 0);
2823     if (s->vmfd >= 0) {
2824         close(s->vmfd);
2825     }
2826     if (s->fd != -1) {
2827         close(s->fd);
2828     }
2829     g_free(s->as);
2830     g_free(s->memory_listener.slots);
2831 
2832     return ret;
2833 }
2834 
kvm_set_sigmask_len(KVMState * s,unsigned int sigmask_len)2835 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
2836 {
2837     s->sigmask_len = sigmask_len;
2838 }
2839 
kvm_handle_io(uint16_t port,MemTxAttrs attrs,void * data,int direction,int size,uint32_t count)2840 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
2841                           int size, uint32_t count)
2842 {
2843     int i;
2844     uint8_t *ptr = data;
2845 
2846     for (i = 0; i < count; i++) {
2847         address_space_rw(&address_space_io, port, attrs,
2848                          ptr, size,
2849                          direction == KVM_EXIT_IO_OUT);
2850         ptr += size;
2851     }
2852 }
2853 
kvm_handle_internal_error(CPUState * cpu,struct kvm_run * run)2854 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
2855 {
2856     int i;
2857 
2858     fprintf(stderr, "KVM internal error. Suberror: %d\n",
2859             run->internal.suberror);
2860 
2861     for (i = 0; i < run->internal.ndata; ++i) {
2862         fprintf(stderr, "extra data[%d]: 0x%016"PRIx64"\n",
2863                 i, (uint64_t)run->internal.data[i]);
2864     }
2865     if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
2866         fprintf(stderr, "emulation failure\n");
2867         if (!kvm_arch_stop_on_emulation_error(cpu)) {
2868             cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2869             return EXCP_INTERRUPT;
2870         }
2871     }
2872     /* FIXME: Should trigger a qmp message to let management know
2873      * something went wrong.
2874      */
2875     return -1;
2876 }
2877 
kvm_flush_coalesced_mmio_buffer(void)2878 void kvm_flush_coalesced_mmio_buffer(void)
2879 {
2880     KVMState *s = kvm_state;
2881 
2882     if (!s || s->coalesced_flush_in_progress) {
2883         return;
2884     }
2885 
2886     s->coalesced_flush_in_progress = true;
2887 
2888     if (s->coalesced_mmio_ring) {
2889         struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
2890         while (ring->first != ring->last) {
2891             struct kvm_coalesced_mmio *ent;
2892 
2893             ent = &ring->coalesced_mmio[ring->first];
2894 
2895             if (ent->pio == 1) {
2896                 address_space_write(&address_space_io, ent->phys_addr,
2897                                     MEMTXATTRS_UNSPECIFIED, ent->data,
2898                                     ent->len);
2899             } else {
2900                 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
2901             }
2902             smp_wmb();
2903             ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
2904         }
2905     }
2906 
2907     s->coalesced_flush_in_progress = false;
2908 }
2909 
do_kvm_cpu_synchronize_state(CPUState * cpu,run_on_cpu_data arg)2910 static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
2911 {
2912     if (!cpu->vcpu_dirty && !kvm_state->guest_state_protected) {
2913         Error *err = NULL;
2914         int ret = kvm_arch_get_registers(cpu, &err);
2915         if (ret) {
2916             if (err) {
2917                 error_reportf_err(err, "Failed to synchronize CPU state: ");
2918             } else {
2919                 error_report("Failed to get registers: %s", strerror(-ret));
2920             }
2921 
2922             cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2923             vm_stop(RUN_STATE_INTERNAL_ERROR);
2924         }
2925 
2926         cpu->vcpu_dirty = true;
2927     }
2928 }
2929 
kvm_cpu_synchronize_state(CPUState * cpu)2930 void kvm_cpu_synchronize_state(CPUState *cpu)
2931 {
2932     if (!cpu->vcpu_dirty && !kvm_state->guest_state_protected) {
2933         run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
2934     }
2935 }
2936 
do_kvm_cpu_synchronize_post_reset(CPUState * cpu,run_on_cpu_data arg)2937 static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
2938 {
2939     Error *err = NULL;
2940     int ret = kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE, &err);
2941     if (ret) {
2942         if (err) {
2943             error_reportf_err(err, "Restoring resisters after reset: ");
2944         } else {
2945             error_report("Failed to put registers after reset: %s",
2946                          strerror(-ret));
2947         }
2948         cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2949         vm_stop(RUN_STATE_INTERNAL_ERROR);
2950     }
2951 
2952     cpu->vcpu_dirty = false;
2953 }
2954 
kvm_cpu_synchronize_post_reset(CPUState * cpu)2955 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
2956 {
2957     run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
2958 
2959     if (cpu == first_cpu) {
2960         kvm_reset_parked_vcpus(kvm_state);
2961     }
2962 }
2963 
do_kvm_cpu_synchronize_post_init(CPUState * cpu,run_on_cpu_data arg)2964 static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
2965 {
2966     Error *err = NULL;
2967     int ret = kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE, &err);
2968     if (ret) {
2969         if (err) {
2970             error_reportf_err(err, "Putting registers after init: ");
2971         } else {
2972             error_report("Failed to put registers after init: %s",
2973                          strerror(-ret));
2974         }
2975         exit(1);
2976     }
2977 
2978     cpu->vcpu_dirty = false;
2979 }
2980 
kvm_cpu_synchronize_post_init(CPUState * cpu)2981 void kvm_cpu_synchronize_post_init(CPUState *cpu)
2982 {
2983     if (!kvm_state->guest_state_protected) {
2984         /*
2985          * This runs before the machine_init_done notifiers, and is the last
2986          * opportunity to synchronize the state of confidential guests.
2987          */
2988         run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
2989     }
2990 }
2991 
do_kvm_cpu_synchronize_pre_loadvm(CPUState * cpu,run_on_cpu_data arg)2992 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
2993 {
2994     cpu->vcpu_dirty = true;
2995 }
2996 
kvm_cpu_synchronize_pre_loadvm(CPUState * cpu)2997 void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
2998 {
2999     run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
3000 }
3001 
3002 #ifdef KVM_HAVE_MCE_INJECTION
3003 static __thread void *pending_sigbus_addr;
3004 static __thread int pending_sigbus_code;
3005 static __thread bool have_sigbus_pending;
3006 #endif
3007 
kvm_cpu_kick(CPUState * cpu)3008 static void kvm_cpu_kick(CPUState *cpu)
3009 {
3010     qatomic_set(&cpu->kvm_run->immediate_exit, 1);
3011 }
3012 
kvm_cpu_kick_self(void)3013 static void kvm_cpu_kick_self(void)
3014 {
3015     if (kvm_immediate_exit) {
3016         kvm_cpu_kick(current_cpu);
3017     } else {
3018         qemu_cpu_kick_self();
3019     }
3020 }
3021 
kvm_eat_signals(CPUState * cpu)3022 static void kvm_eat_signals(CPUState *cpu)
3023 {
3024     struct timespec ts = { 0, 0 };
3025     siginfo_t siginfo;
3026     sigset_t waitset;
3027     sigset_t chkset;
3028     int r;
3029 
3030     if (kvm_immediate_exit) {
3031         qatomic_set(&cpu->kvm_run->immediate_exit, 0);
3032         /* Write kvm_run->immediate_exit before the cpu->exit_request
3033          * write in kvm_cpu_exec.
3034          */
3035         smp_wmb();
3036         return;
3037     }
3038 
3039     sigemptyset(&waitset);
3040     sigaddset(&waitset, SIG_IPI);
3041 
3042     do {
3043         r = sigtimedwait(&waitset, &siginfo, &ts);
3044         if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
3045             perror("sigtimedwait");
3046             exit(1);
3047         }
3048 
3049         r = sigpending(&chkset);
3050         if (r == -1) {
3051             perror("sigpending");
3052             exit(1);
3053         }
3054     } while (sigismember(&chkset, SIG_IPI));
3055 }
3056 
kvm_convert_memory(hwaddr start,hwaddr size,bool to_private)3057 int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private)
3058 {
3059     MemoryRegionSection section;
3060     ram_addr_t offset;
3061     MemoryRegion *mr;
3062     RAMBlock *rb;
3063     void *addr;
3064     int ret = -EINVAL;
3065 
3066     trace_kvm_convert_memory(start, size, to_private ? "shared_to_private" : "private_to_shared");
3067 
3068     if (!QEMU_PTR_IS_ALIGNED(start, qemu_real_host_page_size()) ||
3069         !QEMU_PTR_IS_ALIGNED(size, qemu_real_host_page_size())) {
3070         return ret;
3071     }
3072 
3073     if (!size) {
3074         return ret;
3075     }
3076 
3077     section = memory_region_find(get_system_memory(), start, size);
3078     mr = section.mr;
3079     if (!mr) {
3080         /*
3081          * Ignore converting non-assigned region to shared.
3082          *
3083          * TDX requires vMMIO region to be shared to inject #VE to guest.
3084          * OVMF issues conservatively MapGPA(shared) on 32bit PCI MMIO region,
3085          * and vIO-APIC 0xFEC00000 4K page.
3086          * OVMF assigns 32bit PCI MMIO region to
3087          * [top of low memory: typically 2GB=0xC000000,  0xFC00000)
3088          */
3089         if (!to_private) {
3090             return 0;
3091         }
3092         return ret;
3093     }
3094 
3095     if (!memory_region_has_guest_memfd(mr)) {
3096         /*
3097          * Because vMMIO region must be shared, guest TD may convert vMMIO
3098          * region to shared explicitly.  Don't complain such case.  See
3099          * memory_region_type() for checking if the region is MMIO region.
3100          */
3101         if (!to_private &&
3102             !memory_region_is_ram(mr) &&
3103             !memory_region_is_ram_device(mr) &&
3104             !memory_region_is_rom(mr) &&
3105             !memory_region_is_romd(mr)) {
3106             ret = 0;
3107         } else {
3108             error_report("Convert non guest_memfd backed memory region "
3109                         "(0x%"HWADDR_PRIx" ,+ 0x%"HWADDR_PRIx") to %s",
3110                         start, size, to_private ? "private" : "shared");
3111         }
3112         goto out_unref;
3113     }
3114 
3115     if (to_private) {
3116         ret = kvm_set_memory_attributes_private(start, size);
3117     } else {
3118         ret = kvm_set_memory_attributes_shared(start, size);
3119     }
3120     if (ret) {
3121         goto out_unref;
3122     }
3123 
3124     addr = memory_region_get_ram_ptr(mr) + section.offset_within_region;
3125     rb = qemu_ram_block_from_host(addr, false, &offset);
3126 
3127     ret = ram_block_attributes_state_change(RAM_BLOCK_ATTRIBUTES(mr->rdm),
3128                                             offset, size, to_private);
3129     if (ret) {
3130         error_report("Failed to notify the listener the state change of "
3131                      "(0x%"HWADDR_PRIx" + 0x%"HWADDR_PRIx") to %s",
3132                      start, size, to_private ? "private" : "shared");
3133         goto out_unref;
3134     }
3135 
3136     if (to_private) {
3137         if (rb->page_size != qemu_real_host_page_size()) {
3138             /*
3139              * shared memory is backed by hugetlb, which is supposed to be
3140              * pre-allocated and doesn't need to be discarded
3141              */
3142             goto out_unref;
3143         }
3144         ret = ram_block_discard_range(rb, offset, size);
3145     } else {
3146         ret = ram_block_discard_guest_memfd_range(rb, offset, size);
3147     }
3148 
3149 out_unref:
3150     memory_region_unref(mr);
3151     return ret;
3152 }
3153 
kvm_cpu_exec(CPUState * cpu)3154 int kvm_cpu_exec(CPUState *cpu)
3155 {
3156     struct kvm_run *run = cpu->kvm_run;
3157     int ret, run_ret;
3158 
3159     trace_kvm_cpu_exec();
3160 
3161     if (kvm_arch_process_async_events(cpu)) {
3162         qatomic_set(&cpu->exit_request, 0);
3163         return EXCP_HLT;
3164     }
3165 
3166     bql_unlock();
3167     cpu_exec_start(cpu);
3168 
3169     do {
3170         MemTxAttrs attrs;
3171 
3172         if (cpu->vcpu_dirty) {
3173             Error *err = NULL;
3174             ret = kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE, &err);
3175             if (ret) {
3176                 if (err) {
3177                     error_reportf_err(err, "Putting registers after init: ");
3178                 } else {
3179                     error_report("Failed to put registers after init: %s",
3180                                  strerror(-ret));
3181                 }
3182                 ret = -1;
3183                 break;
3184             }
3185 
3186             cpu->vcpu_dirty = false;
3187         }
3188 
3189         kvm_arch_pre_run(cpu, run);
3190         if (qatomic_read(&cpu->exit_request)) {
3191             trace_kvm_interrupt_exit_request();
3192             /*
3193              * KVM requires us to reenter the kernel after IO exits to complete
3194              * instruction emulation. This self-signal will ensure that we
3195              * leave ASAP again.
3196              */
3197             kvm_cpu_kick_self();
3198         }
3199 
3200         /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
3201          * Matching barrier in kvm_eat_signals.
3202          */
3203         smp_rmb();
3204 
3205         run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
3206 
3207         attrs = kvm_arch_post_run(cpu, run);
3208 
3209 #ifdef KVM_HAVE_MCE_INJECTION
3210         if (unlikely(have_sigbus_pending)) {
3211             bql_lock();
3212             kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
3213                                     pending_sigbus_addr);
3214             have_sigbus_pending = false;
3215             bql_unlock();
3216         }
3217 #endif
3218 
3219         if (run_ret < 0) {
3220             if (run_ret == -EINTR || run_ret == -EAGAIN) {
3221                 trace_kvm_io_window_exit();
3222                 kvm_eat_signals(cpu);
3223                 ret = EXCP_INTERRUPT;
3224                 break;
3225             }
3226             if (!(run_ret == -EFAULT && run->exit_reason == KVM_EXIT_MEMORY_FAULT)) {
3227                 fprintf(stderr, "error: kvm run failed %s\n",
3228                         strerror(-run_ret));
3229 #ifdef TARGET_PPC
3230                 if (run_ret == -EBUSY) {
3231                     fprintf(stderr,
3232                             "This is probably because your SMT is enabled.\n"
3233                             "VCPU can only run on primary threads with all "
3234                             "secondary threads offline.\n");
3235                 }
3236 #endif
3237                 ret = -1;
3238                 break;
3239             }
3240         }
3241 
3242         trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
3243         switch (run->exit_reason) {
3244         case KVM_EXIT_IO:
3245             /* Called outside BQL */
3246             kvm_handle_io(run->io.port, attrs,
3247                           (uint8_t *)run + run->io.data_offset,
3248                           run->io.direction,
3249                           run->io.size,
3250                           run->io.count);
3251             ret = 0;
3252             break;
3253         case KVM_EXIT_MMIO:
3254             /* Called outside BQL */
3255             address_space_rw(&address_space_memory,
3256                              run->mmio.phys_addr, attrs,
3257                              run->mmio.data,
3258                              run->mmio.len,
3259                              run->mmio.is_write);
3260             ret = 0;
3261             break;
3262         case KVM_EXIT_IRQ_WINDOW_OPEN:
3263             ret = EXCP_INTERRUPT;
3264             break;
3265         case KVM_EXIT_SHUTDOWN:
3266             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
3267             ret = EXCP_INTERRUPT;
3268             break;
3269         case KVM_EXIT_UNKNOWN:
3270             fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
3271                     (uint64_t)run->hw.hardware_exit_reason);
3272             ret = -1;
3273             break;
3274         case KVM_EXIT_INTERNAL_ERROR:
3275             ret = kvm_handle_internal_error(cpu, run);
3276             break;
3277         case KVM_EXIT_DIRTY_RING_FULL:
3278             /*
3279              * We shouldn't continue if the dirty ring of this vcpu is
3280              * still full.  Got kicked by KVM_RESET_DIRTY_RINGS.
3281              */
3282             trace_kvm_dirty_ring_full(cpu->cpu_index);
3283             bql_lock();
3284             /*
3285              * We throttle vCPU by making it sleep once it exit from kernel
3286              * due to dirty ring full. In the dirtylimit scenario, reaping
3287              * all vCPUs after a single vCPU dirty ring get full result in
3288              * the miss of sleep, so just reap the ring-fulled vCPU.
3289              */
3290             if (dirtylimit_in_service()) {
3291                 kvm_dirty_ring_reap(kvm_state, cpu);
3292             } else {
3293                 kvm_dirty_ring_reap(kvm_state, NULL);
3294             }
3295             bql_unlock();
3296             dirtylimit_vcpu_execute(cpu);
3297             ret = 0;
3298             break;
3299         case KVM_EXIT_SYSTEM_EVENT:
3300             trace_kvm_run_exit_system_event(cpu->cpu_index, run->system_event.type);
3301             switch (run->system_event.type) {
3302             case KVM_SYSTEM_EVENT_SHUTDOWN:
3303                 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
3304                 ret = EXCP_INTERRUPT;
3305                 break;
3306             case KVM_SYSTEM_EVENT_RESET:
3307                 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
3308                 ret = EXCP_INTERRUPT;
3309                 break;
3310             case KVM_SYSTEM_EVENT_CRASH:
3311                 kvm_cpu_synchronize_state(cpu);
3312                 bql_lock();
3313                 qemu_system_guest_panicked(cpu_get_crash_info(cpu));
3314                 bql_unlock();
3315                 ret = 0;
3316                 break;
3317             default:
3318                 ret = kvm_arch_handle_exit(cpu, run);
3319                 break;
3320             }
3321             break;
3322         case KVM_EXIT_MEMORY_FAULT:
3323             trace_kvm_memory_fault(run->memory_fault.gpa,
3324                                    run->memory_fault.size,
3325                                    run->memory_fault.flags);
3326             if (run->memory_fault.flags & ~KVM_MEMORY_EXIT_FLAG_PRIVATE) {
3327                 error_report("KVM_EXIT_MEMORY_FAULT: Unknown flag 0x%" PRIx64,
3328                              (uint64_t)run->memory_fault.flags);
3329                 ret = -1;
3330                 break;
3331             }
3332             ret = kvm_convert_memory(run->memory_fault.gpa, run->memory_fault.size,
3333                                      run->memory_fault.flags & KVM_MEMORY_EXIT_FLAG_PRIVATE);
3334             break;
3335         default:
3336             ret = kvm_arch_handle_exit(cpu, run);
3337             break;
3338         }
3339     } while (ret == 0);
3340 
3341     cpu_exec_end(cpu);
3342     bql_lock();
3343 
3344     if (ret < 0) {
3345         cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
3346         vm_stop(RUN_STATE_INTERNAL_ERROR);
3347     }
3348 
3349     qatomic_set(&cpu->exit_request, 0);
3350     return ret;
3351 }
3352 
kvm_ioctl(KVMState * s,unsigned long type,...)3353 int kvm_ioctl(KVMState *s, unsigned long type, ...)
3354 {
3355     int ret;
3356     void *arg;
3357     va_list ap;
3358 
3359     va_start(ap, type);
3360     arg = va_arg(ap, void *);
3361     va_end(ap);
3362 
3363     trace_kvm_ioctl(type, arg);
3364     ret = ioctl(s->fd, type, arg);
3365     if (ret == -1) {
3366         ret = -errno;
3367     }
3368     return ret;
3369 }
3370 
kvm_vm_ioctl(KVMState * s,unsigned long type,...)3371 int kvm_vm_ioctl(KVMState *s, unsigned long type, ...)
3372 {
3373     int ret;
3374     void *arg;
3375     va_list ap;
3376 
3377     va_start(ap, type);
3378     arg = va_arg(ap, void *);
3379     va_end(ap);
3380 
3381     trace_kvm_vm_ioctl(type, arg);
3382     accel_ioctl_begin();
3383     ret = ioctl(s->vmfd, type, arg);
3384     accel_ioctl_end();
3385     if (ret == -1) {
3386         ret = -errno;
3387     }
3388     return ret;
3389 }
3390 
kvm_vcpu_ioctl(CPUState * cpu,unsigned long type,...)3391 int kvm_vcpu_ioctl(CPUState *cpu, unsigned long type, ...)
3392 {
3393     int ret;
3394     void *arg;
3395     va_list ap;
3396 
3397     va_start(ap, type);
3398     arg = va_arg(ap, void *);
3399     va_end(ap);
3400 
3401     trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
3402     accel_cpu_ioctl_begin(cpu);
3403     ret = ioctl(cpu->kvm_fd, type, arg);
3404     accel_cpu_ioctl_end(cpu);
3405     if (ret == -1) {
3406         ret = -errno;
3407     }
3408     return ret;
3409 }
3410 
kvm_device_ioctl(int fd,unsigned long type,...)3411 int kvm_device_ioctl(int fd, unsigned long type, ...)
3412 {
3413     int ret;
3414     void *arg;
3415     va_list ap;
3416 
3417     va_start(ap, type);
3418     arg = va_arg(ap, void *);
3419     va_end(ap);
3420 
3421     trace_kvm_device_ioctl(fd, type, arg);
3422     accel_ioctl_begin();
3423     ret = ioctl(fd, type, arg);
3424     accel_ioctl_end();
3425     if (ret == -1) {
3426         ret = -errno;
3427     }
3428     return ret;
3429 }
3430 
kvm_vm_check_attr(KVMState * s,uint32_t group,uint64_t attr)3431 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
3432 {
3433     int ret;
3434     struct kvm_device_attr attribute = {
3435         .group = group,
3436         .attr = attr,
3437     };
3438 
3439     if (!kvm_vm_attributes_allowed) {
3440         return 0;
3441     }
3442 
3443     ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
3444     /* kvm returns 0 on success for HAS_DEVICE_ATTR */
3445     return ret ? 0 : 1;
3446 }
3447 
kvm_device_check_attr(int dev_fd,uint32_t group,uint64_t attr)3448 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
3449 {
3450     struct kvm_device_attr attribute = {
3451         .group = group,
3452         .attr = attr,
3453         .flags = 0,
3454     };
3455 
3456     return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
3457 }
3458 
kvm_device_access(int fd,int group,uint64_t attr,void * val,bool write,Error ** errp)3459 int kvm_device_access(int fd, int group, uint64_t attr,
3460                       void *val, bool write, Error **errp)
3461 {
3462     struct kvm_device_attr kvmattr;
3463     int err;
3464 
3465     kvmattr.flags = 0;
3466     kvmattr.group = group;
3467     kvmattr.attr = attr;
3468     kvmattr.addr = (uintptr_t)val;
3469 
3470     err = kvm_device_ioctl(fd,
3471                            write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
3472                            &kvmattr);
3473     if (err < 0) {
3474         error_setg_errno(errp, -err,
3475                          "KVM_%s_DEVICE_ATTR failed: Group %d "
3476                          "attr 0x%016" PRIx64,
3477                          write ? "SET" : "GET", group, attr);
3478     }
3479     return err;
3480 }
3481 
kvm_has_sync_mmu(void)3482 bool kvm_has_sync_mmu(void)
3483 {
3484     return kvm_state->sync_mmu;
3485 }
3486 
kvm_has_vcpu_events(void)3487 int kvm_has_vcpu_events(void)
3488 {
3489     return kvm_state->vcpu_events;
3490 }
3491 
kvm_max_nested_state_length(void)3492 int kvm_max_nested_state_length(void)
3493 {
3494     return kvm_state->max_nested_state_len;
3495 }
3496 
kvm_has_gsi_routing(void)3497 int kvm_has_gsi_routing(void)
3498 {
3499 #ifdef KVM_CAP_IRQ_ROUTING
3500     return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
3501 #else
3502     return false;
3503 #endif
3504 }
3505 
kvm_arm_supports_user_irq(void)3506 bool kvm_arm_supports_user_irq(void)
3507 {
3508     return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
3509 }
3510 
3511 #ifdef TARGET_KVM_HAVE_GUEST_DEBUG
kvm_find_sw_breakpoint(CPUState * cpu,vaddr pc)3512 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu, vaddr pc)
3513 {
3514     struct kvm_sw_breakpoint *bp;
3515 
3516     QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
3517         if (bp->pc == pc) {
3518             return bp;
3519         }
3520     }
3521     return NULL;
3522 }
3523 
kvm_sw_breakpoints_active(CPUState * cpu)3524 int kvm_sw_breakpoints_active(CPUState *cpu)
3525 {
3526     return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
3527 }
3528 
3529 struct kvm_set_guest_debug_data {
3530     struct kvm_guest_debug dbg;
3531     int err;
3532 };
3533 
kvm_invoke_set_guest_debug(CPUState * cpu,run_on_cpu_data data)3534 static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
3535 {
3536     struct kvm_set_guest_debug_data *dbg_data =
3537         (struct kvm_set_guest_debug_data *) data.host_ptr;
3538 
3539     dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
3540                                    &dbg_data->dbg);
3541 }
3542 
kvm_update_guest_debug(CPUState * cpu,unsigned long reinject_trap)3543 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
3544 {
3545     struct kvm_set_guest_debug_data data;
3546 
3547     data.dbg.control = reinject_trap;
3548 
3549     if (cpu->singlestep_enabled) {
3550         data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
3551 
3552         if (cpu->singlestep_enabled & SSTEP_NOIRQ) {
3553             data.dbg.control |= KVM_GUESTDBG_BLOCKIRQ;
3554         }
3555     }
3556     kvm_arch_update_guest_debug(cpu, &data.dbg);
3557 
3558     run_on_cpu(cpu, kvm_invoke_set_guest_debug,
3559                RUN_ON_CPU_HOST_PTR(&data));
3560     return data.err;
3561 }
3562 
kvm_supports_guest_debug(void)3563 bool kvm_supports_guest_debug(void)
3564 {
3565     /* probed during kvm_init() */
3566     return kvm_has_guest_debug;
3567 }
3568 
kvm_insert_breakpoint(CPUState * cpu,int type,vaddr addr,vaddr len)3569 int kvm_insert_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
3570 {
3571     struct kvm_sw_breakpoint *bp;
3572     int err;
3573 
3574     if (type == GDB_BREAKPOINT_SW) {
3575         bp = kvm_find_sw_breakpoint(cpu, addr);
3576         if (bp) {
3577             bp->use_count++;
3578             return 0;
3579         }
3580 
3581         bp = g_new(struct kvm_sw_breakpoint, 1);
3582         bp->pc = addr;
3583         bp->use_count = 1;
3584         err = kvm_arch_insert_sw_breakpoint(cpu, bp);
3585         if (err) {
3586             g_free(bp);
3587             return err;
3588         }
3589 
3590         QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
3591     } else {
3592         err = kvm_arch_insert_hw_breakpoint(addr, len, type);
3593         if (err) {
3594             return err;
3595         }
3596     }
3597 
3598     CPU_FOREACH(cpu) {
3599         err = kvm_update_guest_debug(cpu, 0);
3600         if (err) {
3601             return err;
3602         }
3603     }
3604     return 0;
3605 }
3606 
kvm_remove_breakpoint(CPUState * cpu,int type,vaddr addr,vaddr len)3607 int kvm_remove_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
3608 {
3609     struct kvm_sw_breakpoint *bp;
3610     int err;
3611 
3612     if (type == GDB_BREAKPOINT_SW) {
3613         bp = kvm_find_sw_breakpoint(cpu, addr);
3614         if (!bp) {
3615             return -ENOENT;
3616         }
3617 
3618         if (bp->use_count > 1) {
3619             bp->use_count--;
3620             return 0;
3621         }
3622 
3623         err = kvm_arch_remove_sw_breakpoint(cpu, bp);
3624         if (err) {
3625             return err;
3626         }
3627 
3628         QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
3629         g_free(bp);
3630     } else {
3631         err = kvm_arch_remove_hw_breakpoint(addr, len, type);
3632         if (err) {
3633             return err;
3634         }
3635     }
3636 
3637     CPU_FOREACH(cpu) {
3638         err = kvm_update_guest_debug(cpu, 0);
3639         if (err) {
3640             return err;
3641         }
3642     }
3643     return 0;
3644 }
3645 
kvm_remove_all_breakpoints(CPUState * cpu)3646 void kvm_remove_all_breakpoints(CPUState *cpu)
3647 {
3648     struct kvm_sw_breakpoint *bp, *next;
3649     KVMState *s = cpu->kvm_state;
3650     CPUState *tmpcpu;
3651 
3652     QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
3653         if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
3654             /* Try harder to find a CPU that currently sees the breakpoint. */
3655             CPU_FOREACH(tmpcpu) {
3656                 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
3657                     break;
3658                 }
3659             }
3660         }
3661         QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
3662         g_free(bp);
3663     }
3664     kvm_arch_remove_all_hw_breakpoints();
3665 
3666     CPU_FOREACH(cpu) {
3667         kvm_update_guest_debug(cpu, 0);
3668     }
3669 }
3670 
3671 #endif /* !TARGET_KVM_HAVE_GUEST_DEBUG */
3672 
kvm_set_signal_mask(CPUState * cpu,const sigset_t * sigset)3673 static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
3674 {
3675     KVMState *s = kvm_state;
3676     struct kvm_signal_mask *sigmask;
3677     int r;
3678 
3679     sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
3680 
3681     sigmask->len = s->sigmask_len;
3682     memcpy(sigmask->sigset, sigset, sizeof(*sigset));
3683     r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
3684     g_free(sigmask);
3685 
3686     return r;
3687 }
3688 
kvm_ipi_signal(int sig)3689 static void kvm_ipi_signal(int sig)
3690 {
3691     if (current_cpu) {
3692         assert(kvm_immediate_exit);
3693         kvm_cpu_kick(current_cpu);
3694     }
3695 }
3696 
kvm_init_cpu_signals(CPUState * cpu)3697 void kvm_init_cpu_signals(CPUState *cpu)
3698 {
3699     int r;
3700     sigset_t set;
3701     struct sigaction sigact;
3702 
3703     memset(&sigact, 0, sizeof(sigact));
3704     sigact.sa_handler = kvm_ipi_signal;
3705     sigaction(SIG_IPI, &sigact, NULL);
3706 
3707     pthread_sigmask(SIG_BLOCK, NULL, &set);
3708 #if defined KVM_HAVE_MCE_INJECTION
3709     sigdelset(&set, SIGBUS);
3710     pthread_sigmask(SIG_SETMASK, &set, NULL);
3711 #endif
3712     sigdelset(&set, SIG_IPI);
3713     if (kvm_immediate_exit) {
3714         r = pthread_sigmask(SIG_SETMASK, &set, NULL);
3715     } else {
3716         r = kvm_set_signal_mask(cpu, &set);
3717     }
3718     if (r) {
3719         fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
3720         exit(1);
3721     }
3722 }
3723 
3724 /* Called asynchronously in VCPU thread.  */
kvm_on_sigbus_vcpu(CPUState * cpu,int code,void * addr)3725 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
3726 {
3727 #ifdef KVM_HAVE_MCE_INJECTION
3728     if (have_sigbus_pending) {
3729         return 1;
3730     }
3731     have_sigbus_pending = true;
3732     pending_sigbus_addr = addr;
3733     pending_sigbus_code = code;
3734     qatomic_set(&cpu->exit_request, 1);
3735     return 0;
3736 #else
3737     return 1;
3738 #endif
3739 }
3740 
3741 /* Called synchronously (via signalfd) in main thread.  */
kvm_on_sigbus(int code,void * addr)3742 int kvm_on_sigbus(int code, void *addr)
3743 {
3744 #ifdef KVM_HAVE_MCE_INJECTION
3745     /* Action required MCE kills the process if SIGBUS is blocked.  Because
3746      * that's what happens in the I/O thread, where we handle MCE via signalfd,
3747      * we can only get action optional here.
3748      */
3749     assert(code != BUS_MCEERR_AR);
3750     kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
3751     return 0;
3752 #else
3753     return 1;
3754 #endif
3755 }
3756 
kvm_create_device(KVMState * s,uint64_t type,bool test)3757 int kvm_create_device(KVMState *s, uint64_t type, bool test)
3758 {
3759     int ret;
3760     struct kvm_create_device create_dev;
3761 
3762     create_dev.type = type;
3763     create_dev.fd = -1;
3764     create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
3765 
3766     if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
3767         return -ENOTSUP;
3768     }
3769 
3770     ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
3771     if (ret) {
3772         return ret;
3773     }
3774 
3775     return test ? 0 : create_dev.fd;
3776 }
3777 
kvm_device_supported(int vmfd,uint64_t type)3778 bool kvm_device_supported(int vmfd, uint64_t type)
3779 {
3780     struct kvm_create_device create_dev = {
3781         .type = type,
3782         .fd = -1,
3783         .flags = KVM_CREATE_DEVICE_TEST,
3784     };
3785 
3786     if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
3787         return false;
3788     }
3789 
3790     return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
3791 }
3792 
kvm_set_one_reg(CPUState * cs,uint64_t id,void * source)3793 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
3794 {
3795     struct kvm_one_reg reg;
3796     int r;
3797 
3798     reg.id = id;
3799     reg.addr = (uintptr_t) source;
3800     r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
3801     if (r) {
3802         trace_kvm_failed_reg_set(id, strerror(-r));
3803     }
3804     return r;
3805 }
3806 
kvm_get_one_reg(CPUState * cs,uint64_t id,void * target)3807 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
3808 {
3809     struct kvm_one_reg reg;
3810     int r;
3811 
3812     reg.id = id;
3813     reg.addr = (uintptr_t) target;
3814     r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
3815     if (r) {
3816         trace_kvm_failed_reg_get(id, strerror(-r));
3817     }
3818     return r;
3819 }
3820 
kvm_accel_has_memory(AccelState * accel,AddressSpace * as,hwaddr start_addr,hwaddr size)3821 static bool kvm_accel_has_memory(AccelState *accel, AddressSpace *as,
3822                                  hwaddr start_addr, hwaddr size)
3823 {
3824     KVMState *kvm = KVM_STATE(accel);
3825     int i;
3826 
3827     for (i = 0; i < kvm->nr_as; ++i) {
3828         if (kvm->as[i].as == as && kvm->as[i].ml) {
3829             size = MIN(kvm_max_slot_size, size);
3830             return NULL != kvm_lookup_matching_slot(kvm->as[i].ml,
3831                                                     start_addr, size);
3832         }
3833     }
3834 
3835     return false;
3836 }
3837 
kvm_get_kvm_shadow_mem(Object * obj,Visitor * v,const char * name,void * opaque,Error ** errp)3838 static void kvm_get_kvm_shadow_mem(Object *obj, Visitor *v,
3839                                    const char *name, void *opaque,
3840                                    Error **errp)
3841 {
3842     KVMState *s = KVM_STATE(obj);
3843     int64_t value = s->kvm_shadow_mem;
3844 
3845     visit_type_int(v, name, &value, errp);
3846 }
3847 
kvm_set_kvm_shadow_mem(Object * obj,Visitor * v,const char * name,void * opaque,Error ** errp)3848 static void kvm_set_kvm_shadow_mem(Object *obj, Visitor *v,
3849                                    const char *name, void *opaque,
3850                                    Error **errp)
3851 {
3852     KVMState *s = KVM_STATE(obj);
3853     int64_t value;
3854 
3855     if (s->fd != -1) {
3856         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3857         return;
3858     }
3859 
3860     if (!visit_type_int(v, name, &value, errp)) {
3861         return;
3862     }
3863 
3864     s->kvm_shadow_mem = value;
3865 }
3866 
kvm_set_kernel_irqchip(Object * obj,Visitor * v,const char * name,void * opaque,Error ** errp)3867 static void kvm_set_kernel_irqchip(Object *obj, Visitor *v,
3868                                    const char *name, void *opaque,
3869                                    Error **errp)
3870 {
3871     KVMState *s = KVM_STATE(obj);
3872     OnOffSplit mode;
3873 
3874     if (s->fd != -1) {
3875         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3876         return;
3877     }
3878 
3879     if (!visit_type_OnOffSplit(v, name, &mode, errp)) {
3880         return;
3881     }
3882     switch (mode) {
3883     case ON_OFF_SPLIT_ON:
3884         s->kernel_irqchip_allowed = true;
3885         s->kernel_irqchip_required = true;
3886         s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3887         break;
3888     case ON_OFF_SPLIT_OFF:
3889         s->kernel_irqchip_allowed = false;
3890         s->kernel_irqchip_required = false;
3891         s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3892         break;
3893     case ON_OFF_SPLIT_SPLIT:
3894         s->kernel_irqchip_allowed = true;
3895         s->kernel_irqchip_required = true;
3896         s->kernel_irqchip_split = ON_OFF_AUTO_ON;
3897         break;
3898     default:
3899         /* The value was checked in visit_type_OnOffSplit() above. If
3900          * we get here, then something is wrong in QEMU.
3901          */
3902         abort();
3903     }
3904 }
3905 
kvm_kernel_irqchip_allowed(void)3906 bool kvm_kernel_irqchip_allowed(void)
3907 {
3908     return kvm_state->kernel_irqchip_allowed;
3909 }
3910 
kvm_kernel_irqchip_required(void)3911 bool kvm_kernel_irqchip_required(void)
3912 {
3913     return kvm_state->kernel_irqchip_required;
3914 }
3915 
kvm_kernel_irqchip_split(void)3916 bool kvm_kernel_irqchip_split(void)
3917 {
3918     return kvm_state->kernel_irqchip_split == ON_OFF_AUTO_ON;
3919 }
3920 
kvm_get_dirty_ring_size(Object * obj,Visitor * v,const char * name,void * opaque,Error ** errp)3921 static void kvm_get_dirty_ring_size(Object *obj, Visitor *v,
3922                                     const char *name, void *opaque,
3923                                     Error **errp)
3924 {
3925     KVMState *s = KVM_STATE(obj);
3926     uint32_t value = s->kvm_dirty_ring_size;
3927 
3928     visit_type_uint32(v, name, &value, errp);
3929 }
3930 
kvm_set_dirty_ring_size(Object * obj,Visitor * v,const char * name,void * opaque,Error ** errp)3931 static void kvm_set_dirty_ring_size(Object *obj, Visitor *v,
3932                                     const char *name, void *opaque,
3933                                     Error **errp)
3934 {
3935     KVMState *s = KVM_STATE(obj);
3936     uint32_t value;
3937 
3938     if (s->fd != -1) {
3939         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3940         return;
3941     }
3942 
3943     if (!visit_type_uint32(v, name, &value, errp)) {
3944         return;
3945     }
3946     if (value & (value - 1)) {
3947         error_setg(errp, "dirty-ring-size must be a power of two.");
3948         return;
3949     }
3950 
3951     s->kvm_dirty_ring_size = value;
3952 }
3953 
kvm_get_device(Object * obj,Error ** errp G_GNUC_UNUSED)3954 static char *kvm_get_device(Object *obj,
3955                             Error **errp G_GNUC_UNUSED)
3956 {
3957     KVMState *s = KVM_STATE(obj);
3958 
3959     return g_strdup(s->device);
3960 }
3961 
kvm_set_device(Object * obj,const char * value,Error ** errp G_GNUC_UNUSED)3962 static void kvm_set_device(Object *obj,
3963                            const char *value,
3964                            Error **errp G_GNUC_UNUSED)
3965 {
3966     KVMState *s = KVM_STATE(obj);
3967 
3968     g_free(s->device);
3969     s->device = g_strdup(value);
3970 }
3971 
kvm_set_kvm_rapl(Object * obj,bool value,Error ** errp)3972 static void kvm_set_kvm_rapl(Object *obj, bool value, Error **errp)
3973 {
3974     KVMState *s = KVM_STATE(obj);
3975     s->msr_energy.enable = value;
3976 }
3977 
kvm_set_kvm_rapl_socket_path(Object * obj,const char * str,Error ** errp)3978 static void kvm_set_kvm_rapl_socket_path(Object *obj,
3979                                          const char *str,
3980                                          Error **errp)
3981 {
3982     KVMState *s = KVM_STATE(obj);
3983     g_free(s->msr_energy.socket_path);
3984     s->msr_energy.socket_path = g_strdup(str);
3985 }
3986 
kvm_accel_instance_init(Object * obj)3987 static void kvm_accel_instance_init(Object *obj)
3988 {
3989     KVMState *s = KVM_STATE(obj);
3990 
3991     s->fd = -1;
3992     s->vmfd = -1;
3993     s->kvm_shadow_mem = -1;
3994     s->kernel_irqchip_allowed = true;
3995     s->kernel_irqchip_split = ON_OFF_AUTO_AUTO;
3996     /* KVM dirty ring is by default off */
3997     s->kvm_dirty_ring_size = 0;
3998     s->kvm_dirty_ring_with_bitmap = false;
3999     s->kvm_eager_split_size = 0;
4000     s->notify_vmexit = NOTIFY_VMEXIT_OPTION_RUN;
4001     s->notify_window = 0;
4002     s->xen_version = 0;
4003     s->xen_gnttab_max_frames = 64;
4004     s->xen_evtchn_max_pirq = 256;
4005     s->device = NULL;
4006     s->msr_energy.enable = false;
4007 }
4008 
4009 /**
4010  * kvm_gdbstub_sstep_flags():
4011  *
4012  * Returns: SSTEP_* flags that KVM supports for guest debug. The
4013  * support is probed during kvm_init()
4014  */
kvm_gdbstub_sstep_flags(AccelState * as)4015 static int kvm_gdbstub_sstep_flags(AccelState *as)
4016 {
4017     return kvm_sstep_flags;
4018 }
4019 
kvm_accel_class_init(ObjectClass * oc,const void * data)4020 static void kvm_accel_class_init(ObjectClass *oc, const void *data)
4021 {
4022     AccelClass *ac = ACCEL_CLASS(oc);
4023     ac->name = "KVM";
4024     ac->init_machine = kvm_init;
4025     ac->has_memory = kvm_accel_has_memory;
4026     ac->allowed = &kvm_allowed;
4027     ac->gdbstub_supported_sstep_flags = kvm_gdbstub_sstep_flags;
4028 
4029     object_class_property_add(oc, "kernel-irqchip", "on|off|split",
4030         NULL, kvm_set_kernel_irqchip,
4031         NULL, NULL);
4032     object_class_property_set_description(oc, "kernel-irqchip",
4033         "Configure KVM in-kernel irqchip");
4034 
4035     object_class_property_add(oc, "kvm-shadow-mem", "int",
4036         kvm_get_kvm_shadow_mem, kvm_set_kvm_shadow_mem,
4037         NULL, NULL);
4038     object_class_property_set_description(oc, "kvm-shadow-mem",
4039         "KVM shadow MMU size");
4040 
4041     object_class_property_add(oc, "dirty-ring-size", "uint32",
4042         kvm_get_dirty_ring_size, kvm_set_dirty_ring_size,
4043         NULL, NULL);
4044     object_class_property_set_description(oc, "dirty-ring-size",
4045         "Size of KVM dirty page ring buffer (default: 0, i.e. use bitmap)");
4046 
4047     object_class_property_add_str(oc, "device", kvm_get_device, kvm_set_device);
4048     object_class_property_set_description(oc, "device",
4049         "Path to the device node to use (default: /dev/kvm)");
4050 
4051     object_class_property_add_bool(oc, "rapl",
4052                                    NULL,
4053                                    kvm_set_kvm_rapl);
4054     object_class_property_set_description(oc, "rapl",
4055         "Allow energy related MSRs for RAPL interface in Guest");
4056 
4057     object_class_property_add_str(oc, "rapl-helper-socket", NULL,
4058                                   kvm_set_kvm_rapl_socket_path);
4059     object_class_property_set_description(oc, "rapl-helper-socket",
4060         "Socket Path for comminucating with the Virtual MSR helper daemon");
4061 
4062     kvm_arch_accel_class_init(oc);
4063 }
4064 
4065 static const TypeInfo kvm_accel_type = {
4066     .name = TYPE_KVM_ACCEL,
4067     .parent = TYPE_ACCEL,
4068     .instance_init = kvm_accel_instance_init,
4069     .class_init = kvm_accel_class_init,
4070     .instance_size = sizeof(KVMState),
4071 };
4072 
kvm_type_init(void)4073 static void kvm_type_init(void)
4074 {
4075     type_register_static(&kvm_accel_type);
4076 }
4077 
4078 type_init(kvm_type_init);
4079 
4080 typedef struct StatsArgs {
4081     union StatsResultsType {
4082         StatsResultList **stats;
4083         StatsSchemaList **schema;
4084     } result;
4085     strList *names;
4086     Error **errp;
4087 } StatsArgs;
4088 
add_kvmstat_entry(struct kvm_stats_desc * pdesc,uint64_t * stats_data,StatsList * stats_list,Error ** errp)4089 static StatsList *add_kvmstat_entry(struct kvm_stats_desc *pdesc,
4090                                     uint64_t *stats_data,
4091                                     StatsList *stats_list,
4092                                     Error **errp)
4093 {
4094 
4095     Stats *stats;
4096     uint64List *val_list = NULL;
4097 
4098     /* Only add stats that we understand.  */
4099     switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
4100     case KVM_STATS_TYPE_CUMULATIVE:
4101     case KVM_STATS_TYPE_INSTANT:
4102     case KVM_STATS_TYPE_PEAK:
4103     case KVM_STATS_TYPE_LINEAR_HIST:
4104     case KVM_STATS_TYPE_LOG_HIST:
4105         break;
4106     default:
4107         return stats_list;
4108     }
4109 
4110     switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
4111     case KVM_STATS_UNIT_NONE:
4112     case KVM_STATS_UNIT_BYTES:
4113     case KVM_STATS_UNIT_CYCLES:
4114     case KVM_STATS_UNIT_SECONDS:
4115     case KVM_STATS_UNIT_BOOLEAN:
4116         break;
4117     default:
4118         return stats_list;
4119     }
4120 
4121     switch (pdesc->flags & KVM_STATS_BASE_MASK) {
4122     case KVM_STATS_BASE_POW10:
4123     case KVM_STATS_BASE_POW2:
4124         break;
4125     default:
4126         return stats_list;
4127     }
4128 
4129     /* Alloc and populate data list */
4130     stats = g_new0(Stats, 1);
4131     stats->name = g_strdup(pdesc->name);
4132     stats->value = g_new0(StatsValue, 1);
4133 
4134     if ((pdesc->flags & KVM_STATS_UNIT_MASK) == KVM_STATS_UNIT_BOOLEAN) {
4135         stats->value->u.boolean = *stats_data;
4136         stats->value->type = QTYPE_QBOOL;
4137     } else if (pdesc->size == 1) {
4138         stats->value->u.scalar = *stats_data;
4139         stats->value->type = QTYPE_QNUM;
4140     } else {
4141         int i;
4142         for (i = 0; i < pdesc->size; i++) {
4143             QAPI_LIST_PREPEND(val_list, stats_data[i]);
4144         }
4145         stats->value->u.list = val_list;
4146         stats->value->type = QTYPE_QLIST;
4147     }
4148 
4149     QAPI_LIST_PREPEND(stats_list, stats);
4150     return stats_list;
4151 }
4152 
add_kvmschema_entry(struct kvm_stats_desc * pdesc,StatsSchemaValueList * list,Error ** errp)4153 static StatsSchemaValueList *add_kvmschema_entry(struct kvm_stats_desc *pdesc,
4154                                                  StatsSchemaValueList *list,
4155                                                  Error **errp)
4156 {
4157     StatsSchemaValueList *schema_entry = g_new0(StatsSchemaValueList, 1);
4158     schema_entry->value = g_new0(StatsSchemaValue, 1);
4159 
4160     switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
4161     case KVM_STATS_TYPE_CUMULATIVE:
4162         schema_entry->value->type = STATS_TYPE_CUMULATIVE;
4163         break;
4164     case KVM_STATS_TYPE_INSTANT:
4165         schema_entry->value->type = STATS_TYPE_INSTANT;
4166         break;
4167     case KVM_STATS_TYPE_PEAK:
4168         schema_entry->value->type = STATS_TYPE_PEAK;
4169         break;
4170     case KVM_STATS_TYPE_LINEAR_HIST:
4171         schema_entry->value->type = STATS_TYPE_LINEAR_HISTOGRAM;
4172         schema_entry->value->bucket_size = pdesc->bucket_size;
4173         schema_entry->value->has_bucket_size = true;
4174         break;
4175     case KVM_STATS_TYPE_LOG_HIST:
4176         schema_entry->value->type = STATS_TYPE_LOG2_HISTOGRAM;
4177         break;
4178     default:
4179         goto exit;
4180     }
4181 
4182     switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
4183     case KVM_STATS_UNIT_NONE:
4184         break;
4185     case KVM_STATS_UNIT_BOOLEAN:
4186         schema_entry->value->has_unit = true;
4187         schema_entry->value->unit = STATS_UNIT_BOOLEAN;
4188         break;
4189     case KVM_STATS_UNIT_BYTES:
4190         schema_entry->value->has_unit = true;
4191         schema_entry->value->unit = STATS_UNIT_BYTES;
4192         break;
4193     case KVM_STATS_UNIT_CYCLES:
4194         schema_entry->value->has_unit = true;
4195         schema_entry->value->unit = STATS_UNIT_CYCLES;
4196         break;
4197     case KVM_STATS_UNIT_SECONDS:
4198         schema_entry->value->has_unit = true;
4199         schema_entry->value->unit = STATS_UNIT_SECONDS;
4200         break;
4201     default:
4202         goto exit;
4203     }
4204 
4205     schema_entry->value->exponent = pdesc->exponent;
4206     if (pdesc->exponent) {
4207         switch (pdesc->flags & KVM_STATS_BASE_MASK) {
4208         case KVM_STATS_BASE_POW10:
4209             schema_entry->value->has_base = true;
4210             schema_entry->value->base = 10;
4211             break;
4212         case KVM_STATS_BASE_POW2:
4213             schema_entry->value->has_base = true;
4214             schema_entry->value->base = 2;
4215             break;
4216         default:
4217             goto exit;
4218         }
4219     }
4220 
4221     schema_entry->value->name = g_strdup(pdesc->name);
4222     schema_entry->next = list;
4223     return schema_entry;
4224 exit:
4225     g_free(schema_entry->value);
4226     g_free(schema_entry);
4227     return list;
4228 }
4229 
4230 /* Cached stats descriptors */
4231 typedef struct StatsDescriptors {
4232     const char *ident; /* cache key, currently the StatsTarget */
4233     struct kvm_stats_desc *kvm_stats_desc;
4234     struct kvm_stats_header kvm_stats_header;
4235     QTAILQ_ENTRY(StatsDescriptors) next;
4236 } StatsDescriptors;
4237 
4238 static QTAILQ_HEAD(, StatsDescriptors) stats_descriptors =
4239     QTAILQ_HEAD_INITIALIZER(stats_descriptors);
4240 
4241 /*
4242  * Return the descriptors for 'target', that either have already been read
4243  * or are retrieved from 'stats_fd'.
4244  */
find_stats_descriptors(StatsTarget target,int stats_fd,Error ** errp)4245 static StatsDescriptors *find_stats_descriptors(StatsTarget target, int stats_fd,
4246                                                 Error **errp)
4247 {
4248     StatsDescriptors *descriptors;
4249     const char *ident;
4250     struct kvm_stats_desc *kvm_stats_desc;
4251     struct kvm_stats_header *kvm_stats_header;
4252     size_t size_desc;
4253     ssize_t ret;
4254 
4255     ident = StatsTarget_str(target);
4256     QTAILQ_FOREACH(descriptors, &stats_descriptors, next) {
4257         if (g_str_equal(descriptors->ident, ident)) {
4258             return descriptors;
4259         }
4260     }
4261 
4262     descriptors = g_new0(StatsDescriptors, 1);
4263 
4264     /* Read stats header */
4265     kvm_stats_header = &descriptors->kvm_stats_header;
4266     ret = pread(stats_fd, kvm_stats_header, sizeof(*kvm_stats_header), 0);
4267     if (ret != sizeof(*kvm_stats_header)) {
4268         error_setg(errp, "KVM stats: failed to read stats header: "
4269                    "expected %zu actual %zu",
4270                    sizeof(*kvm_stats_header), ret);
4271         g_free(descriptors);
4272         return NULL;
4273     }
4274     size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4275 
4276     /* Read stats descriptors */
4277     kvm_stats_desc = g_malloc0_n(kvm_stats_header->num_desc, size_desc);
4278     ret = pread(stats_fd, kvm_stats_desc,
4279                 size_desc * kvm_stats_header->num_desc,
4280                 kvm_stats_header->desc_offset);
4281 
4282     if (ret != size_desc * kvm_stats_header->num_desc) {
4283         error_setg(errp, "KVM stats: failed to read stats descriptors: "
4284                    "expected %zu actual %zu",
4285                    size_desc * kvm_stats_header->num_desc, ret);
4286         g_free(descriptors);
4287         g_free(kvm_stats_desc);
4288         return NULL;
4289     }
4290     descriptors->kvm_stats_desc = kvm_stats_desc;
4291     descriptors->ident = ident;
4292     QTAILQ_INSERT_TAIL(&stats_descriptors, descriptors, next);
4293     return descriptors;
4294 }
4295 
query_stats(StatsResultList ** result,StatsTarget target,strList * names,int stats_fd,CPUState * cpu,Error ** errp)4296 static void query_stats(StatsResultList **result, StatsTarget target,
4297                         strList *names, int stats_fd, CPUState *cpu,
4298                         Error **errp)
4299 {
4300     struct kvm_stats_desc *kvm_stats_desc;
4301     struct kvm_stats_header *kvm_stats_header;
4302     StatsDescriptors *descriptors;
4303     g_autofree uint64_t *stats_data = NULL;
4304     struct kvm_stats_desc *pdesc;
4305     StatsList *stats_list = NULL;
4306     size_t size_desc, size_data = 0;
4307     ssize_t ret;
4308     int i;
4309 
4310     descriptors = find_stats_descriptors(target, stats_fd, errp);
4311     if (!descriptors) {
4312         return;
4313     }
4314 
4315     kvm_stats_header = &descriptors->kvm_stats_header;
4316     kvm_stats_desc = descriptors->kvm_stats_desc;
4317     size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4318 
4319     /* Tally the total data size; read schema data */
4320     for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4321         pdesc = (void *)kvm_stats_desc + i * size_desc;
4322         size_data += pdesc->size * sizeof(*stats_data);
4323     }
4324 
4325     stats_data = g_malloc0(size_data);
4326     ret = pread(stats_fd, stats_data, size_data, kvm_stats_header->data_offset);
4327 
4328     if (ret != size_data) {
4329         error_setg(errp, "KVM stats: failed to read data: "
4330                    "expected %zu actual %zu", size_data, ret);
4331         return;
4332     }
4333 
4334     for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4335         uint64_t *stats;
4336         pdesc = (void *)kvm_stats_desc + i * size_desc;
4337 
4338         /* Add entry to the list */
4339         stats = (void *)stats_data + pdesc->offset;
4340         if (!apply_str_list_filter(pdesc->name, names)) {
4341             continue;
4342         }
4343         stats_list = add_kvmstat_entry(pdesc, stats, stats_list, errp);
4344     }
4345 
4346     if (!stats_list) {
4347         return;
4348     }
4349 
4350     switch (target) {
4351     case STATS_TARGET_VM:
4352         add_stats_entry(result, STATS_PROVIDER_KVM, NULL, stats_list);
4353         break;
4354     case STATS_TARGET_VCPU:
4355         add_stats_entry(result, STATS_PROVIDER_KVM,
4356                         cpu->parent_obj.canonical_path,
4357                         stats_list);
4358         break;
4359     default:
4360         g_assert_not_reached();
4361     }
4362 }
4363 
query_stats_schema(StatsSchemaList ** result,StatsTarget target,int stats_fd,Error ** errp)4364 static void query_stats_schema(StatsSchemaList **result, StatsTarget target,
4365                                int stats_fd, Error **errp)
4366 {
4367     struct kvm_stats_desc *kvm_stats_desc;
4368     struct kvm_stats_header *kvm_stats_header;
4369     StatsDescriptors *descriptors;
4370     struct kvm_stats_desc *pdesc;
4371     StatsSchemaValueList *stats_list = NULL;
4372     size_t size_desc;
4373     int i;
4374 
4375     descriptors = find_stats_descriptors(target, stats_fd, errp);
4376     if (!descriptors) {
4377         return;
4378     }
4379 
4380     kvm_stats_header = &descriptors->kvm_stats_header;
4381     kvm_stats_desc = descriptors->kvm_stats_desc;
4382     size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4383 
4384     /* Tally the total data size; read schema data */
4385     for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4386         pdesc = (void *)kvm_stats_desc + i * size_desc;
4387         stats_list = add_kvmschema_entry(pdesc, stats_list, errp);
4388     }
4389 
4390     add_stats_schema(result, STATS_PROVIDER_KVM, target, stats_list);
4391 }
4392 
query_stats_vcpu(CPUState * cpu,StatsArgs * kvm_stats_args)4393 static void query_stats_vcpu(CPUState *cpu, StatsArgs *kvm_stats_args)
4394 {
4395     int stats_fd = cpu->kvm_vcpu_stats_fd;
4396     Error *local_err = NULL;
4397 
4398     if (stats_fd == -1) {
4399         error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
4400         error_propagate(kvm_stats_args->errp, local_err);
4401         return;
4402     }
4403     query_stats(kvm_stats_args->result.stats, STATS_TARGET_VCPU,
4404                 kvm_stats_args->names, stats_fd, cpu,
4405                 kvm_stats_args->errp);
4406 }
4407 
query_stats_schema_vcpu(CPUState * cpu,StatsArgs * kvm_stats_args)4408 static void query_stats_schema_vcpu(CPUState *cpu, StatsArgs *kvm_stats_args)
4409 {
4410     int stats_fd = cpu->kvm_vcpu_stats_fd;
4411     Error *local_err = NULL;
4412 
4413     if (stats_fd == -1) {
4414         error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
4415         error_propagate(kvm_stats_args->errp, local_err);
4416         return;
4417     }
4418     query_stats_schema(kvm_stats_args->result.schema, STATS_TARGET_VCPU, stats_fd,
4419                        kvm_stats_args->errp);
4420 }
4421 
query_stats_cb(StatsResultList ** result,StatsTarget target,strList * names,strList * targets,Error ** errp)4422 static void query_stats_cb(StatsResultList **result, StatsTarget target,
4423                            strList *names, strList *targets, Error **errp)
4424 {
4425     KVMState *s = kvm_state;
4426     CPUState *cpu;
4427     int stats_fd;
4428 
4429     switch (target) {
4430     case STATS_TARGET_VM:
4431     {
4432         stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
4433         if (stats_fd == -1) {
4434             error_setg_errno(errp, errno, "KVM stats: ioctl failed");
4435             return;
4436         }
4437         query_stats(result, target, names, stats_fd, NULL, errp);
4438         close(stats_fd);
4439         break;
4440     }
4441     case STATS_TARGET_VCPU:
4442     {
4443         StatsArgs stats_args;
4444         stats_args.result.stats = result;
4445         stats_args.names = names;
4446         stats_args.errp = errp;
4447         CPU_FOREACH(cpu) {
4448             if (!apply_str_list_filter(cpu->parent_obj.canonical_path, targets)) {
4449                 continue;
4450             }
4451             query_stats_vcpu(cpu, &stats_args);
4452         }
4453         break;
4454     }
4455     default:
4456         break;
4457     }
4458 }
4459 
query_stats_schemas_cb(StatsSchemaList ** result,Error ** errp)4460 void query_stats_schemas_cb(StatsSchemaList **result, Error **errp)
4461 {
4462     StatsArgs stats_args;
4463     KVMState *s = kvm_state;
4464     int stats_fd;
4465 
4466     stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
4467     if (stats_fd == -1) {
4468         error_setg_errno(errp, errno, "KVM stats: ioctl failed");
4469         return;
4470     }
4471     query_stats_schema(result, STATS_TARGET_VM, stats_fd, errp);
4472     close(stats_fd);
4473 
4474     if (first_cpu) {
4475         stats_args.result.schema = result;
4476         stats_args.errp = errp;
4477         query_stats_schema_vcpu(first_cpu, &stats_args);
4478     }
4479 }
4480 
kvm_mark_guest_state_protected(void)4481 void kvm_mark_guest_state_protected(void)
4482 {
4483     kvm_state->guest_state_protected = true;
4484 }
4485 
kvm_create_guest_memfd(uint64_t size,uint64_t flags,Error ** errp)4486 int kvm_create_guest_memfd(uint64_t size, uint64_t flags, Error **errp)
4487 {
4488     int fd;
4489     struct kvm_create_guest_memfd guest_memfd = {
4490         .size = size,
4491         .flags = flags,
4492     };
4493 
4494     if (!kvm_guest_memfd_supported) {
4495         error_setg(errp, "KVM does not support guest_memfd");
4496         return -1;
4497     }
4498 
4499     fd = kvm_vm_ioctl(kvm_state, KVM_CREATE_GUEST_MEMFD, &guest_memfd);
4500     if (fd < 0) {
4501         error_setg_errno(errp, errno, "Error creating KVM guest_memfd");
4502         return -1;
4503     }
4504 
4505     return fd;
4506 }
4507