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