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