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