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