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