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