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