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