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