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