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