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