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