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