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