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