xref: /openbmc/qemu/accel/kvm/kvm-all.c (revision 261573c7724ffca8795416eae8b435e175672491)
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(KVMState *s, int type)
2474 {
2475     int ret;
2476 
2477     do {
2478         ret = kvm_ioctl(s, KVM_CREATE_VM, type);
2479     } while (ret == -EINTR);
2480 
2481     if (ret < 0) {
2482         error_report("ioctl(KVM_CREATE_VM) failed: %s", strerror(-ret));
2483 
2484 #ifdef TARGET_S390X
2485         if (ret == -EINVAL) {
2486             error_printf("Host kernel setup problem detected."
2487                          " Please verify:\n");
2488             error_printf("- for kernels supporting the"
2489                         " switch_amode or user_mode parameters, whether");
2490             error_printf(" user space is running in primary address space\n");
2491             error_printf("- for kernels supporting the vm.allocate_pgste"
2492                          " sysctl, whether it is enabled\n");
2493         }
2494 #elif defined(TARGET_PPC)
2495         if (ret == -EINVAL) {
2496             error_printf("PPC KVM module is not loaded. Try modprobe kvm_%s.\n",
2497                          (type == 2) ? "pr" : "hv");
2498         }
2499 #endif
2500     }
2501 
2502     return ret;
2503 }
2504 
2505 static int find_kvm_machine_type(MachineState *ms)
2506 {
2507     MachineClass *mc = MACHINE_GET_CLASS(ms);
2508     int type;
2509 
2510     if (object_property_find(OBJECT(current_machine), "kvm-type")) {
2511         g_autofree char *kvm_type;
2512         kvm_type = object_property_get_str(OBJECT(current_machine),
2513                                            "kvm-type",
2514                                            &error_abort);
2515         type = mc->kvm_type(ms, kvm_type);
2516     } else if (mc->kvm_type) {
2517         type = mc->kvm_type(ms, NULL);
2518     } else {
2519         type = kvm_arch_get_default_type(ms);
2520     }
2521     return type;
2522 }
2523 
2524 static int kvm_setup_dirty_ring(KVMState *s)
2525 {
2526     uint64_t dirty_log_manual_caps;
2527     int ret;
2528 
2529     /*
2530      * Enable KVM dirty ring if supported, otherwise fall back to
2531      * dirty logging mode
2532      */
2533     ret = kvm_dirty_ring_init(s);
2534     if (ret < 0) {
2535         return ret;
2536     }
2537 
2538     /*
2539      * KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is not needed when dirty ring is
2540      * enabled.  More importantly, KVM_DIRTY_LOG_INITIALLY_SET will assume no
2541      * page is wr-protected initially, which is against how kvm dirty ring is
2542      * usage - kvm dirty ring requires all pages are wr-protected at the very
2543      * beginning.  Enabling this feature for dirty ring causes data corruption.
2544      *
2545      * TODO: Without KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 and kvm clear dirty log,
2546      * we may expect a higher stall time when starting the migration.  In the
2547      * future we can enable KVM_CLEAR_DIRTY_LOG to work with dirty ring too:
2548      * instead of clearing dirty bit, it can be a way to explicitly wr-protect
2549      * guest pages.
2550      */
2551     if (!s->kvm_dirty_ring_size) {
2552         dirty_log_manual_caps =
2553             kvm_check_extension(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
2554         dirty_log_manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
2555                                   KVM_DIRTY_LOG_INITIALLY_SET);
2556         s->manual_dirty_log_protect = dirty_log_manual_caps;
2557         if (dirty_log_manual_caps) {
2558             ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0,
2559                                     dirty_log_manual_caps);
2560             if (ret) {
2561                 warn_report("Trying to enable capability %"PRIu64" of "
2562                             "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
2563                             "Falling back to the legacy mode. ",
2564                             dirty_log_manual_caps);
2565                 s->manual_dirty_log_protect = 0;
2566             }
2567         }
2568     }
2569 
2570     return 0;
2571 }
2572 
2573 static int kvm_init(AccelState *as, MachineState *ms)
2574 {
2575     MachineClass *mc = MACHINE_GET_CLASS(ms);
2576     static const char upgrade_note[] =
2577         "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
2578         "(see http://sourceforge.net/projects/kvm).\n";
2579     const struct {
2580         const char *name;
2581         int num;
2582     } num_cpus[] = {
2583         { "SMP",          ms->smp.cpus },
2584         { "hotpluggable", ms->smp.max_cpus },
2585         { /* end of list */ }
2586     }, *nc = num_cpus;
2587     int soft_vcpus_limit, hard_vcpus_limit;
2588     KVMState *s = KVM_STATE(as);
2589     const KVMCapabilityInfo *missing_cap;
2590     int ret;
2591     int type;
2592 
2593     qemu_mutex_init(&kml_slots_lock);
2594 
2595     /*
2596      * On systems where the kernel can support different base page
2597      * sizes, host page size may be different from TARGET_PAGE_SIZE,
2598      * even with KVM.  TARGET_PAGE_SIZE is assumed to be the minimum
2599      * page size for the system though.
2600      */
2601     assert(TARGET_PAGE_SIZE <= qemu_real_host_page_size());
2602 
2603     s->sigmask_len = 8;
2604     accel_blocker_init();
2605 
2606 #ifdef TARGET_KVM_HAVE_GUEST_DEBUG
2607     QTAILQ_INIT(&s->kvm_sw_breakpoints);
2608 #endif
2609     QLIST_INIT(&s->kvm_parked_vcpus);
2610     s->fd = qemu_open_old(s->device ?: "/dev/kvm", O_RDWR);
2611     if (s->fd == -1) {
2612         error_report("Could not access KVM kernel module: %m");
2613         ret = -errno;
2614         goto err;
2615     }
2616 
2617     ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
2618     if (ret < KVM_API_VERSION) {
2619         if (ret >= 0) {
2620             ret = -EINVAL;
2621         }
2622         error_report("kvm version too old");
2623         goto err;
2624     }
2625 
2626     if (ret > KVM_API_VERSION) {
2627         ret = -EINVAL;
2628         error_report("kvm version not supported");
2629         goto err;
2630     }
2631 
2632     kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
2633     s->nr_slots_max = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
2634 
2635     /* If unspecified, use the default value */
2636     if (!s->nr_slots_max) {
2637         s->nr_slots_max = KVM_MEMSLOTS_NR_MAX_DEFAULT;
2638     }
2639 
2640     type = find_kvm_machine_type(ms);
2641     if (type < 0) {
2642         ret = -EINVAL;
2643         goto err;
2644     }
2645 
2646     ret = do_kvm_create_vm(s, type);
2647     if (ret < 0) {
2648         goto err;
2649     }
2650 
2651     s->vmfd = ret;
2652 
2653     s->nr_as = kvm_vm_check_extension(s, KVM_CAP_MULTI_ADDRESS_SPACE);
2654     if (s->nr_as <= 1) {
2655         s->nr_as = 1;
2656     }
2657     s->as = g_new0(struct KVMAs, s->nr_as);
2658 
2659     /* check the vcpu limits */
2660     soft_vcpus_limit = kvm_recommended_vcpus(s);
2661     hard_vcpus_limit = kvm_max_vcpus(s);
2662 
2663     while (nc->name) {
2664         if (nc->num > soft_vcpus_limit) {
2665             warn_report("Number of %s cpus requested (%d) exceeds "
2666                         "the recommended cpus supported by KVM (%d)",
2667                         nc->name, nc->num, soft_vcpus_limit);
2668 
2669             if (nc->num > hard_vcpus_limit) {
2670                 error_report("Number of %s cpus requested (%d) exceeds "
2671                              "the maximum cpus supported by KVM (%d)",
2672                              nc->name, nc->num, hard_vcpus_limit);
2673                 exit(1);
2674             }
2675         }
2676         nc++;
2677     }
2678 
2679     missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
2680     if (!missing_cap) {
2681         missing_cap =
2682             kvm_check_extension_list(s, kvm_arch_required_capabilities);
2683     }
2684     if (missing_cap) {
2685         ret = -EINVAL;
2686         error_report("kvm does not support %s", missing_cap->name);
2687         error_printf("%s", upgrade_note);
2688         goto err;
2689     }
2690 
2691     s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
2692     s->coalesced_pio = s->coalesced_mmio &&
2693                        kvm_check_extension(s, KVM_CAP_COALESCED_PIO);
2694 
2695     ret = kvm_setup_dirty_ring(s);
2696     if (ret < 0) {
2697         goto err;
2698     }
2699 
2700 #ifdef KVM_CAP_VCPU_EVENTS
2701     s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
2702 #endif
2703     s->max_nested_state_len = kvm_check_extension(s, KVM_CAP_NESTED_STATE);
2704 
2705     s->irq_set_ioctl = KVM_IRQ_LINE;
2706     if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
2707         s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
2708     }
2709 
2710     kvm_readonly_mem_allowed =
2711         (kvm_vm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
2712 
2713     kvm_resamplefds_allowed =
2714         (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
2715 
2716     kvm_vm_attributes_allowed =
2717         (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
2718 
2719 #ifdef TARGET_KVM_HAVE_GUEST_DEBUG
2720     kvm_has_guest_debug =
2721         (kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG) > 0);
2722 #endif
2723 
2724     kvm_sstep_flags = 0;
2725     if (kvm_has_guest_debug) {
2726         kvm_sstep_flags = SSTEP_ENABLE;
2727 
2728 #if defined TARGET_KVM_HAVE_GUEST_DEBUG
2729         int guest_debug_flags =
2730             kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG2);
2731 
2732         if (guest_debug_flags & KVM_GUESTDBG_BLOCKIRQ) {
2733             kvm_sstep_flags |= SSTEP_NOIRQ;
2734         }
2735 #endif
2736     }
2737 
2738     kvm_state = s;
2739 
2740     ret = kvm_arch_init(ms, s);
2741     if (ret < 0) {
2742         goto err;
2743     }
2744 
2745     kvm_supported_memory_attributes = kvm_vm_check_extension(s, KVM_CAP_MEMORY_ATTRIBUTES);
2746     kvm_guest_memfd_supported =
2747         kvm_check_extension(s, KVM_CAP_GUEST_MEMFD) &&
2748         kvm_check_extension(s, KVM_CAP_USER_MEMORY2) &&
2749         (kvm_supported_memory_attributes & KVM_MEMORY_ATTRIBUTE_PRIVATE);
2750     kvm_pre_fault_memory_supported = kvm_vm_check_extension(s, KVM_CAP_PRE_FAULT_MEMORY);
2751 
2752     if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
2753         s->kernel_irqchip_split = mc->default_kernel_irqchip_split ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
2754     }
2755 
2756     qemu_register_reset(kvm_unpoison_all, NULL);
2757 
2758     if (s->kernel_irqchip_allowed) {
2759         kvm_irqchip_create(s);
2760     }
2761 
2762     s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
2763     s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
2764     s->memory_listener.listener.coalesced_io_add = kvm_coalesce_mmio_region;
2765     s->memory_listener.listener.coalesced_io_del = kvm_uncoalesce_mmio_region;
2766 
2767     kvm_memory_listener_register(s, &s->memory_listener,
2768                                  &address_space_memory, 0, "kvm-memory");
2769     memory_listener_register(&kvm_io_listener,
2770                              &address_space_io);
2771 
2772     s->sync_mmu = !!kvm_vm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2773     if (!s->sync_mmu) {
2774         ret = ram_block_discard_disable(true);
2775         assert(!ret);
2776     }
2777 
2778     if (s->kvm_dirty_ring_size) {
2779         kvm_dirty_ring_reaper_init(s);
2780     }
2781 
2782     if (kvm_check_extension(kvm_state, KVM_CAP_BINARY_STATS_FD)) {
2783         add_stats_callbacks(STATS_PROVIDER_KVM, query_stats_cb,
2784                             query_stats_schemas_cb);
2785     }
2786 
2787     return 0;
2788 
2789 err:
2790     assert(ret < 0);
2791     if (s->vmfd >= 0) {
2792         close(s->vmfd);
2793     }
2794     if (s->fd != -1) {
2795         close(s->fd);
2796     }
2797     g_free(s->as);
2798     g_free(s->memory_listener.slots);
2799 
2800     return ret;
2801 }
2802 
2803 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
2804 {
2805     s->sigmask_len = sigmask_len;
2806 }
2807 
2808 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
2809                           int size, uint32_t count)
2810 {
2811     int i;
2812     uint8_t *ptr = data;
2813 
2814     for (i = 0; i < count; i++) {
2815         address_space_rw(&address_space_io, port, attrs,
2816                          ptr, size,
2817                          direction == KVM_EXIT_IO_OUT);
2818         ptr += size;
2819     }
2820 }
2821 
2822 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
2823 {
2824     int i;
2825 
2826     fprintf(stderr, "KVM internal error. Suberror: %d\n",
2827             run->internal.suberror);
2828 
2829     for (i = 0; i < run->internal.ndata; ++i) {
2830         fprintf(stderr, "extra data[%d]: 0x%016"PRIx64"\n",
2831                 i, (uint64_t)run->internal.data[i]);
2832     }
2833     if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
2834         fprintf(stderr, "emulation failure\n");
2835         if (!kvm_arch_stop_on_emulation_error(cpu)) {
2836             cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2837             return EXCP_INTERRUPT;
2838         }
2839     }
2840     /* FIXME: Should trigger a qmp message to let management know
2841      * something went wrong.
2842      */
2843     return -1;
2844 }
2845 
2846 void kvm_flush_coalesced_mmio_buffer(void)
2847 {
2848     KVMState *s = kvm_state;
2849 
2850     if (!s || s->coalesced_flush_in_progress) {
2851         return;
2852     }
2853 
2854     s->coalesced_flush_in_progress = true;
2855 
2856     if (s->coalesced_mmio_ring) {
2857         struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
2858         while (ring->first != ring->last) {
2859             struct kvm_coalesced_mmio *ent;
2860 
2861             ent = &ring->coalesced_mmio[ring->first];
2862 
2863             if (ent->pio == 1) {
2864                 address_space_write(&address_space_io, ent->phys_addr,
2865                                     MEMTXATTRS_UNSPECIFIED, ent->data,
2866                                     ent->len);
2867             } else {
2868                 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
2869             }
2870             smp_wmb();
2871             ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
2872         }
2873     }
2874 
2875     s->coalesced_flush_in_progress = false;
2876 }
2877 
2878 static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
2879 {
2880     if (!cpu->vcpu_dirty && !kvm_state->guest_state_protected) {
2881         Error *err = NULL;
2882         int ret = kvm_arch_get_registers(cpu, &err);
2883         if (ret) {
2884             if (err) {
2885                 error_reportf_err(err, "Failed to synchronize CPU state: ");
2886             } else {
2887                 error_report("Failed to get registers: %s", strerror(-ret));
2888             }
2889 
2890             cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2891             vm_stop(RUN_STATE_INTERNAL_ERROR);
2892         }
2893 
2894         cpu->vcpu_dirty = true;
2895     }
2896 }
2897 
2898 void kvm_cpu_synchronize_state(CPUState *cpu)
2899 {
2900     if (!cpu->vcpu_dirty && !kvm_state->guest_state_protected) {
2901         run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
2902     }
2903 }
2904 
2905 static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
2906 {
2907     Error *err = NULL;
2908     int ret = kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE, &err);
2909     if (ret) {
2910         if (err) {
2911             error_reportf_err(err, "Restoring resisters after reset: ");
2912         } else {
2913             error_report("Failed to put registers after reset: %s",
2914                          strerror(-ret));
2915         }
2916         cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2917         vm_stop(RUN_STATE_INTERNAL_ERROR);
2918     }
2919 
2920     cpu->vcpu_dirty = false;
2921 }
2922 
2923 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
2924 {
2925     run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
2926 
2927     if (cpu == first_cpu) {
2928         kvm_reset_parked_vcpus(kvm_state);
2929     }
2930 }
2931 
2932 static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
2933 {
2934     Error *err = NULL;
2935     int ret = kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE, &err);
2936     if (ret) {
2937         if (err) {
2938             error_reportf_err(err, "Putting registers after init: ");
2939         } else {
2940             error_report("Failed to put registers after init: %s",
2941                          strerror(-ret));
2942         }
2943         exit(1);
2944     }
2945 
2946     cpu->vcpu_dirty = false;
2947 }
2948 
2949 void kvm_cpu_synchronize_post_init(CPUState *cpu)
2950 {
2951     if (!kvm_state->guest_state_protected) {
2952         /*
2953          * This runs before the machine_init_done notifiers, and is the last
2954          * opportunity to synchronize the state of confidential guests.
2955          */
2956         run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
2957     }
2958 }
2959 
2960 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
2961 {
2962     cpu->vcpu_dirty = true;
2963 }
2964 
2965 void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
2966 {
2967     run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
2968 }
2969 
2970 #ifdef KVM_HAVE_MCE_INJECTION
2971 static __thread void *pending_sigbus_addr;
2972 static __thread int pending_sigbus_code;
2973 static __thread bool have_sigbus_pending;
2974 #endif
2975 
2976 static void kvm_cpu_kick(CPUState *cpu)
2977 {
2978     qatomic_set(&cpu->kvm_run->immediate_exit, 1);
2979 }
2980 
2981 static void kvm_cpu_kick_self(void)
2982 {
2983     if (kvm_immediate_exit) {
2984         kvm_cpu_kick(current_cpu);
2985     } else {
2986         qemu_cpu_kick_self();
2987     }
2988 }
2989 
2990 static void kvm_eat_signals(CPUState *cpu)
2991 {
2992     struct timespec ts = { 0, 0 };
2993     siginfo_t siginfo;
2994     sigset_t waitset;
2995     sigset_t chkset;
2996     int r;
2997 
2998     if (kvm_immediate_exit) {
2999         qatomic_set(&cpu->kvm_run->immediate_exit, 0);
3000         /* Write kvm_run->immediate_exit before the cpu->exit_request
3001          * write in kvm_cpu_exec.
3002          */
3003         smp_wmb();
3004         return;
3005     }
3006 
3007     sigemptyset(&waitset);
3008     sigaddset(&waitset, SIG_IPI);
3009 
3010     do {
3011         r = sigtimedwait(&waitset, &siginfo, &ts);
3012         if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
3013             perror("sigtimedwait");
3014             exit(1);
3015         }
3016 
3017         r = sigpending(&chkset);
3018         if (r == -1) {
3019             perror("sigpending");
3020             exit(1);
3021         }
3022     } while (sigismember(&chkset, SIG_IPI));
3023 }
3024 
3025 int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private)
3026 {
3027     MemoryRegionSection section;
3028     ram_addr_t offset;
3029     MemoryRegion *mr;
3030     RAMBlock *rb;
3031     void *addr;
3032     int ret = -EINVAL;
3033 
3034     trace_kvm_convert_memory(start, size, to_private ? "shared_to_private" : "private_to_shared");
3035 
3036     if (!QEMU_PTR_IS_ALIGNED(start, qemu_real_host_page_size()) ||
3037         !QEMU_PTR_IS_ALIGNED(size, qemu_real_host_page_size())) {
3038         return ret;
3039     }
3040 
3041     if (!size) {
3042         return ret;
3043     }
3044 
3045     section = memory_region_find(get_system_memory(), start, size);
3046     mr = section.mr;
3047     if (!mr) {
3048         /*
3049          * Ignore converting non-assigned region to shared.
3050          *
3051          * TDX requires vMMIO region to be shared to inject #VE to guest.
3052          * OVMF issues conservatively MapGPA(shared) on 32bit PCI MMIO region,
3053          * and vIO-APIC 0xFEC00000 4K page.
3054          * OVMF assigns 32bit PCI MMIO region to
3055          * [top of low memory: typically 2GB=0xC000000,  0xFC00000)
3056          */
3057         if (!to_private) {
3058             return 0;
3059         }
3060         return ret;
3061     }
3062 
3063     if (!memory_region_has_guest_memfd(mr)) {
3064         /*
3065          * Because vMMIO region must be shared, guest TD may convert vMMIO
3066          * region to shared explicitly.  Don't complain such case.  See
3067          * memory_region_type() for checking if the region is MMIO region.
3068          */
3069         if (!to_private &&
3070             !memory_region_is_ram(mr) &&
3071             !memory_region_is_ram_device(mr) &&
3072             !memory_region_is_rom(mr) &&
3073             !memory_region_is_romd(mr)) {
3074             ret = 0;
3075         } else {
3076             error_report("Convert non guest_memfd backed memory region "
3077                         "(0x%"HWADDR_PRIx" ,+ 0x%"HWADDR_PRIx") to %s",
3078                         start, size, to_private ? "private" : "shared");
3079         }
3080         goto out_unref;
3081     }
3082 
3083     if (to_private) {
3084         ret = kvm_set_memory_attributes_private(start, size);
3085     } else {
3086         ret = kvm_set_memory_attributes_shared(start, size);
3087     }
3088     if (ret) {
3089         goto out_unref;
3090     }
3091 
3092     addr = memory_region_get_ram_ptr(mr) + section.offset_within_region;
3093     rb = qemu_ram_block_from_host(addr, false, &offset);
3094 
3095     ret = ram_block_attributes_state_change(RAM_BLOCK_ATTRIBUTES(mr->rdm),
3096                                             offset, size, to_private);
3097     if (ret) {
3098         error_report("Failed to notify the listener the state change of "
3099                      "(0x%"HWADDR_PRIx" + 0x%"HWADDR_PRIx") to %s",
3100                      start, size, to_private ? "private" : "shared");
3101         goto out_unref;
3102     }
3103 
3104     if (to_private) {
3105         if (rb->page_size != qemu_real_host_page_size()) {
3106             /*
3107              * shared memory is backed by hugetlb, which is supposed to be
3108              * pre-allocated and doesn't need to be discarded
3109              */
3110             goto out_unref;
3111         }
3112         ret = ram_block_discard_range(rb, offset, size);
3113     } else {
3114         ret = ram_block_discard_guest_memfd_range(rb, offset, size);
3115     }
3116 
3117 out_unref:
3118     memory_region_unref(mr);
3119     return ret;
3120 }
3121 
3122 int kvm_cpu_exec(CPUState *cpu)
3123 {
3124     struct kvm_run *run = cpu->kvm_run;
3125     int ret, run_ret;
3126 
3127     trace_kvm_cpu_exec();
3128 
3129     if (kvm_arch_process_async_events(cpu)) {
3130         qatomic_set(&cpu->exit_request, 0);
3131         return EXCP_HLT;
3132     }
3133 
3134     bql_unlock();
3135     cpu_exec_start(cpu);
3136 
3137     do {
3138         MemTxAttrs attrs;
3139 
3140         if (cpu->vcpu_dirty) {
3141             Error *err = NULL;
3142             ret = kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE, &err);
3143             if (ret) {
3144                 if (err) {
3145                     error_reportf_err(err, "Putting registers after init: ");
3146                 } else {
3147                     error_report("Failed to put registers after init: %s",
3148                                  strerror(-ret));
3149                 }
3150                 ret = -1;
3151                 break;
3152             }
3153 
3154             cpu->vcpu_dirty = false;
3155         }
3156 
3157         kvm_arch_pre_run(cpu, run);
3158         if (qatomic_read(&cpu->exit_request)) {
3159             trace_kvm_interrupt_exit_request();
3160             /*
3161              * KVM requires us to reenter the kernel after IO exits to complete
3162              * instruction emulation. This self-signal will ensure that we
3163              * leave ASAP again.
3164              */
3165             kvm_cpu_kick_self();
3166         }
3167 
3168         /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
3169          * Matching barrier in kvm_eat_signals.
3170          */
3171         smp_rmb();
3172 
3173         run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
3174 
3175         attrs = kvm_arch_post_run(cpu, run);
3176 
3177 #ifdef KVM_HAVE_MCE_INJECTION
3178         if (unlikely(have_sigbus_pending)) {
3179             bql_lock();
3180             kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
3181                                     pending_sigbus_addr);
3182             have_sigbus_pending = false;
3183             bql_unlock();
3184         }
3185 #endif
3186 
3187         if (run_ret < 0) {
3188             if (run_ret == -EINTR || run_ret == -EAGAIN) {
3189                 trace_kvm_io_window_exit();
3190                 kvm_eat_signals(cpu);
3191                 ret = EXCP_INTERRUPT;
3192                 break;
3193             }
3194             if (!(run_ret == -EFAULT && run->exit_reason == KVM_EXIT_MEMORY_FAULT)) {
3195                 fprintf(stderr, "error: kvm run failed %s\n",
3196                         strerror(-run_ret));
3197 #ifdef TARGET_PPC
3198                 if (run_ret == -EBUSY) {
3199                     fprintf(stderr,
3200                             "This is probably because your SMT is enabled.\n"
3201                             "VCPU can only run on primary threads with all "
3202                             "secondary threads offline.\n");
3203                 }
3204 #endif
3205                 ret = -1;
3206                 break;
3207             }
3208         }
3209 
3210         trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
3211         switch (run->exit_reason) {
3212         case KVM_EXIT_IO:
3213             /* Called outside BQL */
3214             kvm_handle_io(run->io.port, attrs,
3215                           (uint8_t *)run + run->io.data_offset,
3216                           run->io.direction,
3217                           run->io.size,
3218                           run->io.count);
3219             ret = 0;
3220             break;
3221         case KVM_EXIT_MMIO:
3222             /* Called outside BQL */
3223             address_space_rw(&address_space_memory,
3224                              run->mmio.phys_addr, attrs,
3225                              run->mmio.data,
3226                              run->mmio.len,
3227                              run->mmio.is_write);
3228             ret = 0;
3229             break;
3230         case KVM_EXIT_IRQ_WINDOW_OPEN:
3231             ret = EXCP_INTERRUPT;
3232             break;
3233         case KVM_EXIT_SHUTDOWN:
3234             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
3235             ret = EXCP_INTERRUPT;
3236             break;
3237         case KVM_EXIT_UNKNOWN:
3238             fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
3239                     (uint64_t)run->hw.hardware_exit_reason);
3240             ret = -1;
3241             break;
3242         case KVM_EXIT_INTERNAL_ERROR:
3243             ret = kvm_handle_internal_error(cpu, run);
3244             break;
3245         case KVM_EXIT_DIRTY_RING_FULL:
3246             /*
3247              * We shouldn't continue if the dirty ring of this vcpu is
3248              * still full.  Got kicked by KVM_RESET_DIRTY_RINGS.
3249              */
3250             trace_kvm_dirty_ring_full(cpu->cpu_index);
3251             bql_lock();
3252             /*
3253              * We throttle vCPU by making it sleep once it exit from kernel
3254              * due to dirty ring full. In the dirtylimit scenario, reaping
3255              * all vCPUs after a single vCPU dirty ring get full result in
3256              * the miss of sleep, so just reap the ring-fulled vCPU.
3257              */
3258             if (dirtylimit_in_service()) {
3259                 kvm_dirty_ring_reap(kvm_state, cpu);
3260             } else {
3261                 kvm_dirty_ring_reap(kvm_state, NULL);
3262             }
3263             bql_unlock();
3264             dirtylimit_vcpu_execute(cpu);
3265             ret = 0;
3266             break;
3267         case KVM_EXIT_SYSTEM_EVENT:
3268             trace_kvm_run_exit_system_event(cpu->cpu_index, run->system_event.type);
3269             switch (run->system_event.type) {
3270             case KVM_SYSTEM_EVENT_SHUTDOWN:
3271                 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
3272                 ret = EXCP_INTERRUPT;
3273                 break;
3274             case KVM_SYSTEM_EVENT_RESET:
3275                 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
3276                 ret = EXCP_INTERRUPT;
3277                 break;
3278             case KVM_SYSTEM_EVENT_CRASH:
3279                 kvm_cpu_synchronize_state(cpu);
3280                 bql_lock();
3281                 qemu_system_guest_panicked(cpu_get_crash_info(cpu));
3282                 bql_unlock();
3283                 ret = 0;
3284                 break;
3285             default:
3286                 ret = kvm_arch_handle_exit(cpu, run);
3287                 break;
3288             }
3289             break;
3290         case KVM_EXIT_MEMORY_FAULT:
3291             trace_kvm_memory_fault(run->memory_fault.gpa,
3292                                    run->memory_fault.size,
3293                                    run->memory_fault.flags);
3294             if (run->memory_fault.flags & ~KVM_MEMORY_EXIT_FLAG_PRIVATE) {
3295                 error_report("KVM_EXIT_MEMORY_FAULT: Unknown flag 0x%" PRIx64,
3296                              (uint64_t)run->memory_fault.flags);
3297                 ret = -1;
3298                 break;
3299             }
3300             ret = kvm_convert_memory(run->memory_fault.gpa, run->memory_fault.size,
3301                                      run->memory_fault.flags & KVM_MEMORY_EXIT_FLAG_PRIVATE);
3302             break;
3303         default:
3304             ret = kvm_arch_handle_exit(cpu, run);
3305             break;
3306         }
3307     } while (ret == 0);
3308 
3309     cpu_exec_end(cpu);
3310     bql_lock();
3311 
3312     if (ret < 0) {
3313         cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
3314         vm_stop(RUN_STATE_INTERNAL_ERROR);
3315     }
3316 
3317     qatomic_set(&cpu->exit_request, 0);
3318     return ret;
3319 }
3320 
3321 int kvm_ioctl(KVMState *s, unsigned long type, ...)
3322 {
3323     int ret;
3324     void *arg;
3325     va_list ap;
3326 
3327     va_start(ap, type);
3328     arg = va_arg(ap, void *);
3329     va_end(ap);
3330 
3331     trace_kvm_ioctl(type, arg);
3332     ret = ioctl(s->fd, type, arg);
3333     if (ret == -1) {
3334         ret = -errno;
3335     }
3336     return ret;
3337 }
3338 
3339 int kvm_vm_ioctl(KVMState *s, unsigned long type, ...)
3340 {
3341     int ret;
3342     void *arg;
3343     va_list ap;
3344 
3345     va_start(ap, type);
3346     arg = va_arg(ap, void *);
3347     va_end(ap);
3348 
3349     trace_kvm_vm_ioctl(type, arg);
3350     accel_ioctl_begin();
3351     ret = ioctl(s->vmfd, type, arg);
3352     accel_ioctl_end();
3353     if (ret == -1) {
3354         ret = -errno;
3355     }
3356     return ret;
3357 }
3358 
3359 int kvm_vcpu_ioctl(CPUState *cpu, unsigned long type, ...)
3360 {
3361     int ret;
3362     void *arg;
3363     va_list ap;
3364 
3365     va_start(ap, type);
3366     arg = va_arg(ap, void *);
3367     va_end(ap);
3368 
3369     trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
3370     accel_cpu_ioctl_begin(cpu);
3371     ret = ioctl(cpu->kvm_fd, type, arg);
3372     accel_cpu_ioctl_end(cpu);
3373     if (ret == -1) {
3374         ret = -errno;
3375     }
3376     return ret;
3377 }
3378 
3379 int kvm_device_ioctl(int fd, unsigned long type, ...)
3380 {
3381     int ret;
3382     void *arg;
3383     va_list ap;
3384 
3385     va_start(ap, type);
3386     arg = va_arg(ap, void *);
3387     va_end(ap);
3388 
3389     trace_kvm_device_ioctl(fd, type, arg);
3390     accel_ioctl_begin();
3391     ret = ioctl(fd, type, arg);
3392     accel_ioctl_end();
3393     if (ret == -1) {
3394         ret = -errno;
3395     }
3396     return ret;
3397 }
3398 
3399 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
3400 {
3401     int ret;
3402     struct kvm_device_attr attribute = {
3403         .group = group,
3404         .attr = attr,
3405     };
3406 
3407     if (!kvm_vm_attributes_allowed) {
3408         return 0;
3409     }
3410 
3411     ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
3412     /* kvm returns 0 on success for HAS_DEVICE_ATTR */
3413     return ret ? 0 : 1;
3414 }
3415 
3416 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
3417 {
3418     struct kvm_device_attr attribute = {
3419         .group = group,
3420         .attr = attr,
3421         .flags = 0,
3422     };
3423 
3424     return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
3425 }
3426 
3427 int kvm_device_access(int fd, int group, uint64_t attr,
3428                       void *val, bool write, Error **errp)
3429 {
3430     struct kvm_device_attr kvmattr;
3431     int err;
3432 
3433     kvmattr.flags = 0;
3434     kvmattr.group = group;
3435     kvmattr.attr = attr;
3436     kvmattr.addr = (uintptr_t)val;
3437 
3438     err = kvm_device_ioctl(fd,
3439                            write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
3440                            &kvmattr);
3441     if (err < 0) {
3442         error_setg_errno(errp, -err,
3443                          "KVM_%s_DEVICE_ATTR failed: Group %d "
3444                          "attr 0x%016" PRIx64,
3445                          write ? "SET" : "GET", group, attr);
3446     }
3447     return err;
3448 }
3449 
3450 bool kvm_has_sync_mmu(void)
3451 {
3452     return kvm_state->sync_mmu;
3453 }
3454 
3455 int kvm_has_vcpu_events(void)
3456 {
3457     return kvm_state->vcpu_events;
3458 }
3459 
3460 int kvm_max_nested_state_length(void)
3461 {
3462     return kvm_state->max_nested_state_len;
3463 }
3464 
3465 int kvm_has_gsi_routing(void)
3466 {
3467 #ifdef KVM_CAP_IRQ_ROUTING
3468     return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
3469 #else
3470     return false;
3471 #endif
3472 }
3473 
3474 bool kvm_arm_supports_user_irq(void)
3475 {
3476     return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
3477 }
3478 
3479 #ifdef TARGET_KVM_HAVE_GUEST_DEBUG
3480 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu, vaddr pc)
3481 {
3482     struct kvm_sw_breakpoint *bp;
3483 
3484     QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
3485         if (bp->pc == pc) {
3486             return bp;
3487         }
3488     }
3489     return NULL;
3490 }
3491 
3492 int kvm_sw_breakpoints_active(CPUState *cpu)
3493 {
3494     return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
3495 }
3496 
3497 struct kvm_set_guest_debug_data {
3498     struct kvm_guest_debug dbg;
3499     int err;
3500 };
3501 
3502 static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
3503 {
3504     struct kvm_set_guest_debug_data *dbg_data =
3505         (struct kvm_set_guest_debug_data *) data.host_ptr;
3506 
3507     dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
3508                                    &dbg_data->dbg);
3509 }
3510 
3511 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
3512 {
3513     struct kvm_set_guest_debug_data data;
3514 
3515     data.dbg.control = reinject_trap;
3516 
3517     if (cpu->singlestep_enabled) {
3518         data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
3519 
3520         if (cpu->singlestep_enabled & SSTEP_NOIRQ) {
3521             data.dbg.control |= KVM_GUESTDBG_BLOCKIRQ;
3522         }
3523     }
3524     kvm_arch_update_guest_debug(cpu, &data.dbg);
3525 
3526     run_on_cpu(cpu, kvm_invoke_set_guest_debug,
3527                RUN_ON_CPU_HOST_PTR(&data));
3528     return data.err;
3529 }
3530 
3531 bool kvm_supports_guest_debug(void)
3532 {
3533     /* probed during kvm_init() */
3534     return kvm_has_guest_debug;
3535 }
3536 
3537 int kvm_insert_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
3538 {
3539     struct kvm_sw_breakpoint *bp;
3540     int err;
3541 
3542     if (type == GDB_BREAKPOINT_SW) {
3543         bp = kvm_find_sw_breakpoint(cpu, addr);
3544         if (bp) {
3545             bp->use_count++;
3546             return 0;
3547         }
3548 
3549         bp = g_new(struct kvm_sw_breakpoint, 1);
3550         bp->pc = addr;
3551         bp->use_count = 1;
3552         err = kvm_arch_insert_sw_breakpoint(cpu, bp);
3553         if (err) {
3554             g_free(bp);
3555             return err;
3556         }
3557 
3558         QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
3559     } else {
3560         err = kvm_arch_insert_hw_breakpoint(addr, len, type);
3561         if (err) {
3562             return err;
3563         }
3564     }
3565 
3566     CPU_FOREACH(cpu) {
3567         err = kvm_update_guest_debug(cpu, 0);
3568         if (err) {
3569             return err;
3570         }
3571     }
3572     return 0;
3573 }
3574 
3575 int kvm_remove_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
3576 {
3577     struct kvm_sw_breakpoint *bp;
3578     int err;
3579 
3580     if (type == GDB_BREAKPOINT_SW) {
3581         bp = kvm_find_sw_breakpoint(cpu, addr);
3582         if (!bp) {
3583             return -ENOENT;
3584         }
3585 
3586         if (bp->use_count > 1) {
3587             bp->use_count--;
3588             return 0;
3589         }
3590 
3591         err = kvm_arch_remove_sw_breakpoint(cpu, bp);
3592         if (err) {
3593             return err;
3594         }
3595 
3596         QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
3597         g_free(bp);
3598     } else {
3599         err = kvm_arch_remove_hw_breakpoint(addr, len, type);
3600         if (err) {
3601             return err;
3602         }
3603     }
3604 
3605     CPU_FOREACH(cpu) {
3606         err = kvm_update_guest_debug(cpu, 0);
3607         if (err) {
3608             return err;
3609         }
3610     }
3611     return 0;
3612 }
3613 
3614 void kvm_remove_all_breakpoints(CPUState *cpu)
3615 {
3616     struct kvm_sw_breakpoint *bp, *next;
3617     KVMState *s = cpu->kvm_state;
3618     CPUState *tmpcpu;
3619 
3620     QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
3621         if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
3622             /* Try harder to find a CPU that currently sees the breakpoint. */
3623             CPU_FOREACH(tmpcpu) {
3624                 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
3625                     break;
3626                 }
3627             }
3628         }
3629         QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
3630         g_free(bp);
3631     }
3632     kvm_arch_remove_all_hw_breakpoints();
3633 
3634     CPU_FOREACH(cpu) {
3635         kvm_update_guest_debug(cpu, 0);
3636     }
3637 }
3638 
3639 #endif /* !TARGET_KVM_HAVE_GUEST_DEBUG */
3640 
3641 static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
3642 {
3643     KVMState *s = kvm_state;
3644     struct kvm_signal_mask *sigmask;
3645     int r;
3646 
3647     sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
3648 
3649     sigmask->len = s->sigmask_len;
3650     memcpy(sigmask->sigset, sigset, sizeof(*sigset));
3651     r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
3652     g_free(sigmask);
3653 
3654     return r;
3655 }
3656 
3657 static void kvm_ipi_signal(int sig)
3658 {
3659     if (current_cpu) {
3660         assert(kvm_immediate_exit);
3661         kvm_cpu_kick(current_cpu);
3662     }
3663 }
3664 
3665 void kvm_init_cpu_signals(CPUState *cpu)
3666 {
3667     int r;
3668     sigset_t set;
3669     struct sigaction sigact;
3670 
3671     memset(&sigact, 0, sizeof(sigact));
3672     sigact.sa_handler = kvm_ipi_signal;
3673     sigaction(SIG_IPI, &sigact, NULL);
3674 
3675     pthread_sigmask(SIG_BLOCK, NULL, &set);
3676 #if defined KVM_HAVE_MCE_INJECTION
3677     sigdelset(&set, SIGBUS);
3678     pthread_sigmask(SIG_SETMASK, &set, NULL);
3679 #endif
3680     sigdelset(&set, SIG_IPI);
3681     if (kvm_immediate_exit) {
3682         r = pthread_sigmask(SIG_SETMASK, &set, NULL);
3683     } else {
3684         r = kvm_set_signal_mask(cpu, &set);
3685     }
3686     if (r) {
3687         fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
3688         exit(1);
3689     }
3690 }
3691 
3692 /* Called asynchronously in VCPU thread.  */
3693 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
3694 {
3695 #ifdef KVM_HAVE_MCE_INJECTION
3696     if (have_sigbus_pending) {
3697         return 1;
3698     }
3699     have_sigbus_pending = true;
3700     pending_sigbus_addr = addr;
3701     pending_sigbus_code = code;
3702     qatomic_set(&cpu->exit_request, 1);
3703     return 0;
3704 #else
3705     return 1;
3706 #endif
3707 }
3708 
3709 /* Called synchronously (via signalfd) in main thread.  */
3710 int kvm_on_sigbus(int code, void *addr)
3711 {
3712 #ifdef KVM_HAVE_MCE_INJECTION
3713     /* Action required MCE kills the process if SIGBUS is blocked.  Because
3714      * that's what happens in the I/O thread, where we handle MCE via signalfd,
3715      * we can only get action optional here.
3716      */
3717     assert(code != BUS_MCEERR_AR);
3718     kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
3719     return 0;
3720 #else
3721     return 1;
3722 #endif
3723 }
3724 
3725 int kvm_create_device(KVMState *s, uint64_t type, bool test)
3726 {
3727     int ret;
3728     struct kvm_create_device create_dev;
3729 
3730     create_dev.type = type;
3731     create_dev.fd = -1;
3732     create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
3733 
3734     if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
3735         return -ENOTSUP;
3736     }
3737 
3738     ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
3739     if (ret) {
3740         return ret;
3741     }
3742 
3743     return test ? 0 : create_dev.fd;
3744 }
3745 
3746 bool kvm_device_supported(int vmfd, uint64_t type)
3747 {
3748     struct kvm_create_device create_dev = {
3749         .type = type,
3750         .fd = -1,
3751         .flags = KVM_CREATE_DEVICE_TEST,
3752     };
3753 
3754     if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
3755         return false;
3756     }
3757 
3758     return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
3759 }
3760 
3761 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
3762 {
3763     struct kvm_one_reg reg;
3764     int r;
3765 
3766     reg.id = id;
3767     reg.addr = (uintptr_t) source;
3768     r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
3769     if (r) {
3770         trace_kvm_failed_reg_set(id, strerror(-r));
3771     }
3772     return r;
3773 }
3774 
3775 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
3776 {
3777     struct kvm_one_reg reg;
3778     int r;
3779 
3780     reg.id = id;
3781     reg.addr = (uintptr_t) target;
3782     r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
3783     if (r) {
3784         trace_kvm_failed_reg_get(id, strerror(-r));
3785     }
3786     return r;
3787 }
3788 
3789 static bool kvm_accel_has_memory(AccelState *accel, AddressSpace *as,
3790                                  hwaddr start_addr, hwaddr size)
3791 {
3792     KVMState *kvm = KVM_STATE(accel);
3793     int i;
3794 
3795     for (i = 0; i < kvm->nr_as; ++i) {
3796         if (kvm->as[i].as == as && kvm->as[i].ml) {
3797             size = MIN(kvm_max_slot_size, size);
3798             return NULL != kvm_lookup_matching_slot(kvm->as[i].ml,
3799                                                     start_addr, size);
3800         }
3801     }
3802 
3803     return false;
3804 }
3805 
3806 static void kvm_get_kvm_shadow_mem(Object *obj, Visitor *v,
3807                                    const char *name, void *opaque,
3808                                    Error **errp)
3809 {
3810     KVMState *s = KVM_STATE(obj);
3811     int64_t value = s->kvm_shadow_mem;
3812 
3813     visit_type_int(v, name, &value, errp);
3814 }
3815 
3816 static void kvm_set_kvm_shadow_mem(Object *obj, Visitor *v,
3817                                    const char *name, void *opaque,
3818                                    Error **errp)
3819 {
3820     KVMState *s = KVM_STATE(obj);
3821     int64_t value;
3822 
3823     if (s->fd != -1) {
3824         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3825         return;
3826     }
3827 
3828     if (!visit_type_int(v, name, &value, errp)) {
3829         return;
3830     }
3831 
3832     s->kvm_shadow_mem = value;
3833 }
3834 
3835 static void kvm_set_kernel_irqchip(Object *obj, Visitor *v,
3836                                    const char *name, void *opaque,
3837                                    Error **errp)
3838 {
3839     KVMState *s = KVM_STATE(obj);
3840     OnOffSplit mode;
3841 
3842     if (s->fd != -1) {
3843         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3844         return;
3845     }
3846 
3847     if (!visit_type_OnOffSplit(v, name, &mode, errp)) {
3848         return;
3849     }
3850     switch (mode) {
3851     case ON_OFF_SPLIT_ON:
3852         s->kernel_irqchip_allowed = true;
3853         s->kernel_irqchip_required = true;
3854         s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3855         break;
3856     case ON_OFF_SPLIT_OFF:
3857         s->kernel_irqchip_allowed = false;
3858         s->kernel_irqchip_required = false;
3859         s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3860         break;
3861     case ON_OFF_SPLIT_SPLIT:
3862         s->kernel_irqchip_allowed = true;
3863         s->kernel_irqchip_required = true;
3864         s->kernel_irqchip_split = ON_OFF_AUTO_ON;
3865         break;
3866     default:
3867         /* The value was checked in visit_type_OnOffSplit() above. If
3868          * we get here, then something is wrong in QEMU.
3869          */
3870         abort();
3871     }
3872 }
3873 
3874 bool kvm_kernel_irqchip_allowed(void)
3875 {
3876     return kvm_state->kernel_irqchip_allowed;
3877 }
3878 
3879 bool kvm_kernel_irqchip_required(void)
3880 {
3881     return kvm_state->kernel_irqchip_required;
3882 }
3883 
3884 bool kvm_kernel_irqchip_split(void)
3885 {
3886     return kvm_state->kernel_irqchip_split == ON_OFF_AUTO_ON;
3887 }
3888 
3889 static void kvm_get_dirty_ring_size(Object *obj, Visitor *v,
3890                                     const char *name, void *opaque,
3891                                     Error **errp)
3892 {
3893     KVMState *s = KVM_STATE(obj);
3894     uint32_t value = s->kvm_dirty_ring_size;
3895 
3896     visit_type_uint32(v, name, &value, errp);
3897 }
3898 
3899 static void kvm_set_dirty_ring_size(Object *obj, Visitor *v,
3900                                     const char *name, void *opaque,
3901                                     Error **errp)
3902 {
3903     KVMState *s = KVM_STATE(obj);
3904     uint32_t value;
3905 
3906     if (s->fd != -1) {
3907         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3908         return;
3909     }
3910 
3911     if (!visit_type_uint32(v, name, &value, errp)) {
3912         return;
3913     }
3914     if (value & (value - 1)) {
3915         error_setg(errp, "dirty-ring-size must be a power of two.");
3916         return;
3917     }
3918 
3919     s->kvm_dirty_ring_size = value;
3920 }
3921 
3922 static char *kvm_get_device(Object *obj,
3923                             Error **errp G_GNUC_UNUSED)
3924 {
3925     KVMState *s = KVM_STATE(obj);
3926 
3927     return g_strdup(s->device);
3928 }
3929 
3930 static void kvm_set_device(Object *obj,
3931                            const char *value,
3932                            Error **errp G_GNUC_UNUSED)
3933 {
3934     KVMState *s = KVM_STATE(obj);
3935 
3936     g_free(s->device);
3937     s->device = g_strdup(value);
3938 }
3939 
3940 static void kvm_set_kvm_rapl(Object *obj, bool value, Error **errp)
3941 {
3942     KVMState *s = KVM_STATE(obj);
3943     s->msr_energy.enable = value;
3944 }
3945 
3946 static void kvm_set_kvm_rapl_socket_path(Object *obj,
3947                                          const char *str,
3948                                          Error **errp)
3949 {
3950     KVMState *s = KVM_STATE(obj);
3951     g_free(s->msr_energy.socket_path);
3952     s->msr_energy.socket_path = g_strdup(str);
3953 }
3954 
3955 static void kvm_accel_instance_init(Object *obj)
3956 {
3957     KVMState *s = KVM_STATE(obj);
3958 
3959     s->fd = -1;
3960     s->vmfd = -1;
3961     s->kvm_shadow_mem = -1;
3962     s->kernel_irqchip_allowed = true;
3963     s->kernel_irqchip_split = ON_OFF_AUTO_AUTO;
3964     /* KVM dirty ring is by default off */
3965     s->kvm_dirty_ring_size = 0;
3966     s->kvm_dirty_ring_with_bitmap = false;
3967     s->kvm_eager_split_size = 0;
3968     s->notify_vmexit = NOTIFY_VMEXIT_OPTION_RUN;
3969     s->notify_window = 0;
3970     s->xen_version = 0;
3971     s->xen_gnttab_max_frames = 64;
3972     s->xen_evtchn_max_pirq = 256;
3973     s->device = NULL;
3974     s->msr_energy.enable = false;
3975 }
3976 
3977 /**
3978  * kvm_gdbstub_sstep_flags():
3979  *
3980  * Returns: SSTEP_* flags that KVM supports for guest debug. The
3981  * support is probed during kvm_init()
3982  */
3983 static int kvm_gdbstub_sstep_flags(AccelState *as)
3984 {
3985     return kvm_sstep_flags;
3986 }
3987 
3988 static void kvm_accel_class_init(ObjectClass *oc, const void *data)
3989 {
3990     AccelClass *ac = ACCEL_CLASS(oc);
3991     ac->name = "KVM";
3992     ac->init_machine = kvm_init;
3993     ac->has_memory = kvm_accel_has_memory;
3994     ac->allowed = &kvm_allowed;
3995     ac->gdbstub_supported_sstep_flags = kvm_gdbstub_sstep_flags;
3996 
3997     object_class_property_add(oc, "kernel-irqchip", "on|off|split",
3998         NULL, kvm_set_kernel_irqchip,
3999         NULL, NULL);
4000     object_class_property_set_description(oc, "kernel-irqchip",
4001         "Configure KVM in-kernel irqchip");
4002 
4003     object_class_property_add(oc, "kvm-shadow-mem", "int",
4004         kvm_get_kvm_shadow_mem, kvm_set_kvm_shadow_mem,
4005         NULL, NULL);
4006     object_class_property_set_description(oc, "kvm-shadow-mem",
4007         "KVM shadow MMU size");
4008 
4009     object_class_property_add(oc, "dirty-ring-size", "uint32",
4010         kvm_get_dirty_ring_size, kvm_set_dirty_ring_size,
4011         NULL, NULL);
4012     object_class_property_set_description(oc, "dirty-ring-size",
4013         "Size of KVM dirty page ring buffer (default: 0, i.e. use bitmap)");
4014 
4015     object_class_property_add_str(oc, "device", kvm_get_device, kvm_set_device);
4016     object_class_property_set_description(oc, "device",
4017         "Path to the device node to use (default: /dev/kvm)");
4018 
4019     object_class_property_add_bool(oc, "rapl",
4020                                    NULL,
4021                                    kvm_set_kvm_rapl);
4022     object_class_property_set_description(oc, "rapl",
4023         "Allow energy related MSRs for RAPL interface in Guest");
4024 
4025     object_class_property_add_str(oc, "rapl-helper-socket", NULL,
4026                                   kvm_set_kvm_rapl_socket_path);
4027     object_class_property_set_description(oc, "rapl-helper-socket",
4028         "Socket Path for comminucating with the Virtual MSR helper daemon");
4029 
4030     kvm_arch_accel_class_init(oc);
4031 }
4032 
4033 static const TypeInfo kvm_accel_type = {
4034     .name = TYPE_KVM_ACCEL,
4035     .parent = TYPE_ACCEL,
4036     .instance_init = kvm_accel_instance_init,
4037     .class_init = kvm_accel_class_init,
4038     .instance_size = sizeof(KVMState),
4039 };
4040 
4041 static void kvm_type_init(void)
4042 {
4043     type_register_static(&kvm_accel_type);
4044 }
4045 
4046 type_init(kvm_type_init);
4047 
4048 typedef struct StatsArgs {
4049     union StatsResultsType {
4050         StatsResultList **stats;
4051         StatsSchemaList **schema;
4052     } result;
4053     strList *names;
4054     Error **errp;
4055 } StatsArgs;
4056 
4057 static StatsList *add_kvmstat_entry(struct kvm_stats_desc *pdesc,
4058                                     uint64_t *stats_data,
4059                                     StatsList *stats_list,
4060                                     Error **errp)
4061 {
4062 
4063     Stats *stats;
4064     uint64List *val_list = NULL;
4065 
4066     /* Only add stats that we understand.  */
4067     switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
4068     case KVM_STATS_TYPE_CUMULATIVE:
4069     case KVM_STATS_TYPE_INSTANT:
4070     case KVM_STATS_TYPE_PEAK:
4071     case KVM_STATS_TYPE_LINEAR_HIST:
4072     case KVM_STATS_TYPE_LOG_HIST:
4073         break;
4074     default:
4075         return stats_list;
4076     }
4077 
4078     switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
4079     case KVM_STATS_UNIT_NONE:
4080     case KVM_STATS_UNIT_BYTES:
4081     case KVM_STATS_UNIT_CYCLES:
4082     case KVM_STATS_UNIT_SECONDS:
4083     case KVM_STATS_UNIT_BOOLEAN:
4084         break;
4085     default:
4086         return stats_list;
4087     }
4088 
4089     switch (pdesc->flags & KVM_STATS_BASE_MASK) {
4090     case KVM_STATS_BASE_POW10:
4091     case KVM_STATS_BASE_POW2:
4092         break;
4093     default:
4094         return stats_list;
4095     }
4096 
4097     /* Alloc and populate data list */
4098     stats = g_new0(Stats, 1);
4099     stats->name = g_strdup(pdesc->name);
4100     stats->value = g_new0(StatsValue, 1);
4101 
4102     if ((pdesc->flags & KVM_STATS_UNIT_MASK) == KVM_STATS_UNIT_BOOLEAN) {
4103         stats->value->u.boolean = *stats_data;
4104         stats->value->type = QTYPE_QBOOL;
4105     } else if (pdesc->size == 1) {
4106         stats->value->u.scalar = *stats_data;
4107         stats->value->type = QTYPE_QNUM;
4108     } else {
4109         int i;
4110         for (i = 0; i < pdesc->size; i++) {
4111             QAPI_LIST_PREPEND(val_list, stats_data[i]);
4112         }
4113         stats->value->u.list = val_list;
4114         stats->value->type = QTYPE_QLIST;
4115     }
4116 
4117     QAPI_LIST_PREPEND(stats_list, stats);
4118     return stats_list;
4119 }
4120 
4121 static StatsSchemaValueList *add_kvmschema_entry(struct kvm_stats_desc *pdesc,
4122                                                  StatsSchemaValueList *list,
4123                                                  Error **errp)
4124 {
4125     StatsSchemaValueList *schema_entry = g_new0(StatsSchemaValueList, 1);
4126     schema_entry->value = g_new0(StatsSchemaValue, 1);
4127 
4128     switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
4129     case KVM_STATS_TYPE_CUMULATIVE:
4130         schema_entry->value->type = STATS_TYPE_CUMULATIVE;
4131         break;
4132     case KVM_STATS_TYPE_INSTANT:
4133         schema_entry->value->type = STATS_TYPE_INSTANT;
4134         break;
4135     case KVM_STATS_TYPE_PEAK:
4136         schema_entry->value->type = STATS_TYPE_PEAK;
4137         break;
4138     case KVM_STATS_TYPE_LINEAR_HIST:
4139         schema_entry->value->type = STATS_TYPE_LINEAR_HISTOGRAM;
4140         schema_entry->value->bucket_size = pdesc->bucket_size;
4141         schema_entry->value->has_bucket_size = true;
4142         break;
4143     case KVM_STATS_TYPE_LOG_HIST:
4144         schema_entry->value->type = STATS_TYPE_LOG2_HISTOGRAM;
4145         break;
4146     default:
4147         goto exit;
4148     }
4149 
4150     switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
4151     case KVM_STATS_UNIT_NONE:
4152         break;
4153     case KVM_STATS_UNIT_BOOLEAN:
4154         schema_entry->value->has_unit = true;
4155         schema_entry->value->unit = STATS_UNIT_BOOLEAN;
4156         break;
4157     case KVM_STATS_UNIT_BYTES:
4158         schema_entry->value->has_unit = true;
4159         schema_entry->value->unit = STATS_UNIT_BYTES;
4160         break;
4161     case KVM_STATS_UNIT_CYCLES:
4162         schema_entry->value->has_unit = true;
4163         schema_entry->value->unit = STATS_UNIT_CYCLES;
4164         break;
4165     case KVM_STATS_UNIT_SECONDS:
4166         schema_entry->value->has_unit = true;
4167         schema_entry->value->unit = STATS_UNIT_SECONDS;
4168         break;
4169     default:
4170         goto exit;
4171     }
4172 
4173     schema_entry->value->exponent = pdesc->exponent;
4174     if (pdesc->exponent) {
4175         switch (pdesc->flags & KVM_STATS_BASE_MASK) {
4176         case KVM_STATS_BASE_POW10:
4177             schema_entry->value->has_base = true;
4178             schema_entry->value->base = 10;
4179             break;
4180         case KVM_STATS_BASE_POW2:
4181             schema_entry->value->has_base = true;
4182             schema_entry->value->base = 2;
4183             break;
4184         default:
4185             goto exit;
4186         }
4187     }
4188 
4189     schema_entry->value->name = g_strdup(pdesc->name);
4190     schema_entry->next = list;
4191     return schema_entry;
4192 exit:
4193     g_free(schema_entry->value);
4194     g_free(schema_entry);
4195     return list;
4196 }
4197 
4198 /* Cached stats descriptors */
4199 typedef struct StatsDescriptors {
4200     const char *ident; /* cache key, currently the StatsTarget */
4201     struct kvm_stats_desc *kvm_stats_desc;
4202     struct kvm_stats_header kvm_stats_header;
4203     QTAILQ_ENTRY(StatsDescriptors) next;
4204 } StatsDescriptors;
4205 
4206 static QTAILQ_HEAD(, StatsDescriptors) stats_descriptors =
4207     QTAILQ_HEAD_INITIALIZER(stats_descriptors);
4208 
4209 /*
4210  * Return the descriptors for 'target', that either have already been read
4211  * or are retrieved from 'stats_fd'.
4212  */
4213 static StatsDescriptors *find_stats_descriptors(StatsTarget target, int stats_fd,
4214                                                 Error **errp)
4215 {
4216     StatsDescriptors *descriptors;
4217     const char *ident;
4218     struct kvm_stats_desc *kvm_stats_desc;
4219     struct kvm_stats_header *kvm_stats_header;
4220     size_t size_desc;
4221     ssize_t ret;
4222 
4223     ident = StatsTarget_str(target);
4224     QTAILQ_FOREACH(descriptors, &stats_descriptors, next) {
4225         if (g_str_equal(descriptors->ident, ident)) {
4226             return descriptors;
4227         }
4228     }
4229 
4230     descriptors = g_new0(StatsDescriptors, 1);
4231 
4232     /* Read stats header */
4233     kvm_stats_header = &descriptors->kvm_stats_header;
4234     ret = pread(stats_fd, kvm_stats_header, sizeof(*kvm_stats_header), 0);
4235     if (ret != sizeof(*kvm_stats_header)) {
4236         error_setg(errp, "KVM stats: failed to read stats header: "
4237                    "expected %zu actual %zu",
4238                    sizeof(*kvm_stats_header), ret);
4239         g_free(descriptors);
4240         return NULL;
4241     }
4242     size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4243 
4244     /* Read stats descriptors */
4245     kvm_stats_desc = g_malloc0_n(kvm_stats_header->num_desc, size_desc);
4246     ret = pread(stats_fd, kvm_stats_desc,
4247                 size_desc * kvm_stats_header->num_desc,
4248                 kvm_stats_header->desc_offset);
4249 
4250     if (ret != size_desc * kvm_stats_header->num_desc) {
4251         error_setg(errp, "KVM stats: failed to read stats descriptors: "
4252                    "expected %zu actual %zu",
4253                    size_desc * kvm_stats_header->num_desc, ret);
4254         g_free(descriptors);
4255         g_free(kvm_stats_desc);
4256         return NULL;
4257     }
4258     descriptors->kvm_stats_desc = kvm_stats_desc;
4259     descriptors->ident = ident;
4260     QTAILQ_INSERT_TAIL(&stats_descriptors, descriptors, next);
4261     return descriptors;
4262 }
4263 
4264 static void query_stats(StatsResultList **result, StatsTarget target,
4265                         strList *names, int stats_fd, CPUState *cpu,
4266                         Error **errp)
4267 {
4268     struct kvm_stats_desc *kvm_stats_desc;
4269     struct kvm_stats_header *kvm_stats_header;
4270     StatsDescriptors *descriptors;
4271     g_autofree uint64_t *stats_data = NULL;
4272     struct kvm_stats_desc *pdesc;
4273     StatsList *stats_list = NULL;
4274     size_t size_desc, size_data = 0;
4275     ssize_t ret;
4276     int i;
4277 
4278     descriptors = find_stats_descriptors(target, stats_fd, errp);
4279     if (!descriptors) {
4280         return;
4281     }
4282 
4283     kvm_stats_header = &descriptors->kvm_stats_header;
4284     kvm_stats_desc = descriptors->kvm_stats_desc;
4285     size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4286 
4287     /* Tally the total data size; read schema data */
4288     for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4289         pdesc = (void *)kvm_stats_desc + i * size_desc;
4290         size_data += pdesc->size * sizeof(*stats_data);
4291     }
4292 
4293     stats_data = g_malloc0(size_data);
4294     ret = pread(stats_fd, stats_data, size_data, kvm_stats_header->data_offset);
4295 
4296     if (ret != size_data) {
4297         error_setg(errp, "KVM stats: failed to read data: "
4298                    "expected %zu actual %zu", size_data, ret);
4299         return;
4300     }
4301 
4302     for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4303         uint64_t *stats;
4304         pdesc = (void *)kvm_stats_desc + i * size_desc;
4305 
4306         /* Add entry to the list */
4307         stats = (void *)stats_data + pdesc->offset;
4308         if (!apply_str_list_filter(pdesc->name, names)) {
4309             continue;
4310         }
4311         stats_list = add_kvmstat_entry(pdesc, stats, stats_list, errp);
4312     }
4313 
4314     if (!stats_list) {
4315         return;
4316     }
4317 
4318     switch (target) {
4319     case STATS_TARGET_VM:
4320         add_stats_entry(result, STATS_PROVIDER_KVM, NULL, stats_list);
4321         break;
4322     case STATS_TARGET_VCPU:
4323         add_stats_entry(result, STATS_PROVIDER_KVM,
4324                         cpu->parent_obj.canonical_path,
4325                         stats_list);
4326         break;
4327     default:
4328         g_assert_not_reached();
4329     }
4330 }
4331 
4332 static void query_stats_schema(StatsSchemaList **result, StatsTarget target,
4333                                int stats_fd, Error **errp)
4334 {
4335     struct kvm_stats_desc *kvm_stats_desc;
4336     struct kvm_stats_header *kvm_stats_header;
4337     StatsDescriptors *descriptors;
4338     struct kvm_stats_desc *pdesc;
4339     StatsSchemaValueList *stats_list = NULL;
4340     size_t size_desc;
4341     int i;
4342 
4343     descriptors = find_stats_descriptors(target, stats_fd, errp);
4344     if (!descriptors) {
4345         return;
4346     }
4347 
4348     kvm_stats_header = &descriptors->kvm_stats_header;
4349     kvm_stats_desc = descriptors->kvm_stats_desc;
4350     size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4351 
4352     /* Tally the total data size; read schema data */
4353     for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4354         pdesc = (void *)kvm_stats_desc + i * size_desc;
4355         stats_list = add_kvmschema_entry(pdesc, stats_list, errp);
4356     }
4357 
4358     add_stats_schema(result, STATS_PROVIDER_KVM, target, stats_list);
4359 }
4360 
4361 static void query_stats_vcpu(CPUState *cpu, StatsArgs *kvm_stats_args)
4362 {
4363     int stats_fd = cpu->kvm_vcpu_stats_fd;
4364     Error *local_err = NULL;
4365 
4366     if (stats_fd == -1) {
4367         error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
4368         error_propagate(kvm_stats_args->errp, local_err);
4369         return;
4370     }
4371     query_stats(kvm_stats_args->result.stats, STATS_TARGET_VCPU,
4372                 kvm_stats_args->names, stats_fd, cpu,
4373                 kvm_stats_args->errp);
4374 }
4375 
4376 static void query_stats_schema_vcpu(CPUState *cpu, StatsArgs *kvm_stats_args)
4377 {
4378     int stats_fd = cpu->kvm_vcpu_stats_fd;
4379     Error *local_err = NULL;
4380 
4381     if (stats_fd == -1) {
4382         error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
4383         error_propagate(kvm_stats_args->errp, local_err);
4384         return;
4385     }
4386     query_stats_schema(kvm_stats_args->result.schema, STATS_TARGET_VCPU, stats_fd,
4387                        kvm_stats_args->errp);
4388 }
4389 
4390 static void query_stats_cb(StatsResultList **result, StatsTarget target,
4391                            strList *names, strList *targets, Error **errp)
4392 {
4393     KVMState *s = kvm_state;
4394     CPUState *cpu;
4395     int stats_fd;
4396 
4397     switch (target) {
4398     case STATS_TARGET_VM:
4399     {
4400         stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
4401         if (stats_fd == -1) {
4402             error_setg_errno(errp, errno, "KVM stats: ioctl failed");
4403             return;
4404         }
4405         query_stats(result, target, names, stats_fd, NULL, errp);
4406         close(stats_fd);
4407         break;
4408     }
4409     case STATS_TARGET_VCPU:
4410     {
4411         StatsArgs stats_args;
4412         stats_args.result.stats = result;
4413         stats_args.names = names;
4414         stats_args.errp = errp;
4415         CPU_FOREACH(cpu) {
4416             if (!apply_str_list_filter(cpu->parent_obj.canonical_path, targets)) {
4417                 continue;
4418             }
4419             query_stats_vcpu(cpu, &stats_args);
4420         }
4421         break;
4422     }
4423     default:
4424         break;
4425     }
4426 }
4427 
4428 void query_stats_schemas_cb(StatsSchemaList **result, Error **errp)
4429 {
4430     StatsArgs stats_args;
4431     KVMState *s = kvm_state;
4432     int stats_fd;
4433 
4434     stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
4435     if (stats_fd == -1) {
4436         error_setg_errno(errp, errno, "KVM stats: ioctl failed");
4437         return;
4438     }
4439     query_stats_schema(result, STATS_TARGET_VM, stats_fd, errp);
4440     close(stats_fd);
4441 
4442     if (first_cpu) {
4443         stats_args.result.schema = result;
4444         stats_args.errp = errp;
4445         query_stats_schema_vcpu(first_cpu, &stats_args);
4446     }
4447 }
4448 
4449 void kvm_mark_guest_state_protected(void)
4450 {
4451     kvm_state->guest_state_protected = true;
4452 }
4453 
4454 int kvm_create_guest_memfd(uint64_t size, uint64_t flags, Error **errp)
4455 {
4456     int fd;
4457     struct kvm_create_guest_memfd guest_memfd = {
4458         .size = size,
4459         .flags = flags,
4460     };
4461 
4462     if (!kvm_guest_memfd_supported) {
4463         error_setg(errp, "KVM does not support guest_memfd");
4464         return -1;
4465     }
4466 
4467     fd = kvm_vm_ioctl(kvm_state, KVM_CREATE_GUEST_MEMFD, &guest_memfd);
4468     if (fd < 0) {
4469         error_setg_errno(errp, errno, "Error creating KVM guest_memfd");
4470         return -1;
4471     }
4472 
4473     return fd;
4474 }
4475