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