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