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