xref: /qemu/accel/kvm/kvm-all.c (revision 7c1f51bf)
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                     if (kvm_state->kvm_dirty_ring_with_bitmap) {
1365                         kvm_slot_sync_dirty_pages(mem);
1366                         kvm_slot_get_dirty_log(kvm_state, mem);
1367                     }
1368                 } else {
1369                     kvm_slot_get_dirty_log(kvm_state, mem);
1370                 }
1371                 kvm_slot_sync_dirty_pages(mem);
1372             }
1373 
1374             /* unregister the slot */
1375             g_free(mem->dirty_bmap);
1376             mem->dirty_bmap = NULL;
1377             mem->memory_size = 0;
1378             mem->flags = 0;
1379             err = kvm_set_user_memory_region(kml, mem, false);
1380             if (err) {
1381                 fprintf(stderr, "%s: error unregistering slot: %s\n",
1382                         __func__, strerror(-err));
1383                 abort();
1384             }
1385             start_addr += slot_size;
1386             size -= slot_size;
1387         } while (size);
1388         return;
1389     }
1390 
1391     /* register the new slot */
1392     do {
1393         slot_size = MIN(kvm_max_slot_size, size);
1394         mem = kvm_alloc_slot(kml);
1395         mem->as_id = kml->as_id;
1396         mem->memory_size = slot_size;
1397         mem->start_addr = start_addr;
1398         mem->ram_start_offset = ram_start_offset;
1399         mem->ram = ram;
1400         mem->flags = kvm_mem_flags(mr);
1401         kvm_slot_init_dirty_bitmap(mem);
1402         err = kvm_set_user_memory_region(kml, mem, true);
1403         if (err) {
1404             fprintf(stderr, "%s: error registering slot: %s\n", __func__,
1405                     strerror(-err));
1406             abort();
1407         }
1408         start_addr += slot_size;
1409         ram_start_offset += slot_size;
1410         ram += slot_size;
1411         size -= slot_size;
1412     } while (size);
1413 }
1414 
1415 static void *kvm_dirty_ring_reaper_thread(void *data)
1416 {
1417     KVMState *s = data;
1418     struct KVMDirtyRingReaper *r = &s->reaper;
1419 
1420     rcu_register_thread();
1421 
1422     trace_kvm_dirty_ring_reaper("init");
1423 
1424     while (true) {
1425         r->reaper_state = KVM_DIRTY_RING_REAPER_WAIT;
1426         trace_kvm_dirty_ring_reaper("wait");
1427         /*
1428          * TODO: provide a smarter timeout rather than a constant?
1429          */
1430         sleep(1);
1431 
1432         /* keep sleeping so that dirtylimit not be interfered by reaper */
1433         if (dirtylimit_in_service()) {
1434             continue;
1435         }
1436 
1437         trace_kvm_dirty_ring_reaper("wakeup");
1438         r->reaper_state = KVM_DIRTY_RING_REAPER_REAPING;
1439 
1440         qemu_mutex_lock_iothread();
1441         kvm_dirty_ring_reap(s, NULL);
1442         qemu_mutex_unlock_iothread();
1443 
1444         r->reaper_iteration++;
1445     }
1446 
1447     trace_kvm_dirty_ring_reaper("exit");
1448 
1449     rcu_unregister_thread();
1450 
1451     return NULL;
1452 }
1453 
1454 static int kvm_dirty_ring_reaper_init(KVMState *s)
1455 {
1456     struct KVMDirtyRingReaper *r = &s->reaper;
1457 
1458     qemu_thread_create(&r->reaper_thr, "kvm-reaper",
1459                        kvm_dirty_ring_reaper_thread,
1460                        s, QEMU_THREAD_JOINABLE);
1461 
1462     return 0;
1463 }
1464 
1465 static int kvm_dirty_ring_init(KVMState *s)
1466 {
1467     uint32_t ring_size = s->kvm_dirty_ring_size;
1468     uint64_t ring_bytes = ring_size * sizeof(struct kvm_dirty_gfn);
1469     unsigned int capability = KVM_CAP_DIRTY_LOG_RING;
1470     int ret;
1471 
1472     s->kvm_dirty_ring_size = 0;
1473     s->kvm_dirty_ring_bytes = 0;
1474 
1475     /* Bail if the dirty ring size isn't specified */
1476     if (!ring_size) {
1477         return 0;
1478     }
1479 
1480     /*
1481      * Read the max supported pages. Fall back to dirty logging mode
1482      * if the dirty ring isn't supported.
1483      */
1484     ret = kvm_vm_check_extension(s, capability);
1485     if (ret <= 0) {
1486         capability = KVM_CAP_DIRTY_LOG_RING_ACQ_REL;
1487         ret = kvm_vm_check_extension(s, capability);
1488     }
1489 
1490     if (ret <= 0) {
1491         warn_report("KVM dirty ring not available, using bitmap method");
1492         return 0;
1493     }
1494 
1495     if (ring_bytes > ret) {
1496         error_report("KVM dirty ring size %" PRIu32 " too big "
1497                      "(maximum is %ld).  Please use a smaller value.",
1498                      ring_size, (long)ret / sizeof(struct kvm_dirty_gfn));
1499         return -EINVAL;
1500     }
1501 
1502     ret = kvm_vm_enable_cap(s, capability, 0, ring_bytes);
1503     if (ret) {
1504         error_report("Enabling of KVM dirty ring failed: %s. "
1505                      "Suggested minimum value is 1024.", strerror(-ret));
1506         return -EIO;
1507     }
1508 
1509     /* Enable the backup bitmap if it is supported */
1510     ret = kvm_vm_check_extension(s, KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP);
1511     if (ret > 0) {
1512         ret = kvm_vm_enable_cap(s, KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP, 0);
1513         if (ret) {
1514             error_report("Enabling of KVM dirty ring's backup bitmap failed: "
1515                          "%s. ", strerror(-ret));
1516             return -EIO;
1517         }
1518 
1519         s->kvm_dirty_ring_with_bitmap = true;
1520     }
1521 
1522     s->kvm_dirty_ring_size = ring_size;
1523     s->kvm_dirty_ring_bytes = ring_bytes;
1524 
1525     return 0;
1526 }
1527 
1528 static void kvm_region_add(MemoryListener *listener,
1529                            MemoryRegionSection *section)
1530 {
1531     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1532     KVMMemoryUpdate *update;
1533 
1534     update = g_new0(KVMMemoryUpdate, 1);
1535     update->section = *section;
1536 
1537     QSIMPLEQ_INSERT_TAIL(&kml->transaction_add, update, next);
1538 }
1539 
1540 static void kvm_region_del(MemoryListener *listener,
1541                            MemoryRegionSection *section)
1542 {
1543     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1544     KVMMemoryUpdate *update;
1545 
1546     update = g_new0(KVMMemoryUpdate, 1);
1547     update->section = *section;
1548 
1549     QSIMPLEQ_INSERT_TAIL(&kml->transaction_del, update, next);
1550 }
1551 
1552 static void kvm_region_commit(MemoryListener *listener)
1553 {
1554     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener,
1555                                           listener);
1556     KVMMemoryUpdate *u1, *u2;
1557     bool need_inhibit = false;
1558 
1559     if (QSIMPLEQ_EMPTY(&kml->transaction_add) &&
1560         QSIMPLEQ_EMPTY(&kml->transaction_del)) {
1561         return;
1562     }
1563 
1564     /*
1565      * We have to be careful when regions to add overlap with ranges to remove.
1566      * We have to simulate atomic KVM memslot updates by making sure no ioctl()
1567      * is currently active.
1568      *
1569      * The lists are order by addresses, so it's easy to find overlaps.
1570      */
1571     u1 = QSIMPLEQ_FIRST(&kml->transaction_del);
1572     u2 = QSIMPLEQ_FIRST(&kml->transaction_add);
1573     while (u1 && u2) {
1574         Range r1, r2;
1575 
1576         range_init_nofail(&r1, u1->section.offset_within_address_space,
1577                           int128_get64(u1->section.size));
1578         range_init_nofail(&r2, u2->section.offset_within_address_space,
1579                           int128_get64(u2->section.size));
1580 
1581         if (range_overlaps_range(&r1, &r2)) {
1582             need_inhibit = true;
1583             break;
1584         }
1585         if (range_lob(&r1) < range_lob(&r2)) {
1586             u1 = QSIMPLEQ_NEXT(u1, next);
1587         } else {
1588             u2 = QSIMPLEQ_NEXT(u2, next);
1589         }
1590     }
1591 
1592     kvm_slots_lock();
1593     if (need_inhibit) {
1594         accel_ioctl_inhibit_begin();
1595     }
1596 
1597     /* Remove all memslots before adding the new ones. */
1598     while (!QSIMPLEQ_EMPTY(&kml->transaction_del)) {
1599         u1 = QSIMPLEQ_FIRST(&kml->transaction_del);
1600         QSIMPLEQ_REMOVE_HEAD(&kml->transaction_del, next);
1601 
1602         kvm_set_phys_mem(kml, &u1->section, false);
1603         memory_region_unref(u1->section.mr);
1604 
1605         g_free(u1);
1606     }
1607     while (!QSIMPLEQ_EMPTY(&kml->transaction_add)) {
1608         u1 = QSIMPLEQ_FIRST(&kml->transaction_add);
1609         QSIMPLEQ_REMOVE_HEAD(&kml->transaction_add, next);
1610 
1611         memory_region_ref(u1->section.mr);
1612         kvm_set_phys_mem(kml, &u1->section, true);
1613 
1614         g_free(u1);
1615     }
1616 
1617     if (need_inhibit) {
1618         accel_ioctl_inhibit_end();
1619     }
1620     kvm_slots_unlock();
1621 }
1622 
1623 static void kvm_log_sync(MemoryListener *listener,
1624                          MemoryRegionSection *section)
1625 {
1626     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1627 
1628     kvm_slots_lock();
1629     kvm_physical_sync_dirty_bitmap(kml, section);
1630     kvm_slots_unlock();
1631 }
1632 
1633 static void kvm_log_sync_global(MemoryListener *l, bool last_stage)
1634 {
1635     KVMMemoryListener *kml = container_of(l, KVMMemoryListener, listener);
1636     KVMState *s = kvm_state;
1637     KVMSlot *mem;
1638     int i;
1639 
1640     /* Flush all kernel dirty addresses into KVMSlot dirty bitmap */
1641     kvm_dirty_ring_flush();
1642 
1643     /*
1644      * TODO: make this faster when nr_slots is big while there are
1645      * only a few used slots (small VMs).
1646      */
1647     kvm_slots_lock();
1648     for (i = 0; i < s->nr_slots; i++) {
1649         mem = &kml->slots[i];
1650         if (mem->memory_size && mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1651             kvm_slot_sync_dirty_pages(mem);
1652 
1653             if (s->kvm_dirty_ring_with_bitmap && last_stage &&
1654                 kvm_slot_get_dirty_log(s, mem)) {
1655                 kvm_slot_sync_dirty_pages(mem);
1656             }
1657 
1658             /*
1659              * This is not needed by KVM_GET_DIRTY_LOG because the
1660              * ioctl will unconditionally overwrite the whole region.
1661              * However kvm dirty ring has no such side effect.
1662              */
1663             kvm_slot_reset_dirty_pages(mem);
1664         }
1665     }
1666     kvm_slots_unlock();
1667 }
1668 
1669 static void kvm_log_clear(MemoryListener *listener,
1670                           MemoryRegionSection *section)
1671 {
1672     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1673     int r;
1674 
1675     r = kvm_physical_log_clear(kml, section);
1676     if (r < 0) {
1677         error_report_once("%s: kvm log clear failed: mr=%s "
1678                           "offset=%"HWADDR_PRIx" size=%"PRIx64, __func__,
1679                           section->mr->name, section->offset_within_region,
1680                           int128_get64(section->size));
1681         abort();
1682     }
1683 }
1684 
1685 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
1686                                   MemoryRegionSection *section,
1687                                   bool match_data, uint64_t data,
1688                                   EventNotifier *e)
1689 {
1690     int fd = event_notifier_get_fd(e);
1691     int r;
1692 
1693     r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
1694                                data, true, int128_get64(section->size),
1695                                match_data);
1696     if (r < 0) {
1697         fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1698                 __func__, strerror(-r), -r);
1699         abort();
1700     }
1701 }
1702 
1703 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
1704                                   MemoryRegionSection *section,
1705                                   bool match_data, uint64_t data,
1706                                   EventNotifier *e)
1707 {
1708     int fd = event_notifier_get_fd(e);
1709     int r;
1710 
1711     r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
1712                                data, false, int128_get64(section->size),
1713                                match_data);
1714     if (r < 0) {
1715         fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1716                 __func__, strerror(-r), -r);
1717         abort();
1718     }
1719 }
1720 
1721 static void kvm_io_ioeventfd_add(MemoryListener *listener,
1722                                  MemoryRegionSection *section,
1723                                  bool match_data, uint64_t data,
1724                                  EventNotifier *e)
1725 {
1726     int fd = event_notifier_get_fd(e);
1727     int r;
1728 
1729     r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
1730                               data, true, int128_get64(section->size),
1731                               match_data);
1732     if (r < 0) {
1733         fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1734                 __func__, strerror(-r), -r);
1735         abort();
1736     }
1737 }
1738 
1739 static void kvm_io_ioeventfd_del(MemoryListener *listener,
1740                                  MemoryRegionSection *section,
1741                                  bool match_data, uint64_t data,
1742                                  EventNotifier *e)
1743 
1744 {
1745     int fd = event_notifier_get_fd(e);
1746     int r;
1747 
1748     r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
1749                               data, false, int128_get64(section->size),
1750                               match_data);
1751     if (r < 0) {
1752         fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1753                 __func__, strerror(-r), -r);
1754         abort();
1755     }
1756 }
1757 
1758 void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
1759                                   AddressSpace *as, int as_id, const char *name)
1760 {
1761     int i;
1762 
1763     kml->slots = g_new0(KVMSlot, s->nr_slots);
1764     kml->as_id = as_id;
1765 
1766     for (i = 0; i < s->nr_slots; i++) {
1767         kml->slots[i].slot = i;
1768     }
1769 
1770     QSIMPLEQ_INIT(&kml->transaction_add);
1771     QSIMPLEQ_INIT(&kml->transaction_del);
1772 
1773     kml->listener.region_add = kvm_region_add;
1774     kml->listener.region_del = kvm_region_del;
1775     kml->listener.commit = kvm_region_commit;
1776     kml->listener.log_start = kvm_log_start;
1777     kml->listener.log_stop = kvm_log_stop;
1778     kml->listener.priority = 10;
1779     kml->listener.name = name;
1780 
1781     if (s->kvm_dirty_ring_size) {
1782         kml->listener.log_sync_global = kvm_log_sync_global;
1783     } else {
1784         kml->listener.log_sync = kvm_log_sync;
1785         kml->listener.log_clear = kvm_log_clear;
1786     }
1787 
1788     memory_listener_register(&kml->listener, as);
1789 
1790     for (i = 0; i < s->nr_as; ++i) {
1791         if (!s->as[i].as) {
1792             s->as[i].as = as;
1793             s->as[i].ml = kml;
1794             break;
1795         }
1796     }
1797 }
1798 
1799 static MemoryListener kvm_io_listener = {
1800     .name = "kvm-io",
1801     .eventfd_add = kvm_io_ioeventfd_add,
1802     .eventfd_del = kvm_io_ioeventfd_del,
1803     .priority = 10,
1804 };
1805 
1806 int kvm_set_irq(KVMState *s, int irq, int level)
1807 {
1808     struct kvm_irq_level event;
1809     int ret;
1810 
1811     assert(kvm_async_interrupts_enabled());
1812 
1813     event.level = level;
1814     event.irq = irq;
1815     ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
1816     if (ret < 0) {
1817         perror("kvm_set_irq");
1818         abort();
1819     }
1820 
1821     return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
1822 }
1823 
1824 #ifdef KVM_CAP_IRQ_ROUTING
1825 typedef struct KVMMSIRoute {
1826     struct kvm_irq_routing_entry kroute;
1827     QTAILQ_ENTRY(KVMMSIRoute) entry;
1828 } KVMMSIRoute;
1829 
1830 static void set_gsi(KVMState *s, unsigned int gsi)
1831 {
1832     set_bit(gsi, s->used_gsi_bitmap);
1833 }
1834 
1835 static void clear_gsi(KVMState *s, unsigned int gsi)
1836 {
1837     clear_bit(gsi, s->used_gsi_bitmap);
1838 }
1839 
1840 void kvm_init_irq_routing(KVMState *s)
1841 {
1842     int gsi_count, i;
1843 
1844     gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
1845     if (gsi_count > 0) {
1846         /* Round up so we can search ints using ffs */
1847         s->used_gsi_bitmap = bitmap_new(gsi_count);
1848         s->gsi_count = gsi_count;
1849     }
1850 
1851     s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
1852     s->nr_allocated_irq_routes = 0;
1853 
1854     if (!kvm_direct_msi_allowed) {
1855         for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
1856             QTAILQ_INIT(&s->msi_hashtab[i]);
1857         }
1858     }
1859 
1860     kvm_arch_init_irq_routing(s);
1861 }
1862 
1863 void kvm_irqchip_commit_routes(KVMState *s)
1864 {
1865     int ret;
1866 
1867     if (kvm_gsi_direct_mapping()) {
1868         return;
1869     }
1870 
1871     if (!kvm_gsi_routing_enabled()) {
1872         return;
1873     }
1874 
1875     s->irq_routes->flags = 0;
1876     trace_kvm_irqchip_commit_routes();
1877     ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1878     assert(ret == 0);
1879 }
1880 
1881 static void kvm_add_routing_entry(KVMState *s,
1882                                   struct kvm_irq_routing_entry *entry)
1883 {
1884     struct kvm_irq_routing_entry *new;
1885     int n, size;
1886 
1887     if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1888         n = s->nr_allocated_irq_routes * 2;
1889         if (n < 64) {
1890             n = 64;
1891         }
1892         size = sizeof(struct kvm_irq_routing);
1893         size += n * sizeof(*new);
1894         s->irq_routes = g_realloc(s->irq_routes, size);
1895         s->nr_allocated_irq_routes = n;
1896     }
1897     n = s->irq_routes->nr++;
1898     new = &s->irq_routes->entries[n];
1899 
1900     *new = *entry;
1901 
1902     set_gsi(s, entry->gsi);
1903 }
1904 
1905 static int kvm_update_routing_entry(KVMState *s,
1906                                     struct kvm_irq_routing_entry *new_entry)
1907 {
1908     struct kvm_irq_routing_entry *entry;
1909     int n;
1910 
1911     for (n = 0; n < s->irq_routes->nr; n++) {
1912         entry = &s->irq_routes->entries[n];
1913         if (entry->gsi != new_entry->gsi) {
1914             continue;
1915         }
1916 
1917         if(!memcmp(entry, new_entry, sizeof *entry)) {
1918             return 0;
1919         }
1920 
1921         *entry = *new_entry;
1922 
1923         return 0;
1924     }
1925 
1926     return -ESRCH;
1927 }
1928 
1929 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1930 {
1931     struct kvm_irq_routing_entry e = {};
1932 
1933     assert(pin < s->gsi_count);
1934 
1935     e.gsi = irq;
1936     e.type = KVM_IRQ_ROUTING_IRQCHIP;
1937     e.flags = 0;
1938     e.u.irqchip.irqchip = irqchip;
1939     e.u.irqchip.pin = pin;
1940     kvm_add_routing_entry(s, &e);
1941 }
1942 
1943 void kvm_irqchip_release_virq(KVMState *s, int virq)
1944 {
1945     struct kvm_irq_routing_entry *e;
1946     int i;
1947 
1948     if (kvm_gsi_direct_mapping()) {
1949         return;
1950     }
1951 
1952     for (i = 0; i < s->irq_routes->nr; i++) {
1953         e = &s->irq_routes->entries[i];
1954         if (e->gsi == virq) {
1955             s->irq_routes->nr--;
1956             *e = s->irq_routes->entries[s->irq_routes->nr];
1957         }
1958     }
1959     clear_gsi(s, virq);
1960     kvm_arch_release_virq_post(virq);
1961     trace_kvm_irqchip_release_virq(virq);
1962 }
1963 
1964 void kvm_irqchip_add_change_notifier(Notifier *n)
1965 {
1966     notifier_list_add(&kvm_irqchip_change_notifiers, n);
1967 }
1968 
1969 void kvm_irqchip_remove_change_notifier(Notifier *n)
1970 {
1971     notifier_remove(n);
1972 }
1973 
1974 void kvm_irqchip_change_notify(void)
1975 {
1976     notifier_list_notify(&kvm_irqchip_change_notifiers, NULL);
1977 }
1978 
1979 static unsigned int kvm_hash_msi(uint32_t data)
1980 {
1981     /* This is optimized for IA32 MSI layout. However, no other arch shall
1982      * repeat the mistake of not providing a direct MSI injection API. */
1983     return data & 0xff;
1984 }
1985 
1986 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1987 {
1988     KVMMSIRoute *route, *next;
1989     unsigned int hash;
1990 
1991     for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1992         QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1993             kvm_irqchip_release_virq(s, route->kroute.gsi);
1994             QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1995             g_free(route);
1996         }
1997     }
1998 }
1999 
2000 static int kvm_irqchip_get_virq(KVMState *s)
2001 {
2002     int next_virq;
2003 
2004     /*
2005      * PIC and IOAPIC share the first 16 GSI numbers, thus the available
2006      * GSI numbers are more than the number of IRQ route. Allocating a GSI
2007      * number can succeed even though a new route entry cannot be added.
2008      * When this happens, flush dynamic MSI entries to free IRQ route entries.
2009      */
2010     if (!kvm_direct_msi_allowed && s->irq_routes->nr == s->gsi_count) {
2011         kvm_flush_dynamic_msi_routes(s);
2012     }
2013 
2014     /* Return the lowest unused GSI in the bitmap */
2015     next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
2016     if (next_virq >= s->gsi_count) {
2017         return -ENOSPC;
2018     } else {
2019         return next_virq;
2020     }
2021 }
2022 
2023 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
2024 {
2025     unsigned int hash = kvm_hash_msi(msg.data);
2026     KVMMSIRoute *route;
2027 
2028     QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
2029         if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
2030             route->kroute.u.msi.address_hi == (msg.address >> 32) &&
2031             route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
2032             return route;
2033         }
2034     }
2035     return NULL;
2036 }
2037 
2038 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
2039 {
2040     struct kvm_msi msi;
2041     KVMMSIRoute *route;
2042 
2043     if (kvm_direct_msi_allowed) {
2044         msi.address_lo = (uint32_t)msg.address;
2045         msi.address_hi = msg.address >> 32;
2046         msi.data = le32_to_cpu(msg.data);
2047         msi.flags = 0;
2048         memset(msi.pad, 0, sizeof(msi.pad));
2049 
2050         return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
2051     }
2052 
2053     route = kvm_lookup_msi_route(s, msg);
2054     if (!route) {
2055         int virq;
2056 
2057         virq = kvm_irqchip_get_virq(s);
2058         if (virq < 0) {
2059             return virq;
2060         }
2061 
2062         route = g_new0(KVMMSIRoute, 1);
2063         route->kroute.gsi = virq;
2064         route->kroute.type = KVM_IRQ_ROUTING_MSI;
2065         route->kroute.flags = 0;
2066         route->kroute.u.msi.address_lo = (uint32_t)msg.address;
2067         route->kroute.u.msi.address_hi = msg.address >> 32;
2068         route->kroute.u.msi.data = le32_to_cpu(msg.data);
2069 
2070         kvm_add_routing_entry(s, &route->kroute);
2071         kvm_irqchip_commit_routes(s);
2072 
2073         QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
2074                            entry);
2075     }
2076 
2077     assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
2078 
2079     return kvm_set_irq(s, route->kroute.gsi, 1);
2080 }
2081 
2082 int kvm_irqchip_add_msi_route(KVMRouteChange *c, int vector, PCIDevice *dev)
2083 {
2084     struct kvm_irq_routing_entry kroute = {};
2085     int virq;
2086     KVMState *s = c->s;
2087     MSIMessage msg = {0, 0};
2088 
2089     if (pci_available && dev) {
2090         msg = pci_get_msi_message(dev, vector);
2091     }
2092 
2093     if (kvm_gsi_direct_mapping()) {
2094         return kvm_arch_msi_data_to_gsi(msg.data);
2095     }
2096 
2097     if (!kvm_gsi_routing_enabled()) {
2098         return -ENOSYS;
2099     }
2100 
2101     virq = kvm_irqchip_get_virq(s);
2102     if (virq < 0) {
2103         return virq;
2104     }
2105 
2106     kroute.gsi = virq;
2107     kroute.type = KVM_IRQ_ROUTING_MSI;
2108     kroute.flags = 0;
2109     kroute.u.msi.address_lo = (uint32_t)msg.address;
2110     kroute.u.msi.address_hi = msg.address >> 32;
2111     kroute.u.msi.data = le32_to_cpu(msg.data);
2112     if (pci_available && kvm_msi_devid_required()) {
2113         kroute.flags = KVM_MSI_VALID_DEVID;
2114         kroute.u.msi.devid = pci_requester_id(dev);
2115     }
2116     if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
2117         kvm_irqchip_release_virq(s, virq);
2118         return -EINVAL;
2119     }
2120 
2121     trace_kvm_irqchip_add_msi_route(dev ? dev->name : (char *)"N/A",
2122                                     vector, virq);
2123 
2124     kvm_add_routing_entry(s, &kroute);
2125     kvm_arch_add_msi_route_post(&kroute, vector, dev);
2126     c->changes++;
2127 
2128     return virq;
2129 }
2130 
2131 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
2132                                  PCIDevice *dev)
2133 {
2134     struct kvm_irq_routing_entry kroute = {};
2135 
2136     if (kvm_gsi_direct_mapping()) {
2137         return 0;
2138     }
2139 
2140     if (!kvm_irqchip_in_kernel()) {
2141         return -ENOSYS;
2142     }
2143 
2144     kroute.gsi = virq;
2145     kroute.type = KVM_IRQ_ROUTING_MSI;
2146     kroute.flags = 0;
2147     kroute.u.msi.address_lo = (uint32_t)msg.address;
2148     kroute.u.msi.address_hi = msg.address >> 32;
2149     kroute.u.msi.data = le32_to_cpu(msg.data);
2150     if (pci_available && kvm_msi_devid_required()) {
2151         kroute.flags = KVM_MSI_VALID_DEVID;
2152         kroute.u.msi.devid = pci_requester_id(dev);
2153     }
2154     if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
2155         return -EINVAL;
2156     }
2157 
2158     trace_kvm_irqchip_update_msi_route(virq);
2159 
2160     return kvm_update_routing_entry(s, &kroute);
2161 }
2162 
2163 static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
2164                                     EventNotifier *resample, int virq,
2165                                     bool assign)
2166 {
2167     int fd = event_notifier_get_fd(event);
2168     int rfd = resample ? event_notifier_get_fd(resample) : -1;
2169 
2170     struct kvm_irqfd irqfd = {
2171         .fd = fd,
2172         .gsi = virq,
2173         .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
2174     };
2175 
2176     if (rfd != -1) {
2177         assert(assign);
2178         if (kvm_irqchip_is_split()) {
2179             /*
2180              * When the slow irqchip (e.g. IOAPIC) is in the
2181              * userspace, KVM kernel resamplefd will not work because
2182              * the EOI of the interrupt will be delivered to userspace
2183              * instead, so the KVM kernel resamplefd kick will be
2184              * skipped.  The userspace here mimics what the kernel
2185              * provides with resamplefd, remember the resamplefd and
2186              * kick it when we receive EOI of this IRQ.
2187              *
2188              * This is hackery because IOAPIC is mostly bypassed
2189              * (except EOI broadcasts) when irqfd is used.  However
2190              * this can bring much performance back for split irqchip
2191              * with INTx IRQs (for VFIO, this gives 93% perf of the
2192              * full fast path, which is 46% perf boost comparing to
2193              * the INTx slow path).
2194              */
2195             kvm_resample_fd_insert(virq, resample);
2196         } else {
2197             irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
2198             irqfd.resamplefd = rfd;
2199         }
2200     } else if (!assign) {
2201         if (kvm_irqchip_is_split()) {
2202             kvm_resample_fd_remove(virq);
2203         }
2204     }
2205 
2206     if (!kvm_irqfds_enabled()) {
2207         return -ENOSYS;
2208     }
2209 
2210     return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
2211 }
2212 
2213 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
2214 {
2215     struct kvm_irq_routing_entry kroute = {};
2216     int virq;
2217 
2218     if (!kvm_gsi_routing_enabled()) {
2219         return -ENOSYS;
2220     }
2221 
2222     virq = kvm_irqchip_get_virq(s);
2223     if (virq < 0) {
2224         return virq;
2225     }
2226 
2227     kroute.gsi = virq;
2228     kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
2229     kroute.flags = 0;
2230     kroute.u.adapter.summary_addr = adapter->summary_addr;
2231     kroute.u.adapter.ind_addr = adapter->ind_addr;
2232     kroute.u.adapter.summary_offset = adapter->summary_offset;
2233     kroute.u.adapter.ind_offset = adapter->ind_offset;
2234     kroute.u.adapter.adapter_id = adapter->adapter_id;
2235 
2236     kvm_add_routing_entry(s, &kroute);
2237 
2238     return virq;
2239 }
2240 
2241 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
2242 {
2243     struct kvm_irq_routing_entry kroute = {};
2244     int virq;
2245 
2246     if (!kvm_gsi_routing_enabled()) {
2247         return -ENOSYS;
2248     }
2249     if (!kvm_check_extension(s, KVM_CAP_HYPERV_SYNIC)) {
2250         return -ENOSYS;
2251     }
2252     virq = kvm_irqchip_get_virq(s);
2253     if (virq < 0) {
2254         return virq;
2255     }
2256 
2257     kroute.gsi = virq;
2258     kroute.type = KVM_IRQ_ROUTING_HV_SINT;
2259     kroute.flags = 0;
2260     kroute.u.hv_sint.vcpu = vcpu;
2261     kroute.u.hv_sint.sint = sint;
2262 
2263     kvm_add_routing_entry(s, &kroute);
2264     kvm_irqchip_commit_routes(s);
2265 
2266     return virq;
2267 }
2268 
2269 #else /* !KVM_CAP_IRQ_ROUTING */
2270 
2271 void kvm_init_irq_routing(KVMState *s)
2272 {
2273 }
2274 
2275 void kvm_irqchip_release_virq(KVMState *s, int virq)
2276 {
2277 }
2278 
2279 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
2280 {
2281     abort();
2282 }
2283 
2284 int kvm_irqchip_add_msi_route(KVMRouteChange *c, int vector, PCIDevice *dev)
2285 {
2286     return -ENOSYS;
2287 }
2288 
2289 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
2290 {
2291     return -ENOSYS;
2292 }
2293 
2294 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
2295 {
2296     return -ENOSYS;
2297 }
2298 
2299 static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
2300                                     EventNotifier *resample, int virq,
2301                                     bool assign)
2302 {
2303     abort();
2304 }
2305 
2306 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
2307 {
2308     return -ENOSYS;
2309 }
2310 #endif /* !KVM_CAP_IRQ_ROUTING */
2311 
2312 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
2313                                        EventNotifier *rn, int virq)
2314 {
2315     return kvm_irqchip_assign_irqfd(s, n, rn, virq, true);
2316 }
2317 
2318 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
2319                                           int virq)
2320 {
2321     return kvm_irqchip_assign_irqfd(s, n, NULL, virq, false);
2322 }
2323 
2324 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
2325                                    EventNotifier *rn, qemu_irq irq)
2326 {
2327     gpointer key, gsi;
2328     gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
2329 
2330     if (!found) {
2331         return -ENXIO;
2332     }
2333     return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
2334 }
2335 
2336 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
2337                                       qemu_irq irq)
2338 {
2339     gpointer key, gsi;
2340     gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
2341 
2342     if (!found) {
2343         return -ENXIO;
2344     }
2345     return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
2346 }
2347 
2348 void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
2349 {
2350     g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
2351 }
2352 
2353 static void kvm_irqchip_create(KVMState *s)
2354 {
2355     int ret;
2356 
2357     assert(s->kernel_irqchip_split != ON_OFF_AUTO_AUTO);
2358     if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
2359         ;
2360     } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
2361         ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
2362         if (ret < 0) {
2363             fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
2364             exit(1);
2365         }
2366     } else {
2367         return;
2368     }
2369 
2370     /* First probe and see if there's a arch-specific hook to create the
2371      * in-kernel irqchip for us */
2372     ret = kvm_arch_irqchip_create(s);
2373     if (ret == 0) {
2374         if (s->kernel_irqchip_split == ON_OFF_AUTO_ON) {
2375             error_report("Split IRQ chip mode not supported.");
2376             exit(1);
2377         } else {
2378             ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
2379         }
2380     }
2381     if (ret < 0) {
2382         fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
2383         exit(1);
2384     }
2385 
2386     kvm_kernel_irqchip = true;
2387     /* If we have an in-kernel IRQ chip then we must have asynchronous
2388      * interrupt delivery (though the reverse is not necessarily true)
2389      */
2390     kvm_async_interrupts_allowed = true;
2391     kvm_halt_in_kernel_allowed = true;
2392 
2393     kvm_init_irq_routing(s);
2394 
2395     s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
2396 }
2397 
2398 /* Find number of supported CPUs using the recommended
2399  * procedure from the kernel API documentation to cope with
2400  * older kernels that may be missing capabilities.
2401  */
2402 static int kvm_recommended_vcpus(KVMState *s)
2403 {
2404     int ret = kvm_vm_check_extension(s, KVM_CAP_NR_VCPUS);
2405     return (ret) ? ret : 4;
2406 }
2407 
2408 static int kvm_max_vcpus(KVMState *s)
2409 {
2410     int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
2411     return (ret) ? ret : kvm_recommended_vcpus(s);
2412 }
2413 
2414 static int kvm_max_vcpu_id(KVMState *s)
2415 {
2416     int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
2417     return (ret) ? ret : kvm_max_vcpus(s);
2418 }
2419 
2420 bool kvm_vcpu_id_is_valid(int vcpu_id)
2421 {
2422     KVMState *s = KVM_STATE(current_accel());
2423     return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
2424 }
2425 
2426 bool kvm_dirty_ring_enabled(void)
2427 {
2428     return kvm_state->kvm_dirty_ring_size ? true : false;
2429 }
2430 
2431 static void query_stats_cb(StatsResultList **result, StatsTarget target,
2432                            strList *names, strList *targets, Error **errp);
2433 static void query_stats_schemas_cb(StatsSchemaList **result, Error **errp);
2434 
2435 uint32_t kvm_dirty_ring_size(void)
2436 {
2437     return kvm_state->kvm_dirty_ring_size;
2438 }
2439 
2440 static int kvm_init(MachineState *ms)
2441 {
2442     MachineClass *mc = MACHINE_GET_CLASS(ms);
2443     static const char upgrade_note[] =
2444         "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
2445         "(see http://sourceforge.net/projects/kvm).\n";
2446     const struct {
2447         const char *name;
2448         int num;
2449     } num_cpus[] = {
2450         { "SMP",          ms->smp.cpus },
2451         { "hotpluggable", ms->smp.max_cpus },
2452         { /* end of list */ }
2453     }, *nc = num_cpus;
2454     int soft_vcpus_limit, hard_vcpus_limit;
2455     KVMState *s;
2456     const KVMCapabilityInfo *missing_cap;
2457     int ret;
2458     int type = 0;
2459     uint64_t dirty_log_manual_caps;
2460 
2461     qemu_mutex_init(&kml_slots_lock);
2462 
2463     s = KVM_STATE(ms->accelerator);
2464 
2465     /*
2466      * On systems where the kernel can support different base page
2467      * sizes, host page size may be different from TARGET_PAGE_SIZE,
2468      * even with KVM.  TARGET_PAGE_SIZE is assumed to be the minimum
2469      * page size for the system though.
2470      */
2471     assert(TARGET_PAGE_SIZE <= qemu_real_host_page_size());
2472 
2473     s->sigmask_len = 8;
2474     accel_blocker_init();
2475 
2476 #ifdef KVM_CAP_SET_GUEST_DEBUG
2477     QTAILQ_INIT(&s->kvm_sw_breakpoints);
2478 #endif
2479     QLIST_INIT(&s->kvm_parked_vcpus);
2480     s->fd = qemu_open_old("/dev/kvm", O_RDWR);
2481     if (s->fd == -1) {
2482         fprintf(stderr, "Could not access KVM kernel module: %m\n");
2483         ret = -errno;
2484         goto err;
2485     }
2486 
2487     ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
2488     if (ret < KVM_API_VERSION) {
2489         if (ret >= 0) {
2490             ret = -EINVAL;
2491         }
2492         fprintf(stderr, "kvm version too old\n");
2493         goto err;
2494     }
2495 
2496     if (ret > KVM_API_VERSION) {
2497         ret = -EINVAL;
2498         fprintf(stderr, "kvm version not supported\n");
2499         goto err;
2500     }
2501 
2502     kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
2503     s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
2504 
2505     /* If unspecified, use the default value */
2506     if (!s->nr_slots) {
2507         s->nr_slots = 32;
2508     }
2509 
2510     s->nr_as = kvm_check_extension(s, KVM_CAP_MULTI_ADDRESS_SPACE);
2511     if (s->nr_as <= 1) {
2512         s->nr_as = 1;
2513     }
2514     s->as = g_new0(struct KVMAs, s->nr_as);
2515 
2516     if (object_property_find(OBJECT(current_machine), "kvm-type")) {
2517         g_autofree char *kvm_type = object_property_get_str(OBJECT(current_machine),
2518                                                             "kvm-type",
2519                                                             &error_abort);
2520         type = mc->kvm_type(ms, kvm_type);
2521     } else if (mc->kvm_type) {
2522         type = mc->kvm_type(ms, NULL);
2523     }
2524 
2525     do {
2526         ret = kvm_ioctl(s, KVM_CREATE_VM, type);
2527     } while (ret == -EINTR);
2528 
2529     if (ret < 0) {
2530         fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
2531                 strerror(-ret));
2532 
2533 #ifdef TARGET_S390X
2534         if (ret == -EINVAL) {
2535             fprintf(stderr,
2536                     "Host kernel setup problem detected. Please verify:\n");
2537             fprintf(stderr, "- for kernels supporting the switch_amode or"
2538                     " user_mode parameters, whether\n");
2539             fprintf(stderr,
2540                     "  user space is running in primary address space\n");
2541             fprintf(stderr,
2542                     "- for kernels supporting the vm.allocate_pgste sysctl, "
2543                     "whether it is enabled\n");
2544         }
2545 #elif defined(TARGET_PPC)
2546         if (ret == -EINVAL) {
2547             fprintf(stderr,
2548                     "PPC KVM module is not loaded. Try modprobe kvm_%s.\n",
2549                     (type == 2) ? "pr" : "hv");
2550         }
2551 #endif
2552         goto err;
2553     }
2554 
2555     s->vmfd = ret;
2556 
2557     /* check the vcpu limits */
2558     soft_vcpus_limit = kvm_recommended_vcpus(s);
2559     hard_vcpus_limit = kvm_max_vcpus(s);
2560 
2561     while (nc->name) {
2562         if (nc->num > soft_vcpus_limit) {
2563             warn_report("Number of %s cpus requested (%d) exceeds "
2564                         "the recommended cpus supported by KVM (%d)",
2565                         nc->name, nc->num, soft_vcpus_limit);
2566 
2567             if (nc->num > hard_vcpus_limit) {
2568                 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
2569                         "the maximum cpus supported by KVM (%d)\n",
2570                         nc->name, nc->num, hard_vcpus_limit);
2571                 exit(1);
2572             }
2573         }
2574         nc++;
2575     }
2576 
2577     missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
2578     if (!missing_cap) {
2579         missing_cap =
2580             kvm_check_extension_list(s, kvm_arch_required_capabilities);
2581     }
2582     if (missing_cap) {
2583         ret = -EINVAL;
2584         fprintf(stderr, "kvm does not support %s\n%s",
2585                 missing_cap->name, upgrade_note);
2586         goto err;
2587     }
2588 
2589     s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
2590     s->coalesced_pio = s->coalesced_mmio &&
2591                        kvm_check_extension(s, KVM_CAP_COALESCED_PIO);
2592 
2593     /*
2594      * Enable KVM dirty ring if supported, otherwise fall back to
2595      * dirty logging mode
2596      */
2597     ret = kvm_dirty_ring_init(s);
2598     if (ret < 0) {
2599         goto err;
2600     }
2601 
2602     /*
2603      * KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is not needed when dirty ring is
2604      * enabled.  More importantly, KVM_DIRTY_LOG_INITIALLY_SET will assume no
2605      * page is wr-protected initially, which is against how kvm dirty ring is
2606      * usage - kvm dirty ring requires all pages are wr-protected at the very
2607      * beginning.  Enabling this feature for dirty ring causes data corruption.
2608      *
2609      * TODO: Without KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 and kvm clear dirty log,
2610      * we may expect a higher stall time when starting the migration.  In the
2611      * future we can enable KVM_CLEAR_DIRTY_LOG to work with dirty ring too:
2612      * instead of clearing dirty bit, it can be a way to explicitly wr-protect
2613      * guest pages.
2614      */
2615     if (!s->kvm_dirty_ring_size) {
2616         dirty_log_manual_caps =
2617             kvm_check_extension(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
2618         dirty_log_manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
2619                                   KVM_DIRTY_LOG_INITIALLY_SET);
2620         s->manual_dirty_log_protect = dirty_log_manual_caps;
2621         if (dirty_log_manual_caps) {
2622             ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0,
2623                                     dirty_log_manual_caps);
2624             if (ret) {
2625                 warn_report("Trying to enable capability %"PRIu64" of "
2626                             "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
2627                             "Falling back to the legacy mode. ",
2628                             dirty_log_manual_caps);
2629                 s->manual_dirty_log_protect = 0;
2630             }
2631         }
2632     }
2633 
2634 #ifdef KVM_CAP_VCPU_EVENTS
2635     s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
2636 #endif
2637 
2638     s->robust_singlestep =
2639         kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
2640 
2641 #ifdef KVM_CAP_DEBUGREGS
2642     s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
2643 #endif
2644 
2645     s->max_nested_state_len = kvm_check_extension(s, KVM_CAP_NESTED_STATE);
2646 
2647 #ifdef KVM_CAP_IRQ_ROUTING
2648     kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
2649 #endif
2650 
2651     s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
2652 
2653     s->irq_set_ioctl = KVM_IRQ_LINE;
2654     if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
2655         s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
2656     }
2657 
2658     kvm_readonly_mem_allowed =
2659         (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
2660 
2661     kvm_eventfds_allowed =
2662         (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
2663 
2664     kvm_irqfds_allowed =
2665         (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
2666 
2667     kvm_resamplefds_allowed =
2668         (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
2669 
2670     kvm_vm_attributes_allowed =
2671         (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
2672 
2673     kvm_ioeventfd_any_length_allowed =
2674         (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
2675 
2676 #ifdef KVM_CAP_SET_GUEST_DEBUG
2677     kvm_has_guest_debug =
2678         (kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG) > 0);
2679 #endif
2680 
2681     kvm_sstep_flags = 0;
2682     if (kvm_has_guest_debug) {
2683         kvm_sstep_flags = SSTEP_ENABLE;
2684 
2685 #if defined KVM_CAP_SET_GUEST_DEBUG2
2686         int guest_debug_flags =
2687             kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG2);
2688 
2689         if (guest_debug_flags & KVM_GUESTDBG_BLOCKIRQ) {
2690             kvm_sstep_flags |= SSTEP_NOIRQ;
2691         }
2692 #endif
2693     }
2694 
2695     kvm_state = s;
2696 
2697     ret = kvm_arch_init(ms, s);
2698     if (ret < 0) {
2699         goto err;
2700     }
2701 
2702     if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
2703         s->kernel_irqchip_split = mc->default_kernel_irqchip_split ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
2704     }
2705 
2706     qemu_register_reset(kvm_unpoison_all, NULL);
2707 
2708     if (s->kernel_irqchip_allowed) {
2709         kvm_irqchip_create(s);
2710     }
2711 
2712     if (kvm_eventfds_allowed) {
2713         s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
2714         s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
2715     }
2716     s->memory_listener.listener.coalesced_io_add = kvm_coalesce_mmio_region;
2717     s->memory_listener.listener.coalesced_io_del = kvm_uncoalesce_mmio_region;
2718 
2719     kvm_memory_listener_register(s, &s->memory_listener,
2720                                  &address_space_memory, 0, "kvm-memory");
2721     if (kvm_eventfds_allowed) {
2722         memory_listener_register(&kvm_io_listener,
2723                                  &address_space_io);
2724     }
2725     memory_listener_register(&kvm_coalesced_pio_listener,
2726                              &address_space_io);
2727 
2728     s->many_ioeventfds = kvm_check_many_ioeventfds();
2729 
2730     s->sync_mmu = !!kvm_vm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2731     if (!s->sync_mmu) {
2732         ret = ram_block_discard_disable(true);
2733         assert(!ret);
2734     }
2735 
2736     if (s->kvm_dirty_ring_size) {
2737         ret = kvm_dirty_ring_reaper_init(s);
2738         if (ret) {
2739             goto err;
2740         }
2741     }
2742 
2743     if (kvm_check_extension(kvm_state, KVM_CAP_BINARY_STATS_FD)) {
2744         add_stats_callbacks(STATS_PROVIDER_KVM, query_stats_cb,
2745                             query_stats_schemas_cb);
2746     }
2747 
2748     return 0;
2749 
2750 err:
2751     assert(ret < 0);
2752     if (s->vmfd >= 0) {
2753         close(s->vmfd);
2754     }
2755     if (s->fd != -1) {
2756         close(s->fd);
2757     }
2758     g_free(s->memory_listener.slots);
2759 
2760     return ret;
2761 }
2762 
2763 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
2764 {
2765     s->sigmask_len = sigmask_len;
2766 }
2767 
2768 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
2769                           int size, uint32_t count)
2770 {
2771     int i;
2772     uint8_t *ptr = data;
2773 
2774     for (i = 0; i < count; i++) {
2775         address_space_rw(&address_space_io, port, attrs,
2776                          ptr, size,
2777                          direction == KVM_EXIT_IO_OUT);
2778         ptr += size;
2779     }
2780 }
2781 
2782 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
2783 {
2784     fprintf(stderr, "KVM internal error. Suberror: %d\n",
2785             run->internal.suberror);
2786 
2787     if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
2788         int i;
2789 
2790         for (i = 0; i < run->internal.ndata; ++i) {
2791             fprintf(stderr, "extra data[%d]: 0x%016"PRIx64"\n",
2792                     i, (uint64_t)run->internal.data[i]);
2793         }
2794     }
2795     if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
2796         fprintf(stderr, "emulation failure\n");
2797         if (!kvm_arch_stop_on_emulation_error(cpu)) {
2798             cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2799             return EXCP_INTERRUPT;
2800         }
2801     }
2802     /* FIXME: Should trigger a qmp message to let management know
2803      * something went wrong.
2804      */
2805     return -1;
2806 }
2807 
2808 void kvm_flush_coalesced_mmio_buffer(void)
2809 {
2810     KVMState *s = kvm_state;
2811 
2812     if (s->coalesced_flush_in_progress) {
2813         return;
2814     }
2815 
2816     s->coalesced_flush_in_progress = true;
2817 
2818     if (s->coalesced_mmio_ring) {
2819         struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
2820         while (ring->first != ring->last) {
2821             struct kvm_coalesced_mmio *ent;
2822 
2823             ent = &ring->coalesced_mmio[ring->first];
2824 
2825             if (ent->pio == 1) {
2826                 address_space_write(&address_space_io, ent->phys_addr,
2827                                     MEMTXATTRS_UNSPECIFIED, ent->data,
2828                                     ent->len);
2829             } else {
2830                 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
2831             }
2832             smp_wmb();
2833             ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
2834         }
2835     }
2836 
2837     s->coalesced_flush_in_progress = false;
2838 }
2839 
2840 bool kvm_cpu_check_are_resettable(void)
2841 {
2842     return kvm_arch_cpu_check_are_resettable();
2843 }
2844 
2845 static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
2846 {
2847     if (!cpu->vcpu_dirty) {
2848         kvm_arch_get_registers(cpu);
2849         cpu->vcpu_dirty = true;
2850     }
2851 }
2852 
2853 void kvm_cpu_synchronize_state(CPUState *cpu)
2854 {
2855     if (!cpu->vcpu_dirty) {
2856         run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
2857     }
2858 }
2859 
2860 static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
2861 {
2862     kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
2863     cpu->vcpu_dirty = false;
2864 }
2865 
2866 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
2867 {
2868     run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
2869 }
2870 
2871 static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
2872 {
2873     kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
2874     cpu->vcpu_dirty = false;
2875 }
2876 
2877 void kvm_cpu_synchronize_post_init(CPUState *cpu)
2878 {
2879     run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
2880 }
2881 
2882 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
2883 {
2884     cpu->vcpu_dirty = true;
2885 }
2886 
2887 void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
2888 {
2889     run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
2890 }
2891 
2892 #ifdef KVM_HAVE_MCE_INJECTION
2893 static __thread void *pending_sigbus_addr;
2894 static __thread int pending_sigbus_code;
2895 static __thread bool have_sigbus_pending;
2896 #endif
2897 
2898 static void kvm_cpu_kick(CPUState *cpu)
2899 {
2900     qatomic_set(&cpu->kvm_run->immediate_exit, 1);
2901 }
2902 
2903 static void kvm_cpu_kick_self(void)
2904 {
2905     if (kvm_immediate_exit) {
2906         kvm_cpu_kick(current_cpu);
2907     } else {
2908         qemu_cpu_kick_self();
2909     }
2910 }
2911 
2912 static void kvm_eat_signals(CPUState *cpu)
2913 {
2914     struct timespec ts = { 0, 0 };
2915     siginfo_t siginfo;
2916     sigset_t waitset;
2917     sigset_t chkset;
2918     int r;
2919 
2920     if (kvm_immediate_exit) {
2921         qatomic_set(&cpu->kvm_run->immediate_exit, 0);
2922         /* Write kvm_run->immediate_exit before the cpu->exit_request
2923          * write in kvm_cpu_exec.
2924          */
2925         smp_wmb();
2926         return;
2927     }
2928 
2929     sigemptyset(&waitset);
2930     sigaddset(&waitset, SIG_IPI);
2931 
2932     do {
2933         r = sigtimedwait(&waitset, &siginfo, &ts);
2934         if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
2935             perror("sigtimedwait");
2936             exit(1);
2937         }
2938 
2939         r = sigpending(&chkset);
2940         if (r == -1) {
2941             perror("sigpending");
2942             exit(1);
2943         }
2944     } while (sigismember(&chkset, SIG_IPI));
2945 }
2946 
2947 int kvm_cpu_exec(CPUState *cpu)
2948 {
2949     struct kvm_run *run = cpu->kvm_run;
2950     int ret, run_ret;
2951 
2952     DPRINTF("kvm_cpu_exec()\n");
2953 
2954     if (kvm_arch_process_async_events(cpu)) {
2955         qatomic_set(&cpu->exit_request, 0);
2956         return EXCP_HLT;
2957     }
2958 
2959     qemu_mutex_unlock_iothread();
2960     cpu_exec_start(cpu);
2961 
2962     do {
2963         MemTxAttrs attrs;
2964 
2965         if (cpu->vcpu_dirty) {
2966             kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
2967             cpu->vcpu_dirty = false;
2968         }
2969 
2970         kvm_arch_pre_run(cpu, run);
2971         if (qatomic_read(&cpu->exit_request)) {
2972             DPRINTF("interrupt exit requested\n");
2973             /*
2974              * KVM requires us to reenter the kernel after IO exits to complete
2975              * instruction emulation. This self-signal will ensure that we
2976              * leave ASAP again.
2977              */
2978             kvm_cpu_kick_self();
2979         }
2980 
2981         /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2982          * Matching barrier in kvm_eat_signals.
2983          */
2984         smp_rmb();
2985 
2986         run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
2987 
2988         attrs = kvm_arch_post_run(cpu, run);
2989 
2990 #ifdef KVM_HAVE_MCE_INJECTION
2991         if (unlikely(have_sigbus_pending)) {
2992             qemu_mutex_lock_iothread();
2993             kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
2994                                     pending_sigbus_addr);
2995             have_sigbus_pending = false;
2996             qemu_mutex_unlock_iothread();
2997         }
2998 #endif
2999 
3000         if (run_ret < 0) {
3001             if (run_ret == -EINTR || run_ret == -EAGAIN) {
3002                 DPRINTF("io window exit\n");
3003                 kvm_eat_signals(cpu);
3004                 ret = EXCP_INTERRUPT;
3005                 break;
3006             }
3007             fprintf(stderr, "error: kvm run failed %s\n",
3008                     strerror(-run_ret));
3009 #ifdef TARGET_PPC
3010             if (run_ret == -EBUSY) {
3011                 fprintf(stderr,
3012                         "This is probably because your SMT is enabled.\n"
3013                         "VCPU can only run on primary threads with all "
3014                         "secondary threads offline.\n");
3015             }
3016 #endif
3017             ret = -1;
3018             break;
3019         }
3020 
3021         trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
3022         switch (run->exit_reason) {
3023         case KVM_EXIT_IO:
3024             DPRINTF("handle_io\n");
3025             /* Called outside BQL */
3026             kvm_handle_io(run->io.port, attrs,
3027                           (uint8_t *)run + run->io.data_offset,
3028                           run->io.direction,
3029                           run->io.size,
3030                           run->io.count);
3031             ret = 0;
3032             break;
3033         case KVM_EXIT_MMIO:
3034             DPRINTF("handle_mmio\n");
3035             /* Called outside BQL */
3036             address_space_rw(&address_space_memory,
3037                              run->mmio.phys_addr, attrs,
3038                              run->mmio.data,
3039                              run->mmio.len,
3040                              run->mmio.is_write);
3041             ret = 0;
3042             break;
3043         case KVM_EXIT_IRQ_WINDOW_OPEN:
3044             DPRINTF("irq_window_open\n");
3045             ret = EXCP_INTERRUPT;
3046             break;
3047         case KVM_EXIT_SHUTDOWN:
3048             DPRINTF("shutdown\n");
3049             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
3050             ret = EXCP_INTERRUPT;
3051             break;
3052         case KVM_EXIT_UNKNOWN:
3053             fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
3054                     (uint64_t)run->hw.hardware_exit_reason);
3055             ret = -1;
3056             break;
3057         case KVM_EXIT_INTERNAL_ERROR:
3058             ret = kvm_handle_internal_error(cpu, run);
3059             break;
3060         case KVM_EXIT_DIRTY_RING_FULL:
3061             /*
3062              * We shouldn't continue if the dirty ring of this vcpu is
3063              * still full.  Got kicked by KVM_RESET_DIRTY_RINGS.
3064              */
3065             trace_kvm_dirty_ring_full(cpu->cpu_index);
3066             qemu_mutex_lock_iothread();
3067             /*
3068              * We throttle vCPU by making it sleep once it exit from kernel
3069              * due to dirty ring full. In the dirtylimit scenario, reaping
3070              * all vCPUs after a single vCPU dirty ring get full result in
3071              * the miss of sleep, so just reap the ring-fulled vCPU.
3072              */
3073             if (dirtylimit_in_service()) {
3074                 kvm_dirty_ring_reap(kvm_state, cpu);
3075             } else {
3076                 kvm_dirty_ring_reap(kvm_state, NULL);
3077             }
3078             qemu_mutex_unlock_iothread();
3079             dirtylimit_vcpu_execute(cpu);
3080             ret = 0;
3081             break;
3082         case KVM_EXIT_SYSTEM_EVENT:
3083             switch (run->system_event.type) {
3084             case KVM_SYSTEM_EVENT_SHUTDOWN:
3085                 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
3086                 ret = EXCP_INTERRUPT;
3087                 break;
3088             case KVM_SYSTEM_EVENT_RESET:
3089                 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
3090                 ret = EXCP_INTERRUPT;
3091                 break;
3092             case KVM_SYSTEM_EVENT_CRASH:
3093                 kvm_cpu_synchronize_state(cpu);
3094                 qemu_mutex_lock_iothread();
3095                 qemu_system_guest_panicked(cpu_get_crash_info(cpu));
3096                 qemu_mutex_unlock_iothread();
3097                 ret = 0;
3098                 break;
3099             default:
3100                 DPRINTF("kvm_arch_handle_exit\n");
3101                 ret = kvm_arch_handle_exit(cpu, run);
3102                 break;
3103             }
3104             break;
3105         default:
3106             DPRINTF("kvm_arch_handle_exit\n");
3107             ret = kvm_arch_handle_exit(cpu, run);
3108             break;
3109         }
3110     } while (ret == 0);
3111 
3112     cpu_exec_end(cpu);
3113     qemu_mutex_lock_iothread();
3114 
3115     if (ret < 0) {
3116         cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
3117         vm_stop(RUN_STATE_INTERNAL_ERROR);
3118     }
3119 
3120     qatomic_set(&cpu->exit_request, 0);
3121     return ret;
3122 }
3123 
3124 int kvm_ioctl(KVMState *s, int type, ...)
3125 {
3126     int ret;
3127     void *arg;
3128     va_list ap;
3129 
3130     va_start(ap, type);
3131     arg = va_arg(ap, void *);
3132     va_end(ap);
3133 
3134     trace_kvm_ioctl(type, arg);
3135     ret = ioctl(s->fd, type, arg);
3136     if (ret == -1) {
3137         ret = -errno;
3138     }
3139     return ret;
3140 }
3141 
3142 int kvm_vm_ioctl(KVMState *s, int type, ...)
3143 {
3144     int ret;
3145     void *arg;
3146     va_list ap;
3147 
3148     va_start(ap, type);
3149     arg = va_arg(ap, void *);
3150     va_end(ap);
3151 
3152     trace_kvm_vm_ioctl(type, arg);
3153     accel_ioctl_begin();
3154     ret = ioctl(s->vmfd, type, arg);
3155     accel_ioctl_end();
3156     if (ret == -1) {
3157         ret = -errno;
3158     }
3159     return ret;
3160 }
3161 
3162 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
3163 {
3164     int ret;
3165     void *arg;
3166     va_list ap;
3167 
3168     va_start(ap, type);
3169     arg = va_arg(ap, void *);
3170     va_end(ap);
3171 
3172     trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
3173     accel_cpu_ioctl_begin(cpu);
3174     ret = ioctl(cpu->kvm_fd, type, arg);
3175     accel_cpu_ioctl_end(cpu);
3176     if (ret == -1) {
3177         ret = -errno;
3178     }
3179     return ret;
3180 }
3181 
3182 int kvm_device_ioctl(int fd, int type, ...)
3183 {
3184     int ret;
3185     void *arg;
3186     va_list ap;
3187 
3188     va_start(ap, type);
3189     arg = va_arg(ap, void *);
3190     va_end(ap);
3191 
3192     trace_kvm_device_ioctl(fd, type, arg);
3193     accel_ioctl_begin();
3194     ret = ioctl(fd, type, arg);
3195     accel_ioctl_end();
3196     if (ret == -1) {
3197         ret = -errno;
3198     }
3199     return ret;
3200 }
3201 
3202 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
3203 {
3204     int ret;
3205     struct kvm_device_attr attribute = {
3206         .group = group,
3207         .attr = attr,
3208     };
3209 
3210     if (!kvm_vm_attributes_allowed) {
3211         return 0;
3212     }
3213 
3214     ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
3215     /* kvm returns 0 on success for HAS_DEVICE_ATTR */
3216     return ret ? 0 : 1;
3217 }
3218 
3219 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
3220 {
3221     struct kvm_device_attr attribute = {
3222         .group = group,
3223         .attr = attr,
3224         .flags = 0,
3225     };
3226 
3227     return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
3228 }
3229 
3230 int kvm_device_access(int fd, int group, uint64_t attr,
3231                       void *val, bool write, Error **errp)
3232 {
3233     struct kvm_device_attr kvmattr;
3234     int err;
3235 
3236     kvmattr.flags = 0;
3237     kvmattr.group = group;
3238     kvmattr.attr = attr;
3239     kvmattr.addr = (uintptr_t)val;
3240 
3241     err = kvm_device_ioctl(fd,
3242                            write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
3243                            &kvmattr);
3244     if (err < 0) {
3245         error_setg_errno(errp, -err,
3246                          "KVM_%s_DEVICE_ATTR failed: Group %d "
3247                          "attr 0x%016" PRIx64,
3248                          write ? "SET" : "GET", group, attr);
3249     }
3250     return err;
3251 }
3252 
3253 bool kvm_has_sync_mmu(void)
3254 {
3255     return kvm_state->sync_mmu;
3256 }
3257 
3258 int kvm_has_vcpu_events(void)
3259 {
3260     return kvm_state->vcpu_events;
3261 }
3262 
3263 int kvm_has_robust_singlestep(void)
3264 {
3265     return kvm_state->robust_singlestep;
3266 }
3267 
3268 int kvm_has_debugregs(void)
3269 {
3270     return kvm_state->debugregs;
3271 }
3272 
3273 int kvm_max_nested_state_length(void)
3274 {
3275     return kvm_state->max_nested_state_len;
3276 }
3277 
3278 int kvm_has_many_ioeventfds(void)
3279 {
3280     if (!kvm_enabled()) {
3281         return 0;
3282     }
3283     return kvm_state->many_ioeventfds;
3284 }
3285 
3286 int kvm_has_gsi_routing(void)
3287 {
3288 #ifdef KVM_CAP_IRQ_ROUTING
3289     return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
3290 #else
3291     return false;
3292 #endif
3293 }
3294 
3295 int kvm_has_intx_set_mask(void)
3296 {
3297     return kvm_state->intx_set_mask;
3298 }
3299 
3300 bool kvm_arm_supports_user_irq(void)
3301 {
3302     return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
3303 }
3304 
3305 #ifdef KVM_CAP_SET_GUEST_DEBUG
3306 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
3307                                                  target_ulong pc)
3308 {
3309     struct kvm_sw_breakpoint *bp;
3310 
3311     QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
3312         if (bp->pc == pc) {
3313             return bp;
3314         }
3315     }
3316     return NULL;
3317 }
3318 
3319 int kvm_sw_breakpoints_active(CPUState *cpu)
3320 {
3321     return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
3322 }
3323 
3324 struct kvm_set_guest_debug_data {
3325     struct kvm_guest_debug dbg;
3326     int err;
3327 };
3328 
3329 static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
3330 {
3331     struct kvm_set_guest_debug_data *dbg_data =
3332         (struct kvm_set_guest_debug_data *) data.host_ptr;
3333 
3334     dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
3335                                    &dbg_data->dbg);
3336 }
3337 
3338 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
3339 {
3340     struct kvm_set_guest_debug_data data;
3341 
3342     data.dbg.control = reinject_trap;
3343 
3344     if (cpu->singlestep_enabled) {
3345         data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
3346 
3347         if (cpu->singlestep_enabled & SSTEP_NOIRQ) {
3348             data.dbg.control |= KVM_GUESTDBG_BLOCKIRQ;
3349         }
3350     }
3351     kvm_arch_update_guest_debug(cpu, &data.dbg);
3352 
3353     run_on_cpu(cpu, kvm_invoke_set_guest_debug,
3354                RUN_ON_CPU_HOST_PTR(&data));
3355     return data.err;
3356 }
3357 
3358 bool kvm_supports_guest_debug(void)
3359 {
3360     /* probed during kvm_init() */
3361     return kvm_has_guest_debug;
3362 }
3363 
3364 int kvm_insert_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
3365 {
3366     struct kvm_sw_breakpoint *bp;
3367     int err;
3368 
3369     if (type == GDB_BREAKPOINT_SW) {
3370         bp = kvm_find_sw_breakpoint(cpu, addr);
3371         if (bp) {
3372             bp->use_count++;
3373             return 0;
3374         }
3375 
3376         bp = g_new(struct kvm_sw_breakpoint, 1);
3377         bp->pc = addr;
3378         bp->use_count = 1;
3379         err = kvm_arch_insert_sw_breakpoint(cpu, bp);
3380         if (err) {
3381             g_free(bp);
3382             return err;
3383         }
3384 
3385         QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
3386     } else {
3387         err = kvm_arch_insert_hw_breakpoint(addr, len, type);
3388         if (err) {
3389             return err;
3390         }
3391     }
3392 
3393     CPU_FOREACH(cpu) {
3394         err = kvm_update_guest_debug(cpu, 0);
3395         if (err) {
3396             return err;
3397         }
3398     }
3399     return 0;
3400 }
3401 
3402 int kvm_remove_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
3403 {
3404     struct kvm_sw_breakpoint *bp;
3405     int err;
3406 
3407     if (type == GDB_BREAKPOINT_SW) {
3408         bp = kvm_find_sw_breakpoint(cpu, addr);
3409         if (!bp) {
3410             return -ENOENT;
3411         }
3412 
3413         if (bp->use_count > 1) {
3414             bp->use_count--;
3415             return 0;
3416         }
3417 
3418         err = kvm_arch_remove_sw_breakpoint(cpu, bp);
3419         if (err) {
3420             return err;
3421         }
3422 
3423         QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
3424         g_free(bp);
3425     } else {
3426         err = kvm_arch_remove_hw_breakpoint(addr, len, type);
3427         if (err) {
3428             return err;
3429         }
3430     }
3431 
3432     CPU_FOREACH(cpu) {
3433         err = kvm_update_guest_debug(cpu, 0);
3434         if (err) {
3435             return err;
3436         }
3437     }
3438     return 0;
3439 }
3440 
3441 void kvm_remove_all_breakpoints(CPUState *cpu)
3442 {
3443     struct kvm_sw_breakpoint *bp, *next;
3444     KVMState *s = cpu->kvm_state;
3445     CPUState *tmpcpu;
3446 
3447     QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
3448         if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
3449             /* Try harder to find a CPU that currently sees the breakpoint. */
3450             CPU_FOREACH(tmpcpu) {
3451                 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
3452                     break;
3453                 }
3454             }
3455         }
3456         QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
3457         g_free(bp);
3458     }
3459     kvm_arch_remove_all_hw_breakpoints();
3460 
3461     CPU_FOREACH(cpu) {
3462         kvm_update_guest_debug(cpu, 0);
3463     }
3464 }
3465 
3466 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
3467 
3468 static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
3469 {
3470     KVMState *s = kvm_state;
3471     struct kvm_signal_mask *sigmask;
3472     int r;
3473 
3474     sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
3475 
3476     sigmask->len = s->sigmask_len;
3477     memcpy(sigmask->sigset, sigset, sizeof(*sigset));
3478     r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
3479     g_free(sigmask);
3480 
3481     return r;
3482 }
3483 
3484 static void kvm_ipi_signal(int sig)
3485 {
3486     if (current_cpu) {
3487         assert(kvm_immediate_exit);
3488         kvm_cpu_kick(current_cpu);
3489     }
3490 }
3491 
3492 void kvm_init_cpu_signals(CPUState *cpu)
3493 {
3494     int r;
3495     sigset_t set;
3496     struct sigaction sigact;
3497 
3498     memset(&sigact, 0, sizeof(sigact));
3499     sigact.sa_handler = kvm_ipi_signal;
3500     sigaction(SIG_IPI, &sigact, NULL);
3501 
3502     pthread_sigmask(SIG_BLOCK, NULL, &set);
3503 #if defined KVM_HAVE_MCE_INJECTION
3504     sigdelset(&set, SIGBUS);
3505     pthread_sigmask(SIG_SETMASK, &set, NULL);
3506 #endif
3507     sigdelset(&set, SIG_IPI);
3508     if (kvm_immediate_exit) {
3509         r = pthread_sigmask(SIG_SETMASK, &set, NULL);
3510     } else {
3511         r = kvm_set_signal_mask(cpu, &set);
3512     }
3513     if (r) {
3514         fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
3515         exit(1);
3516     }
3517 }
3518 
3519 /* Called asynchronously in VCPU thread.  */
3520 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
3521 {
3522 #ifdef KVM_HAVE_MCE_INJECTION
3523     if (have_sigbus_pending) {
3524         return 1;
3525     }
3526     have_sigbus_pending = true;
3527     pending_sigbus_addr = addr;
3528     pending_sigbus_code = code;
3529     qatomic_set(&cpu->exit_request, 1);
3530     return 0;
3531 #else
3532     return 1;
3533 #endif
3534 }
3535 
3536 /* Called synchronously (via signalfd) in main thread.  */
3537 int kvm_on_sigbus(int code, void *addr)
3538 {
3539 #ifdef KVM_HAVE_MCE_INJECTION
3540     /* Action required MCE kills the process if SIGBUS is blocked.  Because
3541      * that's what happens in the I/O thread, where we handle MCE via signalfd,
3542      * we can only get action optional here.
3543      */
3544     assert(code != BUS_MCEERR_AR);
3545     kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
3546     return 0;
3547 #else
3548     return 1;
3549 #endif
3550 }
3551 
3552 int kvm_create_device(KVMState *s, uint64_t type, bool test)
3553 {
3554     int ret;
3555     struct kvm_create_device create_dev;
3556 
3557     create_dev.type = type;
3558     create_dev.fd = -1;
3559     create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
3560 
3561     if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
3562         return -ENOTSUP;
3563     }
3564 
3565     ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
3566     if (ret) {
3567         return ret;
3568     }
3569 
3570     return test ? 0 : create_dev.fd;
3571 }
3572 
3573 bool kvm_device_supported(int vmfd, uint64_t type)
3574 {
3575     struct kvm_create_device create_dev = {
3576         .type = type,
3577         .fd = -1,
3578         .flags = KVM_CREATE_DEVICE_TEST,
3579     };
3580 
3581     if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
3582         return false;
3583     }
3584 
3585     return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
3586 }
3587 
3588 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
3589 {
3590     struct kvm_one_reg reg;
3591     int r;
3592 
3593     reg.id = id;
3594     reg.addr = (uintptr_t) source;
3595     r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
3596     if (r) {
3597         trace_kvm_failed_reg_set(id, strerror(-r));
3598     }
3599     return r;
3600 }
3601 
3602 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
3603 {
3604     struct kvm_one_reg reg;
3605     int r;
3606 
3607     reg.id = id;
3608     reg.addr = (uintptr_t) target;
3609     r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
3610     if (r) {
3611         trace_kvm_failed_reg_get(id, strerror(-r));
3612     }
3613     return r;
3614 }
3615 
3616 static bool kvm_accel_has_memory(MachineState *ms, AddressSpace *as,
3617                                  hwaddr start_addr, hwaddr size)
3618 {
3619     KVMState *kvm = KVM_STATE(ms->accelerator);
3620     int i;
3621 
3622     for (i = 0; i < kvm->nr_as; ++i) {
3623         if (kvm->as[i].as == as && kvm->as[i].ml) {
3624             size = MIN(kvm_max_slot_size, size);
3625             return NULL != kvm_lookup_matching_slot(kvm->as[i].ml,
3626                                                     start_addr, size);
3627         }
3628     }
3629 
3630     return false;
3631 }
3632 
3633 static void kvm_get_kvm_shadow_mem(Object *obj, Visitor *v,
3634                                    const char *name, void *opaque,
3635                                    Error **errp)
3636 {
3637     KVMState *s = KVM_STATE(obj);
3638     int64_t value = s->kvm_shadow_mem;
3639 
3640     visit_type_int(v, name, &value, errp);
3641 }
3642 
3643 static void kvm_set_kvm_shadow_mem(Object *obj, Visitor *v,
3644                                    const char *name, void *opaque,
3645                                    Error **errp)
3646 {
3647     KVMState *s = KVM_STATE(obj);
3648     int64_t value;
3649 
3650     if (s->fd != -1) {
3651         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3652         return;
3653     }
3654 
3655     if (!visit_type_int(v, name, &value, errp)) {
3656         return;
3657     }
3658 
3659     s->kvm_shadow_mem = value;
3660 }
3661 
3662 static void kvm_set_kernel_irqchip(Object *obj, Visitor *v,
3663                                    const char *name, void *opaque,
3664                                    Error **errp)
3665 {
3666     KVMState *s = KVM_STATE(obj);
3667     OnOffSplit mode;
3668 
3669     if (s->fd != -1) {
3670         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3671         return;
3672     }
3673 
3674     if (!visit_type_OnOffSplit(v, name, &mode, errp)) {
3675         return;
3676     }
3677     switch (mode) {
3678     case ON_OFF_SPLIT_ON:
3679         s->kernel_irqchip_allowed = true;
3680         s->kernel_irqchip_required = true;
3681         s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3682         break;
3683     case ON_OFF_SPLIT_OFF:
3684         s->kernel_irqchip_allowed = false;
3685         s->kernel_irqchip_required = false;
3686         s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3687         break;
3688     case ON_OFF_SPLIT_SPLIT:
3689         s->kernel_irqchip_allowed = true;
3690         s->kernel_irqchip_required = true;
3691         s->kernel_irqchip_split = ON_OFF_AUTO_ON;
3692         break;
3693     default:
3694         /* The value was checked in visit_type_OnOffSplit() above. If
3695          * we get here, then something is wrong in QEMU.
3696          */
3697         abort();
3698     }
3699 }
3700 
3701 bool kvm_kernel_irqchip_allowed(void)
3702 {
3703     return kvm_state->kernel_irqchip_allowed;
3704 }
3705 
3706 bool kvm_kernel_irqchip_required(void)
3707 {
3708     return kvm_state->kernel_irqchip_required;
3709 }
3710 
3711 bool kvm_kernel_irqchip_split(void)
3712 {
3713     return kvm_state->kernel_irqchip_split == ON_OFF_AUTO_ON;
3714 }
3715 
3716 static void kvm_get_dirty_ring_size(Object *obj, Visitor *v,
3717                                     const char *name, void *opaque,
3718                                     Error **errp)
3719 {
3720     KVMState *s = KVM_STATE(obj);
3721     uint32_t value = s->kvm_dirty_ring_size;
3722 
3723     visit_type_uint32(v, name, &value, errp);
3724 }
3725 
3726 static void kvm_set_dirty_ring_size(Object *obj, Visitor *v,
3727                                     const char *name, void *opaque,
3728                                     Error **errp)
3729 {
3730     KVMState *s = KVM_STATE(obj);
3731     uint32_t value;
3732 
3733     if (s->fd != -1) {
3734         error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3735         return;
3736     }
3737 
3738     if (!visit_type_uint32(v, name, &value, errp)) {
3739         return;
3740     }
3741     if (value & (value - 1)) {
3742         error_setg(errp, "dirty-ring-size must be a power of two.");
3743         return;
3744     }
3745 
3746     s->kvm_dirty_ring_size = value;
3747 }
3748 
3749 static void kvm_accel_instance_init(Object *obj)
3750 {
3751     KVMState *s = KVM_STATE(obj);
3752 
3753     s->fd = -1;
3754     s->vmfd = -1;
3755     s->kvm_shadow_mem = -1;
3756     s->kernel_irqchip_allowed = true;
3757     s->kernel_irqchip_split = ON_OFF_AUTO_AUTO;
3758     /* KVM dirty ring is by default off */
3759     s->kvm_dirty_ring_size = 0;
3760     s->kvm_dirty_ring_with_bitmap = false;
3761     s->notify_vmexit = NOTIFY_VMEXIT_OPTION_RUN;
3762     s->notify_window = 0;
3763     s->xen_version = 0;
3764     s->xen_gnttab_max_frames = 64;
3765     s->xen_evtchn_max_pirq = 256;
3766 }
3767 
3768 /**
3769  * kvm_gdbstub_sstep_flags():
3770  *
3771  * Returns: SSTEP_* flags that KVM supports for guest debug. The
3772  * support is probed during kvm_init()
3773  */
3774 static int kvm_gdbstub_sstep_flags(void)
3775 {
3776     return kvm_sstep_flags;
3777 }
3778 
3779 static void kvm_accel_class_init(ObjectClass *oc, void *data)
3780 {
3781     AccelClass *ac = ACCEL_CLASS(oc);
3782     ac->name = "KVM";
3783     ac->init_machine = kvm_init;
3784     ac->has_memory = kvm_accel_has_memory;
3785     ac->allowed = &kvm_allowed;
3786     ac->gdbstub_supported_sstep_flags = kvm_gdbstub_sstep_flags;
3787 
3788     object_class_property_add(oc, "kernel-irqchip", "on|off|split",
3789         NULL, kvm_set_kernel_irqchip,
3790         NULL, NULL);
3791     object_class_property_set_description(oc, "kernel-irqchip",
3792         "Configure KVM in-kernel irqchip");
3793 
3794     object_class_property_add(oc, "kvm-shadow-mem", "int",
3795         kvm_get_kvm_shadow_mem, kvm_set_kvm_shadow_mem,
3796         NULL, NULL);
3797     object_class_property_set_description(oc, "kvm-shadow-mem",
3798         "KVM shadow MMU size");
3799 
3800     object_class_property_add(oc, "dirty-ring-size", "uint32",
3801         kvm_get_dirty_ring_size, kvm_set_dirty_ring_size,
3802         NULL, NULL);
3803     object_class_property_set_description(oc, "dirty-ring-size",
3804         "Size of KVM dirty page ring buffer (default: 0, i.e. use bitmap)");
3805 
3806     kvm_arch_accel_class_init(oc);
3807 }
3808 
3809 static const TypeInfo kvm_accel_type = {
3810     .name = TYPE_KVM_ACCEL,
3811     .parent = TYPE_ACCEL,
3812     .instance_init = kvm_accel_instance_init,
3813     .class_init = kvm_accel_class_init,
3814     .instance_size = sizeof(KVMState),
3815 };
3816 
3817 static void kvm_type_init(void)
3818 {
3819     type_register_static(&kvm_accel_type);
3820 }
3821 
3822 type_init(kvm_type_init);
3823 
3824 typedef struct StatsArgs {
3825     union StatsResultsType {
3826         StatsResultList **stats;
3827         StatsSchemaList **schema;
3828     } result;
3829     strList *names;
3830     Error **errp;
3831 } StatsArgs;
3832 
3833 static StatsList *add_kvmstat_entry(struct kvm_stats_desc *pdesc,
3834                                     uint64_t *stats_data,
3835                                     StatsList *stats_list,
3836                                     Error **errp)
3837 {
3838 
3839     Stats *stats;
3840     uint64List *val_list = NULL;
3841 
3842     /* Only add stats that we understand.  */
3843     switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
3844     case KVM_STATS_TYPE_CUMULATIVE:
3845     case KVM_STATS_TYPE_INSTANT:
3846     case KVM_STATS_TYPE_PEAK:
3847     case KVM_STATS_TYPE_LINEAR_HIST:
3848     case KVM_STATS_TYPE_LOG_HIST:
3849         break;
3850     default:
3851         return stats_list;
3852     }
3853 
3854     switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
3855     case KVM_STATS_UNIT_NONE:
3856     case KVM_STATS_UNIT_BYTES:
3857     case KVM_STATS_UNIT_CYCLES:
3858     case KVM_STATS_UNIT_SECONDS:
3859     case KVM_STATS_UNIT_BOOLEAN:
3860         break;
3861     default:
3862         return stats_list;
3863     }
3864 
3865     switch (pdesc->flags & KVM_STATS_BASE_MASK) {
3866     case KVM_STATS_BASE_POW10:
3867     case KVM_STATS_BASE_POW2:
3868         break;
3869     default:
3870         return stats_list;
3871     }
3872 
3873     /* Alloc and populate data list */
3874     stats = g_new0(Stats, 1);
3875     stats->name = g_strdup(pdesc->name);
3876     stats->value = g_new0(StatsValue, 1);;
3877 
3878     if ((pdesc->flags & KVM_STATS_UNIT_MASK) == KVM_STATS_UNIT_BOOLEAN) {
3879         stats->value->u.boolean = *stats_data;
3880         stats->value->type = QTYPE_QBOOL;
3881     } else if (pdesc->size == 1) {
3882         stats->value->u.scalar = *stats_data;
3883         stats->value->type = QTYPE_QNUM;
3884     } else {
3885         int i;
3886         for (i = 0; i < pdesc->size; i++) {
3887             QAPI_LIST_PREPEND(val_list, stats_data[i]);
3888         }
3889         stats->value->u.list = val_list;
3890         stats->value->type = QTYPE_QLIST;
3891     }
3892 
3893     QAPI_LIST_PREPEND(stats_list, stats);
3894     return stats_list;
3895 }
3896 
3897 static StatsSchemaValueList *add_kvmschema_entry(struct kvm_stats_desc *pdesc,
3898                                                  StatsSchemaValueList *list,
3899                                                  Error **errp)
3900 {
3901     StatsSchemaValueList *schema_entry = g_new0(StatsSchemaValueList, 1);
3902     schema_entry->value = g_new0(StatsSchemaValue, 1);
3903 
3904     switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
3905     case KVM_STATS_TYPE_CUMULATIVE:
3906         schema_entry->value->type = STATS_TYPE_CUMULATIVE;
3907         break;
3908     case KVM_STATS_TYPE_INSTANT:
3909         schema_entry->value->type = STATS_TYPE_INSTANT;
3910         break;
3911     case KVM_STATS_TYPE_PEAK:
3912         schema_entry->value->type = STATS_TYPE_PEAK;
3913         break;
3914     case KVM_STATS_TYPE_LINEAR_HIST:
3915         schema_entry->value->type = STATS_TYPE_LINEAR_HISTOGRAM;
3916         schema_entry->value->bucket_size = pdesc->bucket_size;
3917         schema_entry->value->has_bucket_size = true;
3918         break;
3919     case KVM_STATS_TYPE_LOG_HIST:
3920         schema_entry->value->type = STATS_TYPE_LOG2_HISTOGRAM;
3921         break;
3922     default:
3923         goto exit;
3924     }
3925 
3926     switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
3927     case KVM_STATS_UNIT_NONE:
3928         break;
3929     case KVM_STATS_UNIT_BOOLEAN:
3930         schema_entry->value->has_unit = true;
3931         schema_entry->value->unit = STATS_UNIT_BOOLEAN;
3932         break;
3933     case KVM_STATS_UNIT_BYTES:
3934         schema_entry->value->has_unit = true;
3935         schema_entry->value->unit = STATS_UNIT_BYTES;
3936         break;
3937     case KVM_STATS_UNIT_CYCLES:
3938         schema_entry->value->has_unit = true;
3939         schema_entry->value->unit = STATS_UNIT_CYCLES;
3940         break;
3941     case KVM_STATS_UNIT_SECONDS:
3942         schema_entry->value->has_unit = true;
3943         schema_entry->value->unit = STATS_UNIT_SECONDS;
3944         break;
3945     default:
3946         goto exit;
3947     }
3948 
3949     schema_entry->value->exponent = pdesc->exponent;
3950     if (pdesc->exponent) {
3951         switch (pdesc->flags & KVM_STATS_BASE_MASK) {
3952         case KVM_STATS_BASE_POW10:
3953             schema_entry->value->has_base = true;
3954             schema_entry->value->base = 10;
3955             break;
3956         case KVM_STATS_BASE_POW2:
3957             schema_entry->value->has_base = true;
3958             schema_entry->value->base = 2;
3959             break;
3960         default:
3961             goto exit;
3962         }
3963     }
3964 
3965     schema_entry->value->name = g_strdup(pdesc->name);
3966     schema_entry->next = list;
3967     return schema_entry;
3968 exit:
3969     g_free(schema_entry->value);
3970     g_free(schema_entry);
3971     return list;
3972 }
3973 
3974 /* Cached stats descriptors */
3975 typedef struct StatsDescriptors {
3976     const char *ident; /* cache key, currently the StatsTarget */
3977     struct kvm_stats_desc *kvm_stats_desc;
3978     struct kvm_stats_header kvm_stats_header;
3979     QTAILQ_ENTRY(StatsDescriptors) next;
3980 } StatsDescriptors;
3981 
3982 static QTAILQ_HEAD(, StatsDescriptors) stats_descriptors =
3983     QTAILQ_HEAD_INITIALIZER(stats_descriptors);
3984 
3985 /*
3986  * Return the descriptors for 'target', that either have already been read
3987  * or are retrieved from 'stats_fd'.
3988  */
3989 static StatsDescriptors *find_stats_descriptors(StatsTarget target, int stats_fd,
3990                                                 Error **errp)
3991 {
3992     StatsDescriptors *descriptors;
3993     const char *ident;
3994     struct kvm_stats_desc *kvm_stats_desc;
3995     struct kvm_stats_header *kvm_stats_header;
3996     size_t size_desc;
3997     ssize_t ret;
3998 
3999     ident = StatsTarget_str(target);
4000     QTAILQ_FOREACH(descriptors, &stats_descriptors, next) {
4001         if (g_str_equal(descriptors->ident, ident)) {
4002             return descriptors;
4003         }
4004     }
4005 
4006     descriptors = g_new0(StatsDescriptors, 1);
4007 
4008     /* Read stats header */
4009     kvm_stats_header = &descriptors->kvm_stats_header;
4010     ret = read(stats_fd, kvm_stats_header, sizeof(*kvm_stats_header));
4011     if (ret != sizeof(*kvm_stats_header)) {
4012         error_setg(errp, "KVM stats: failed to read stats header: "
4013                    "expected %zu actual %zu",
4014                    sizeof(*kvm_stats_header), ret);
4015         g_free(descriptors);
4016         return NULL;
4017     }
4018     size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4019 
4020     /* Read stats descriptors */
4021     kvm_stats_desc = g_malloc0_n(kvm_stats_header->num_desc, size_desc);
4022     ret = pread(stats_fd, kvm_stats_desc,
4023                 size_desc * kvm_stats_header->num_desc,
4024                 kvm_stats_header->desc_offset);
4025 
4026     if (ret != size_desc * kvm_stats_header->num_desc) {
4027         error_setg(errp, "KVM stats: failed to read stats descriptors: "
4028                    "expected %zu actual %zu",
4029                    size_desc * kvm_stats_header->num_desc, ret);
4030         g_free(descriptors);
4031         g_free(kvm_stats_desc);
4032         return NULL;
4033     }
4034     descriptors->kvm_stats_desc = kvm_stats_desc;
4035     descriptors->ident = ident;
4036     QTAILQ_INSERT_TAIL(&stats_descriptors, descriptors, next);
4037     return descriptors;
4038 }
4039 
4040 static void query_stats(StatsResultList **result, StatsTarget target,
4041                         strList *names, int stats_fd, Error **errp)
4042 {
4043     struct kvm_stats_desc *kvm_stats_desc;
4044     struct kvm_stats_header *kvm_stats_header;
4045     StatsDescriptors *descriptors;
4046     g_autofree uint64_t *stats_data = NULL;
4047     struct kvm_stats_desc *pdesc;
4048     StatsList *stats_list = NULL;
4049     size_t size_desc, size_data = 0;
4050     ssize_t ret;
4051     int i;
4052 
4053     descriptors = find_stats_descriptors(target, stats_fd, errp);
4054     if (!descriptors) {
4055         return;
4056     }
4057 
4058     kvm_stats_header = &descriptors->kvm_stats_header;
4059     kvm_stats_desc = descriptors->kvm_stats_desc;
4060     size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4061 
4062     /* Tally the total data size; read schema data */
4063     for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4064         pdesc = (void *)kvm_stats_desc + i * size_desc;
4065         size_data += pdesc->size * sizeof(*stats_data);
4066     }
4067 
4068     stats_data = g_malloc0(size_data);
4069     ret = pread(stats_fd, stats_data, size_data, kvm_stats_header->data_offset);
4070 
4071     if (ret != size_data) {
4072         error_setg(errp, "KVM stats: failed to read data: "
4073                    "expected %zu actual %zu", size_data, ret);
4074         return;
4075     }
4076 
4077     for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4078         uint64_t *stats;
4079         pdesc = (void *)kvm_stats_desc + i * size_desc;
4080 
4081         /* Add entry to the list */
4082         stats = (void *)stats_data + pdesc->offset;
4083         if (!apply_str_list_filter(pdesc->name, names)) {
4084             continue;
4085         }
4086         stats_list = add_kvmstat_entry(pdesc, stats, stats_list, errp);
4087     }
4088 
4089     if (!stats_list) {
4090         return;
4091     }
4092 
4093     switch (target) {
4094     case STATS_TARGET_VM:
4095         add_stats_entry(result, STATS_PROVIDER_KVM, NULL, stats_list);
4096         break;
4097     case STATS_TARGET_VCPU:
4098         add_stats_entry(result, STATS_PROVIDER_KVM,
4099                         current_cpu->parent_obj.canonical_path,
4100                         stats_list);
4101         break;
4102     default:
4103         g_assert_not_reached();
4104     }
4105 }
4106 
4107 static void query_stats_schema(StatsSchemaList **result, StatsTarget target,
4108                                int stats_fd, Error **errp)
4109 {
4110     struct kvm_stats_desc *kvm_stats_desc;
4111     struct kvm_stats_header *kvm_stats_header;
4112     StatsDescriptors *descriptors;
4113     struct kvm_stats_desc *pdesc;
4114     StatsSchemaValueList *stats_list = NULL;
4115     size_t size_desc;
4116     int i;
4117 
4118     descriptors = find_stats_descriptors(target, stats_fd, errp);
4119     if (!descriptors) {
4120         return;
4121     }
4122 
4123     kvm_stats_header = &descriptors->kvm_stats_header;
4124     kvm_stats_desc = descriptors->kvm_stats_desc;
4125     size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4126 
4127     /* Tally the total data size; read schema data */
4128     for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4129         pdesc = (void *)kvm_stats_desc + i * size_desc;
4130         stats_list = add_kvmschema_entry(pdesc, stats_list, errp);
4131     }
4132 
4133     add_stats_schema(result, STATS_PROVIDER_KVM, target, stats_list);
4134 }
4135 
4136 static void query_stats_vcpu(CPUState *cpu, run_on_cpu_data data)
4137 {
4138     StatsArgs *kvm_stats_args = (StatsArgs *) data.host_ptr;
4139     int stats_fd = kvm_vcpu_ioctl(cpu, KVM_GET_STATS_FD, NULL);
4140     Error *local_err = NULL;
4141 
4142     if (stats_fd == -1) {
4143         error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
4144         error_propagate(kvm_stats_args->errp, local_err);
4145         return;
4146     }
4147     query_stats(kvm_stats_args->result.stats, STATS_TARGET_VCPU,
4148                 kvm_stats_args->names, stats_fd, kvm_stats_args->errp);
4149     close(stats_fd);
4150 }
4151 
4152 static void query_stats_schema_vcpu(CPUState *cpu, run_on_cpu_data data)
4153 {
4154     StatsArgs *kvm_stats_args = (StatsArgs *) data.host_ptr;
4155     int stats_fd = kvm_vcpu_ioctl(cpu, KVM_GET_STATS_FD, NULL);
4156     Error *local_err = NULL;
4157 
4158     if (stats_fd == -1) {
4159         error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
4160         error_propagate(kvm_stats_args->errp, local_err);
4161         return;
4162     }
4163     query_stats_schema(kvm_stats_args->result.schema, STATS_TARGET_VCPU, stats_fd,
4164                        kvm_stats_args->errp);
4165     close(stats_fd);
4166 }
4167 
4168 static void query_stats_cb(StatsResultList **result, StatsTarget target,
4169                            strList *names, strList *targets, Error **errp)
4170 {
4171     KVMState *s = kvm_state;
4172     CPUState *cpu;
4173     int stats_fd;
4174 
4175     switch (target) {
4176     case STATS_TARGET_VM:
4177     {
4178         stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
4179         if (stats_fd == -1) {
4180             error_setg_errno(errp, errno, "KVM stats: ioctl failed");
4181             return;
4182         }
4183         query_stats(result, target, names, stats_fd, errp);
4184         close(stats_fd);
4185         break;
4186     }
4187     case STATS_TARGET_VCPU:
4188     {
4189         StatsArgs stats_args;
4190         stats_args.result.stats = result;
4191         stats_args.names = names;
4192         stats_args.errp = errp;
4193         CPU_FOREACH(cpu) {
4194             if (!apply_str_list_filter(cpu->parent_obj.canonical_path, targets)) {
4195                 continue;
4196             }
4197             run_on_cpu(cpu, query_stats_vcpu, RUN_ON_CPU_HOST_PTR(&stats_args));
4198         }
4199         break;
4200     }
4201     default:
4202         break;
4203     }
4204 }
4205 
4206 void query_stats_schemas_cb(StatsSchemaList **result, Error **errp)
4207 {
4208     StatsArgs stats_args;
4209     KVMState *s = kvm_state;
4210     int stats_fd;
4211 
4212     stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
4213     if (stats_fd == -1) {
4214         error_setg_errno(errp, errno, "KVM stats: ioctl failed");
4215         return;
4216     }
4217     query_stats_schema(result, STATS_TARGET_VM, stats_fd, errp);
4218     close(stats_fd);
4219 
4220     if (first_cpu) {
4221         stats_args.result.schema = result;
4222         stats_args.errp = errp;
4223         run_on_cpu(first_cpu, query_stats_schema_vcpu, RUN_ON_CPU_HOST_PTR(&stats_args));
4224     }
4225 }
4226