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