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