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