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