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