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