xref: /openbmc/qemu/accel/kvm/kvm-all.c (revision 343562e8)
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 
42 #include "hw/boards.h"
43 
44 /* This check must be after config-host.h is included */
45 #ifdef CONFIG_EVENTFD
46 #include <sys/eventfd.h>
47 #endif
48 
49 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
50  * need to use the real host PAGE_SIZE, as that's what KVM will use.
51  */
52 #define PAGE_SIZE getpagesize()
53 
54 //#define DEBUG_KVM
55 
56 #ifdef DEBUG_KVM
57 #define DPRINTF(fmt, ...) \
58     do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
59 #else
60 #define DPRINTF(fmt, ...) \
61     do { } while (0)
62 #endif
63 
64 #define KVM_MSI_HASHTAB_SIZE    256
65 
66 struct KVMParkedVcpu {
67     unsigned long vcpu_id;
68     int kvm_fd;
69     QLIST_ENTRY(KVMParkedVcpu) node;
70 };
71 
72 struct KVMState
73 {
74     AccelState parent_obj;
75 
76     int nr_slots;
77     int fd;
78     int vmfd;
79     int coalesced_mmio;
80     struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
81     bool coalesced_flush_in_progress;
82     int vcpu_events;
83     int robust_singlestep;
84     int debugregs;
85 #ifdef KVM_CAP_SET_GUEST_DEBUG
86     struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
87 #endif
88     int many_ioeventfds;
89     int intx_set_mask;
90     /* The man page (and posix) say ioctl numbers are signed int, but
91      * they're not.  Linux, glibc and *BSD all treat ioctl numbers as
92      * unsigned, and treating them as signed here can break things */
93     unsigned irq_set_ioctl;
94     unsigned int sigmask_len;
95     GHashTable *gsimap;
96 #ifdef KVM_CAP_IRQ_ROUTING
97     struct kvm_irq_routing *irq_routes;
98     int nr_allocated_irq_routes;
99     unsigned long *used_gsi_bitmap;
100     unsigned int gsi_count;
101     QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
102 #endif
103     KVMMemoryListener memory_listener;
104     QLIST_HEAD(, KVMParkedVcpu) kvm_parked_vcpus;
105 };
106 
107 KVMState *kvm_state;
108 bool kvm_kernel_irqchip;
109 bool kvm_split_irqchip;
110 bool kvm_async_interrupts_allowed;
111 bool kvm_halt_in_kernel_allowed;
112 bool kvm_eventfds_allowed;
113 bool kvm_irqfds_allowed;
114 bool kvm_resamplefds_allowed;
115 bool kvm_msi_via_irqfd_allowed;
116 bool kvm_gsi_routing_allowed;
117 bool kvm_gsi_direct_mapping;
118 bool kvm_allowed;
119 bool kvm_readonly_mem_allowed;
120 bool kvm_vm_attributes_allowed;
121 bool kvm_direct_msi_allowed;
122 bool kvm_ioeventfd_any_length_allowed;
123 bool kvm_msi_use_devid;
124 static bool kvm_immediate_exit;
125 
126 static const KVMCapabilityInfo kvm_required_capabilites[] = {
127     KVM_CAP_INFO(USER_MEMORY),
128     KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
129     KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS),
130     KVM_CAP_LAST_INFO
131 };
132 
133 int kvm_get_max_memslots(void)
134 {
135     KVMState *s = KVM_STATE(current_machine->accelerator);
136 
137     return s->nr_slots;
138 }
139 
140 static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
141 {
142     KVMState *s = kvm_state;
143     int i;
144 
145     for (i = 0; i < s->nr_slots; i++) {
146         if (kml->slots[i].memory_size == 0) {
147             return &kml->slots[i];
148         }
149     }
150 
151     return NULL;
152 }
153 
154 bool kvm_has_free_slot(MachineState *ms)
155 {
156     KVMState *s = KVM_STATE(ms->accelerator);
157 
158     return kvm_get_free_slot(&s->memory_listener);
159 }
160 
161 static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
162 {
163     KVMSlot *slot = kvm_get_free_slot(kml);
164 
165     if (slot) {
166         return slot;
167     }
168 
169     fprintf(stderr, "%s: no free slot available\n", __func__);
170     abort();
171 }
172 
173 static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
174                                          hwaddr start_addr,
175                                          hwaddr size)
176 {
177     KVMState *s = kvm_state;
178     int i;
179 
180     for (i = 0; i < s->nr_slots; i++) {
181         KVMSlot *mem = &kml->slots[i];
182 
183         if (start_addr == mem->start_addr && size == mem->memory_size) {
184             return mem;
185         }
186     }
187 
188     return NULL;
189 }
190 
191 /*
192  * Calculate and align the start address and the size of the section.
193  * Return the size. If the size is 0, the aligned section is empty.
194  */
195 static hwaddr kvm_align_section(MemoryRegionSection *section,
196                                 hwaddr *start)
197 {
198     hwaddr size = int128_get64(section->size);
199     hwaddr delta;
200 
201     *start = section->offset_within_address_space;
202 
203     /* kvm works in page size chunks, but the function may be called
204        with sub-page size and unaligned start address. Pad the start
205        address to next and truncate size to previous page boundary. */
206     delta = qemu_real_host_page_size - (*start & ~qemu_real_host_page_mask);
207     delta &= ~qemu_real_host_page_mask;
208     *start += delta;
209     if (delta > size) {
210         return 0;
211     }
212     size -= delta;
213     size &= qemu_real_host_page_mask;
214     if (*start & ~qemu_real_host_page_mask) {
215         return 0;
216     }
217 
218     return size;
219 }
220 
221 /*
222  * Find overlapping slot with lowest start address
223  */
224 static KVMSlot *kvm_lookup_overlapping_slot(KVMMemoryListener *kml,
225                                             hwaddr start_addr,
226                                             hwaddr end_addr)
227 {
228     KVMState *s = kvm_state;
229     KVMSlot *found = NULL;
230     int i;
231 
232     for (i = 0; i < s->nr_slots; i++) {
233         KVMSlot *mem = &kml->slots[i];
234 
235         if (mem->memory_size == 0 ||
236             (found && found->start_addr < mem->start_addr)) {
237             continue;
238         }
239 
240         if (end_addr > mem->start_addr &&
241             start_addr < mem->start_addr + mem->memory_size) {
242             found = mem;
243         }
244     }
245 
246     return found;
247 }
248 
249 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
250                                        hwaddr *phys_addr)
251 {
252     KVMMemoryListener *kml = &s->memory_listener;
253     int i;
254 
255     for (i = 0; i < s->nr_slots; i++) {
256         KVMSlot *mem = &kml->slots[i];
257 
258         if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
259             *phys_addr = mem->start_addr + (ram - mem->ram);
260             return 1;
261         }
262     }
263 
264     return 0;
265 }
266 
267 static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot)
268 {
269     KVMState *s = kvm_state;
270     struct kvm_userspace_memory_region mem;
271 
272     mem.slot = slot->slot | (kml->as_id << 16);
273     mem.guest_phys_addr = slot->start_addr;
274     mem.userspace_addr = (unsigned long)slot->ram;
275     mem.flags = slot->flags;
276 
277     if (slot->memory_size && mem.flags & KVM_MEM_READONLY) {
278         /* Set the slot size to 0 before setting the slot to the desired
279          * value. This is needed based on KVM commit 75d61fbc. */
280         mem.memory_size = 0;
281         kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
282     }
283     mem.memory_size = slot->memory_size;
284     return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
285 }
286 
287 int kvm_destroy_vcpu(CPUState *cpu)
288 {
289     KVMState *s = kvm_state;
290     long mmap_size;
291     struct KVMParkedVcpu *vcpu = NULL;
292     int ret = 0;
293 
294     DPRINTF("kvm_destroy_vcpu\n");
295 
296     mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
297     if (mmap_size < 0) {
298         ret = mmap_size;
299         DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
300         goto err;
301     }
302 
303     ret = munmap(cpu->kvm_run, mmap_size);
304     if (ret < 0) {
305         goto err;
306     }
307 
308     vcpu = g_malloc0(sizeof(*vcpu));
309     vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
310     vcpu->kvm_fd = cpu->kvm_fd;
311     QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
312 err:
313     return ret;
314 }
315 
316 static int kvm_get_vcpu(KVMState *s, unsigned long vcpu_id)
317 {
318     struct KVMParkedVcpu *cpu;
319 
320     QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
321         if (cpu->vcpu_id == vcpu_id) {
322             int kvm_fd;
323 
324             QLIST_REMOVE(cpu, node);
325             kvm_fd = cpu->kvm_fd;
326             g_free(cpu);
327             return kvm_fd;
328         }
329     }
330 
331     return kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)vcpu_id);
332 }
333 
334 int kvm_init_vcpu(CPUState *cpu)
335 {
336     KVMState *s = kvm_state;
337     long mmap_size;
338     int ret;
339 
340     DPRINTF("kvm_init_vcpu\n");
341 
342     ret = kvm_get_vcpu(s, kvm_arch_vcpu_id(cpu));
343     if (ret < 0) {
344         DPRINTF("kvm_create_vcpu failed\n");
345         goto err;
346     }
347 
348     cpu->kvm_fd = ret;
349     cpu->kvm_state = s;
350     cpu->vcpu_dirty = true;
351 
352     mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
353     if (mmap_size < 0) {
354         ret = mmap_size;
355         DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
356         goto err;
357     }
358 
359     cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
360                         cpu->kvm_fd, 0);
361     if (cpu->kvm_run == MAP_FAILED) {
362         ret = -errno;
363         DPRINTF("mmap'ing vcpu state failed\n");
364         goto err;
365     }
366 
367     if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
368         s->coalesced_mmio_ring =
369             (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
370     }
371 
372     ret = kvm_arch_init_vcpu(cpu);
373 err:
374     return ret;
375 }
376 
377 /*
378  * dirty pages logging control
379  */
380 
381 static int kvm_mem_flags(MemoryRegion *mr)
382 {
383     bool readonly = mr->readonly || memory_region_is_romd(mr);
384     int flags = 0;
385 
386     if (memory_region_get_dirty_log_mask(mr) != 0) {
387         flags |= KVM_MEM_LOG_DIRTY_PAGES;
388     }
389     if (readonly && kvm_readonly_mem_allowed) {
390         flags |= KVM_MEM_READONLY;
391     }
392     return flags;
393 }
394 
395 static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
396                                  MemoryRegion *mr)
397 {
398     int old_flags;
399 
400     old_flags = mem->flags;
401     mem->flags = kvm_mem_flags(mr);
402 
403     /* If nothing changed effectively, no need to issue ioctl */
404     if (mem->flags == old_flags) {
405         return 0;
406     }
407 
408     return kvm_set_user_memory_region(kml, mem);
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         fprintf(stderr, "%s: error finding slot\n", __func__);
425         abort();
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     unsigned long size, allocated_size = 0;
493     struct kvm_dirty_log d = {};
494     KVMSlot *mem;
495     int ret = 0;
496     hwaddr start_addr = section->offset_within_address_space;
497     hwaddr end_addr = start_addr + int128_get64(section->size);
498 
499     d.dirty_bitmap = NULL;
500     while (start_addr < end_addr) {
501         mem = kvm_lookup_overlapping_slot(kml, start_addr, end_addr);
502         if (mem == NULL) {
503             break;
504         }
505 
506         /* XXX bad kernel interface alert
507          * For dirty bitmap, kernel allocates array of size aligned to
508          * bits-per-long.  But for case when the kernel is 64bits and
509          * the userspace is 32bits, userspace can't align to the same
510          * bits-per-long, since sizeof(long) is different between kernel
511          * and user space.  This way, userspace will provide buffer which
512          * may be 4 bytes less than the kernel will use, resulting in
513          * userspace memory corruption (which is not detectable by valgrind
514          * too, in most cases).
515          * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
516          * a hope that sizeof(long) won't become >8 any time soon.
517          */
518         size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
519                      /*HOST_LONG_BITS*/ 64) / 8;
520         if (!d.dirty_bitmap) {
521             d.dirty_bitmap = g_malloc(size);
522         } else if (size > allocated_size) {
523             d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
524         }
525         allocated_size = size;
526         memset(d.dirty_bitmap, 0, allocated_size);
527 
528         d.slot = mem->slot | (kml->as_id << 16);
529         if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
530             DPRINTF("ioctl failed %d\n", errno);
531             ret = -1;
532             break;
533         }
534 
535         kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
536         start_addr = mem->start_addr + mem->memory_size;
537     }
538     g_free(d.dirty_bitmap);
539 
540     return ret;
541 }
542 
543 static void kvm_coalesce_mmio_region(MemoryListener *listener,
544                                      MemoryRegionSection *secion,
545                                      hwaddr start, hwaddr size)
546 {
547     KVMState *s = kvm_state;
548 
549     if (s->coalesced_mmio) {
550         struct kvm_coalesced_mmio_zone zone;
551 
552         zone.addr = start;
553         zone.size = size;
554         zone.pad = 0;
555 
556         (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
557     }
558 }
559 
560 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
561                                        MemoryRegionSection *secion,
562                                        hwaddr start, hwaddr size)
563 {
564     KVMState *s = kvm_state;
565 
566     if (s->coalesced_mmio) {
567         struct kvm_coalesced_mmio_zone zone;
568 
569         zone.addr = start;
570         zone.size = size;
571         zone.pad = 0;
572 
573         (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
574     }
575 }
576 
577 int kvm_check_extension(KVMState *s, unsigned int extension)
578 {
579     int ret;
580 
581     ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
582     if (ret < 0) {
583         ret = 0;
584     }
585 
586     return ret;
587 }
588 
589 int kvm_vm_check_extension(KVMState *s, unsigned int extension)
590 {
591     int ret;
592 
593     ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
594     if (ret < 0) {
595         /* VM wide version not implemented, use global one instead */
596         ret = kvm_check_extension(s, extension);
597     }
598 
599     return ret;
600 }
601 
602 static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
603 {
604 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
605     /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
606      * endianness, but the memory core hands them in target endianness.
607      * For example, PPC is always treated as big-endian even if running
608      * on KVM and on PPC64LE.  Correct here.
609      */
610     switch (size) {
611     case 2:
612         val = bswap16(val);
613         break;
614     case 4:
615         val = bswap32(val);
616         break;
617     }
618 #endif
619     return val;
620 }
621 
622 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
623                                   bool assign, uint32_t size, bool datamatch)
624 {
625     int ret;
626     struct kvm_ioeventfd iofd = {
627         .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
628         .addr = addr,
629         .len = size,
630         .flags = 0,
631         .fd = fd,
632     };
633 
634     if (!kvm_enabled()) {
635         return -ENOSYS;
636     }
637 
638     if (datamatch) {
639         iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
640     }
641     if (!assign) {
642         iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
643     }
644 
645     ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
646 
647     if (ret < 0) {
648         return -errno;
649     }
650 
651     return 0;
652 }
653 
654 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
655                                  bool assign, uint32_t size, bool datamatch)
656 {
657     struct kvm_ioeventfd kick = {
658         .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
659         .addr = addr,
660         .flags = KVM_IOEVENTFD_FLAG_PIO,
661         .len = size,
662         .fd = fd,
663     };
664     int r;
665     if (!kvm_enabled()) {
666         return -ENOSYS;
667     }
668     if (datamatch) {
669         kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
670     }
671     if (!assign) {
672         kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
673     }
674     r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
675     if (r < 0) {
676         return r;
677     }
678     return 0;
679 }
680 
681 
682 static int kvm_check_many_ioeventfds(void)
683 {
684     /* Userspace can use ioeventfd for io notification.  This requires a host
685      * that supports eventfd(2) and an I/O thread; since eventfd does not
686      * support SIGIO it cannot interrupt the vcpu.
687      *
688      * Older kernels have a 6 device limit on the KVM io bus.  Find out so we
689      * can avoid creating too many ioeventfds.
690      */
691 #if defined(CONFIG_EVENTFD)
692     int ioeventfds[7];
693     int i, ret = 0;
694     for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
695         ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
696         if (ioeventfds[i] < 0) {
697             break;
698         }
699         ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
700         if (ret < 0) {
701             close(ioeventfds[i]);
702             break;
703         }
704     }
705 
706     /* Decide whether many devices are supported or not */
707     ret = i == ARRAY_SIZE(ioeventfds);
708 
709     while (i-- > 0) {
710         kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
711         close(ioeventfds[i]);
712     }
713     return ret;
714 #else
715     return 0;
716 #endif
717 }
718 
719 static const KVMCapabilityInfo *
720 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
721 {
722     while (list->name) {
723         if (!kvm_check_extension(s, list->value)) {
724             return list;
725         }
726         list++;
727     }
728     return NULL;
729 }
730 
731 static void kvm_set_phys_mem(KVMMemoryListener *kml,
732                              MemoryRegionSection *section, bool add)
733 {
734     KVMSlot *mem;
735     int err;
736     MemoryRegion *mr = section->mr;
737     bool writeable = !mr->readonly && !mr->rom_device;
738     hwaddr start_addr, size;
739     void *ram;
740 
741     if (!memory_region_is_ram(mr)) {
742         if (writeable || !kvm_readonly_mem_allowed) {
743             return;
744         } else if (!mr->romd_mode) {
745             /* If the memory device is not in romd_mode, then we actually want
746              * to remove the kvm memory slot so all accesses will trap. */
747             add = false;
748         }
749     }
750 
751     size = kvm_align_section(section, &start_addr);
752     if (!size) {
753         return;
754     }
755 
756     ram = memory_region_get_ram_ptr(mr) + section->offset_within_region +
757           (section->offset_within_address_space - start_addr);
758 
759     mem = kvm_lookup_matching_slot(kml, start_addr, size);
760     if (!add) {
761         if (!mem) {
762             g_assert(!memory_region_is_ram(mr) && !writeable && !mr->romd_mode);
763             return;
764         }
765         if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
766             kvm_physical_sync_dirty_bitmap(kml, section);
767         }
768 
769         /* unregister the slot */
770         mem->memory_size = 0;
771         err = kvm_set_user_memory_region(kml, mem);
772         if (err) {
773             fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
774                     __func__, strerror(-err));
775             abort();
776         }
777         return;
778     }
779 
780     if (mem) {
781         /* update the slot */
782         kvm_slot_update_flags(kml, mem, mr);
783         return;
784     }
785 
786     /* register the new slot */
787     mem = kvm_alloc_slot(kml);
788     mem->memory_size = size;
789     mem->start_addr = start_addr;
790     mem->ram = ram;
791     mem->flags = kvm_mem_flags(mr);
792 
793     err = kvm_set_user_memory_region(kml, mem);
794     if (err) {
795         fprintf(stderr, "%s: error registering slot: %s\n", __func__,
796                 strerror(-err));
797         abort();
798     }
799 }
800 
801 static void kvm_region_add(MemoryListener *listener,
802                            MemoryRegionSection *section)
803 {
804     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
805 
806     memory_region_ref(section->mr);
807     kvm_set_phys_mem(kml, section, true);
808 }
809 
810 static void kvm_region_del(MemoryListener *listener,
811                            MemoryRegionSection *section)
812 {
813     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
814 
815     kvm_set_phys_mem(kml, section, false);
816     memory_region_unref(section->mr);
817 }
818 
819 static void kvm_log_sync(MemoryListener *listener,
820                          MemoryRegionSection *section)
821 {
822     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
823     int r;
824 
825     r = kvm_physical_sync_dirty_bitmap(kml, section);
826     if (r < 0) {
827         abort();
828     }
829 }
830 
831 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
832                                   MemoryRegionSection *section,
833                                   bool match_data, uint64_t data,
834                                   EventNotifier *e)
835 {
836     int fd = event_notifier_get_fd(e);
837     int r;
838 
839     r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
840                                data, true, int128_get64(section->size),
841                                match_data);
842     if (r < 0) {
843         fprintf(stderr, "%s: error adding ioeventfd: %s\n",
844                 __func__, strerror(-r));
845         abort();
846     }
847 }
848 
849 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
850                                   MemoryRegionSection *section,
851                                   bool match_data, uint64_t data,
852                                   EventNotifier *e)
853 {
854     int fd = event_notifier_get_fd(e);
855     int r;
856 
857     r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
858                                data, false, int128_get64(section->size),
859                                match_data);
860     if (r < 0) {
861         abort();
862     }
863 }
864 
865 static void kvm_io_ioeventfd_add(MemoryListener *listener,
866                                  MemoryRegionSection *section,
867                                  bool match_data, uint64_t data,
868                                  EventNotifier *e)
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, true, int128_get64(section->size),
875                               match_data);
876     if (r < 0) {
877         fprintf(stderr, "%s: error adding ioeventfd: %s\n",
878                 __func__, strerror(-r));
879         abort();
880     }
881 }
882 
883 static void kvm_io_ioeventfd_del(MemoryListener *listener,
884                                  MemoryRegionSection *section,
885                                  bool match_data, uint64_t data,
886                                  EventNotifier *e)
887 
888 {
889     int fd = event_notifier_get_fd(e);
890     int r;
891 
892     r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
893                               data, false, int128_get64(section->size),
894                               match_data);
895     if (r < 0) {
896         abort();
897     }
898 }
899 
900 void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
901                                   AddressSpace *as, int as_id)
902 {
903     int i;
904 
905     kml->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
906     kml->as_id = as_id;
907 
908     for (i = 0; i < s->nr_slots; i++) {
909         kml->slots[i].slot = i;
910     }
911 
912     kml->listener.region_add = kvm_region_add;
913     kml->listener.region_del = kvm_region_del;
914     kml->listener.log_start = kvm_log_start;
915     kml->listener.log_stop = kvm_log_stop;
916     kml->listener.log_sync = kvm_log_sync;
917     kml->listener.priority = 10;
918 
919     memory_listener_register(&kml->listener, as);
920 }
921 
922 static MemoryListener kvm_io_listener = {
923     .eventfd_add = kvm_io_ioeventfd_add,
924     .eventfd_del = kvm_io_ioeventfd_del,
925     .priority = 10,
926 };
927 
928 int kvm_set_irq(KVMState *s, int irq, int level)
929 {
930     struct kvm_irq_level event;
931     int ret;
932 
933     assert(kvm_async_interrupts_enabled());
934 
935     event.level = level;
936     event.irq = irq;
937     ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
938     if (ret < 0) {
939         perror("kvm_set_irq");
940         abort();
941     }
942 
943     return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
944 }
945 
946 #ifdef KVM_CAP_IRQ_ROUTING
947 typedef struct KVMMSIRoute {
948     struct kvm_irq_routing_entry kroute;
949     QTAILQ_ENTRY(KVMMSIRoute) entry;
950 } KVMMSIRoute;
951 
952 static void set_gsi(KVMState *s, unsigned int gsi)
953 {
954     set_bit(gsi, s->used_gsi_bitmap);
955 }
956 
957 static void clear_gsi(KVMState *s, unsigned int gsi)
958 {
959     clear_bit(gsi, s->used_gsi_bitmap);
960 }
961 
962 void kvm_init_irq_routing(KVMState *s)
963 {
964     int gsi_count, i;
965 
966     gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
967     if (gsi_count > 0) {
968         /* Round up so we can search ints using ffs */
969         s->used_gsi_bitmap = bitmap_new(gsi_count);
970         s->gsi_count = gsi_count;
971     }
972 
973     s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
974     s->nr_allocated_irq_routes = 0;
975 
976     if (!kvm_direct_msi_allowed) {
977         for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
978             QTAILQ_INIT(&s->msi_hashtab[i]);
979         }
980     }
981 
982     kvm_arch_init_irq_routing(s);
983 }
984 
985 void kvm_irqchip_commit_routes(KVMState *s)
986 {
987     int ret;
988 
989     if (kvm_gsi_direct_mapping()) {
990         return;
991     }
992 
993     if (!kvm_gsi_routing_enabled()) {
994         return;
995     }
996 
997     s->irq_routes->flags = 0;
998     trace_kvm_irqchip_commit_routes();
999     ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1000     assert(ret == 0);
1001 }
1002 
1003 static void kvm_add_routing_entry(KVMState *s,
1004                                   struct kvm_irq_routing_entry *entry)
1005 {
1006     struct kvm_irq_routing_entry *new;
1007     int n, size;
1008 
1009     if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1010         n = s->nr_allocated_irq_routes * 2;
1011         if (n < 64) {
1012             n = 64;
1013         }
1014         size = sizeof(struct kvm_irq_routing);
1015         size += n * sizeof(*new);
1016         s->irq_routes = g_realloc(s->irq_routes, size);
1017         s->nr_allocated_irq_routes = n;
1018     }
1019     n = s->irq_routes->nr++;
1020     new = &s->irq_routes->entries[n];
1021 
1022     *new = *entry;
1023 
1024     set_gsi(s, entry->gsi);
1025 }
1026 
1027 static int kvm_update_routing_entry(KVMState *s,
1028                                     struct kvm_irq_routing_entry *new_entry)
1029 {
1030     struct kvm_irq_routing_entry *entry;
1031     int n;
1032 
1033     for (n = 0; n < s->irq_routes->nr; n++) {
1034         entry = &s->irq_routes->entries[n];
1035         if (entry->gsi != new_entry->gsi) {
1036             continue;
1037         }
1038 
1039         if(!memcmp(entry, new_entry, sizeof *entry)) {
1040             return 0;
1041         }
1042 
1043         *entry = *new_entry;
1044 
1045         return 0;
1046     }
1047 
1048     return -ESRCH;
1049 }
1050 
1051 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1052 {
1053     struct kvm_irq_routing_entry e = {};
1054 
1055     assert(pin < s->gsi_count);
1056 
1057     e.gsi = irq;
1058     e.type = KVM_IRQ_ROUTING_IRQCHIP;
1059     e.flags = 0;
1060     e.u.irqchip.irqchip = irqchip;
1061     e.u.irqchip.pin = pin;
1062     kvm_add_routing_entry(s, &e);
1063 }
1064 
1065 void kvm_irqchip_release_virq(KVMState *s, int virq)
1066 {
1067     struct kvm_irq_routing_entry *e;
1068     int i;
1069 
1070     if (kvm_gsi_direct_mapping()) {
1071         return;
1072     }
1073 
1074     for (i = 0; i < s->irq_routes->nr; i++) {
1075         e = &s->irq_routes->entries[i];
1076         if (e->gsi == virq) {
1077             s->irq_routes->nr--;
1078             *e = s->irq_routes->entries[s->irq_routes->nr];
1079         }
1080     }
1081     clear_gsi(s, virq);
1082     kvm_arch_release_virq_post(virq);
1083     trace_kvm_irqchip_release_virq(virq);
1084 }
1085 
1086 static unsigned int kvm_hash_msi(uint32_t data)
1087 {
1088     /* This is optimized for IA32 MSI layout. However, no other arch shall
1089      * repeat the mistake of not providing a direct MSI injection API. */
1090     return data & 0xff;
1091 }
1092 
1093 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1094 {
1095     KVMMSIRoute *route, *next;
1096     unsigned int hash;
1097 
1098     for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1099         QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1100             kvm_irqchip_release_virq(s, route->kroute.gsi);
1101             QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1102             g_free(route);
1103         }
1104     }
1105 }
1106 
1107 static int kvm_irqchip_get_virq(KVMState *s)
1108 {
1109     int next_virq;
1110 
1111     /*
1112      * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1113      * GSI numbers are more than the number of IRQ route. Allocating a GSI
1114      * number can succeed even though a new route entry cannot be added.
1115      * When this happens, flush dynamic MSI entries to free IRQ route entries.
1116      */
1117     if (!kvm_direct_msi_allowed && s->irq_routes->nr == s->gsi_count) {
1118         kvm_flush_dynamic_msi_routes(s);
1119     }
1120 
1121     /* Return the lowest unused GSI in the bitmap */
1122     next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
1123     if (next_virq >= s->gsi_count) {
1124         return -ENOSPC;
1125     } else {
1126         return next_virq;
1127     }
1128 }
1129 
1130 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1131 {
1132     unsigned int hash = kvm_hash_msi(msg.data);
1133     KVMMSIRoute *route;
1134 
1135     QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1136         if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1137             route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1138             route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1139             return route;
1140         }
1141     }
1142     return NULL;
1143 }
1144 
1145 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1146 {
1147     struct kvm_msi msi;
1148     KVMMSIRoute *route;
1149 
1150     if (kvm_direct_msi_allowed) {
1151         msi.address_lo = (uint32_t)msg.address;
1152         msi.address_hi = msg.address >> 32;
1153         msi.data = le32_to_cpu(msg.data);
1154         msi.flags = 0;
1155         memset(msi.pad, 0, sizeof(msi.pad));
1156 
1157         return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1158     }
1159 
1160     route = kvm_lookup_msi_route(s, msg);
1161     if (!route) {
1162         int virq;
1163 
1164         virq = kvm_irqchip_get_virq(s);
1165         if (virq < 0) {
1166             return virq;
1167         }
1168 
1169         route = g_malloc0(sizeof(KVMMSIRoute));
1170         route->kroute.gsi = virq;
1171         route->kroute.type = KVM_IRQ_ROUTING_MSI;
1172         route->kroute.flags = 0;
1173         route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1174         route->kroute.u.msi.address_hi = msg.address >> 32;
1175         route->kroute.u.msi.data = le32_to_cpu(msg.data);
1176 
1177         kvm_add_routing_entry(s, &route->kroute);
1178         kvm_irqchip_commit_routes(s);
1179 
1180         QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1181                            entry);
1182     }
1183 
1184     assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1185 
1186     return kvm_set_irq(s, route->kroute.gsi, 1);
1187 }
1188 
1189 int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
1190 {
1191     struct kvm_irq_routing_entry kroute = {};
1192     int virq;
1193     MSIMessage msg = {0, 0};
1194 
1195     if (pci_available && dev) {
1196         msg = pci_get_msi_message(dev, vector);
1197     }
1198 
1199     if (kvm_gsi_direct_mapping()) {
1200         return kvm_arch_msi_data_to_gsi(msg.data);
1201     }
1202 
1203     if (!kvm_gsi_routing_enabled()) {
1204         return -ENOSYS;
1205     }
1206 
1207     virq = kvm_irqchip_get_virq(s);
1208     if (virq < 0) {
1209         return virq;
1210     }
1211 
1212     kroute.gsi = virq;
1213     kroute.type = KVM_IRQ_ROUTING_MSI;
1214     kroute.flags = 0;
1215     kroute.u.msi.address_lo = (uint32_t)msg.address;
1216     kroute.u.msi.address_hi = msg.address >> 32;
1217     kroute.u.msi.data = le32_to_cpu(msg.data);
1218     if (pci_available && kvm_msi_devid_required()) {
1219         kroute.flags = KVM_MSI_VALID_DEVID;
1220         kroute.u.msi.devid = pci_requester_id(dev);
1221     }
1222     if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1223         kvm_irqchip_release_virq(s, virq);
1224         return -EINVAL;
1225     }
1226 
1227     trace_kvm_irqchip_add_msi_route(dev ? dev->name : (char *)"N/A",
1228                                     vector, virq);
1229 
1230     kvm_add_routing_entry(s, &kroute);
1231     kvm_arch_add_msi_route_post(&kroute, vector, dev);
1232     kvm_irqchip_commit_routes(s);
1233 
1234     return virq;
1235 }
1236 
1237 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
1238                                  PCIDevice *dev)
1239 {
1240     struct kvm_irq_routing_entry kroute = {};
1241 
1242     if (kvm_gsi_direct_mapping()) {
1243         return 0;
1244     }
1245 
1246     if (!kvm_irqchip_in_kernel()) {
1247         return -ENOSYS;
1248     }
1249 
1250     kroute.gsi = virq;
1251     kroute.type = KVM_IRQ_ROUTING_MSI;
1252     kroute.flags = 0;
1253     kroute.u.msi.address_lo = (uint32_t)msg.address;
1254     kroute.u.msi.address_hi = msg.address >> 32;
1255     kroute.u.msi.data = le32_to_cpu(msg.data);
1256     if (pci_available && kvm_msi_devid_required()) {
1257         kroute.flags = KVM_MSI_VALID_DEVID;
1258         kroute.u.msi.devid = pci_requester_id(dev);
1259     }
1260     if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1261         return -EINVAL;
1262     }
1263 
1264     trace_kvm_irqchip_update_msi_route(virq);
1265 
1266     return kvm_update_routing_entry(s, &kroute);
1267 }
1268 
1269 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int rfd, int virq,
1270                                     bool assign)
1271 {
1272     struct kvm_irqfd irqfd = {
1273         .fd = fd,
1274         .gsi = virq,
1275         .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1276     };
1277 
1278     if (rfd != -1) {
1279         irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1280         irqfd.resamplefd = rfd;
1281     }
1282 
1283     if (!kvm_irqfds_enabled()) {
1284         return -ENOSYS;
1285     }
1286 
1287     return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1288 }
1289 
1290 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1291 {
1292     struct kvm_irq_routing_entry kroute = {};
1293     int virq;
1294 
1295     if (!kvm_gsi_routing_enabled()) {
1296         return -ENOSYS;
1297     }
1298 
1299     virq = kvm_irqchip_get_virq(s);
1300     if (virq < 0) {
1301         return virq;
1302     }
1303 
1304     kroute.gsi = virq;
1305     kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1306     kroute.flags = 0;
1307     kroute.u.adapter.summary_addr = adapter->summary_addr;
1308     kroute.u.adapter.ind_addr = adapter->ind_addr;
1309     kroute.u.adapter.summary_offset = adapter->summary_offset;
1310     kroute.u.adapter.ind_offset = adapter->ind_offset;
1311     kroute.u.adapter.adapter_id = adapter->adapter_id;
1312 
1313     kvm_add_routing_entry(s, &kroute);
1314 
1315     return virq;
1316 }
1317 
1318 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1319 {
1320     struct kvm_irq_routing_entry kroute = {};
1321     int virq;
1322 
1323     if (!kvm_gsi_routing_enabled()) {
1324         return -ENOSYS;
1325     }
1326     if (!kvm_check_extension(s, KVM_CAP_HYPERV_SYNIC)) {
1327         return -ENOSYS;
1328     }
1329     virq = kvm_irqchip_get_virq(s);
1330     if (virq < 0) {
1331         return virq;
1332     }
1333 
1334     kroute.gsi = virq;
1335     kroute.type = KVM_IRQ_ROUTING_HV_SINT;
1336     kroute.flags = 0;
1337     kroute.u.hv_sint.vcpu = vcpu;
1338     kroute.u.hv_sint.sint = sint;
1339 
1340     kvm_add_routing_entry(s, &kroute);
1341     kvm_irqchip_commit_routes(s);
1342 
1343     return virq;
1344 }
1345 
1346 #else /* !KVM_CAP_IRQ_ROUTING */
1347 
1348 void kvm_init_irq_routing(KVMState *s)
1349 {
1350 }
1351 
1352 void kvm_irqchip_release_virq(KVMState *s, int virq)
1353 {
1354 }
1355 
1356 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1357 {
1358     abort();
1359 }
1360 
1361 int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
1362 {
1363     return -ENOSYS;
1364 }
1365 
1366 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1367 {
1368     return -ENOSYS;
1369 }
1370 
1371 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1372 {
1373     return -ENOSYS;
1374 }
1375 
1376 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1377 {
1378     abort();
1379 }
1380 
1381 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1382 {
1383     return -ENOSYS;
1384 }
1385 #endif /* !KVM_CAP_IRQ_ROUTING */
1386 
1387 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1388                                        EventNotifier *rn, int virq)
1389 {
1390     return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n),
1391            rn ? event_notifier_get_fd(rn) : -1, virq, true);
1392 }
1393 
1394 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1395                                           int virq)
1396 {
1397     return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), -1, virq,
1398            false);
1399 }
1400 
1401 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1402                                    EventNotifier *rn, qemu_irq irq)
1403 {
1404     gpointer key, gsi;
1405     gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1406 
1407     if (!found) {
1408         return -ENXIO;
1409     }
1410     return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
1411 }
1412 
1413 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
1414                                       qemu_irq irq)
1415 {
1416     gpointer key, gsi;
1417     gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1418 
1419     if (!found) {
1420         return -ENXIO;
1421     }
1422     return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
1423 }
1424 
1425 void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
1426 {
1427     g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
1428 }
1429 
1430 static void kvm_irqchip_create(MachineState *machine, KVMState *s)
1431 {
1432     int ret;
1433 
1434     if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
1435         ;
1436     } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
1437         ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
1438         if (ret < 0) {
1439             fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
1440             exit(1);
1441         }
1442     } else {
1443         return;
1444     }
1445 
1446     /* First probe and see if there's a arch-specific hook to create the
1447      * in-kernel irqchip for us */
1448     ret = kvm_arch_irqchip_create(machine, s);
1449     if (ret == 0) {
1450         if (machine_kernel_irqchip_split(machine)) {
1451             perror("Split IRQ chip mode not supported.");
1452             exit(1);
1453         } else {
1454             ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1455         }
1456     }
1457     if (ret < 0) {
1458         fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
1459         exit(1);
1460     }
1461 
1462     kvm_kernel_irqchip = true;
1463     /* If we have an in-kernel IRQ chip then we must have asynchronous
1464      * interrupt delivery (though the reverse is not necessarily true)
1465      */
1466     kvm_async_interrupts_allowed = true;
1467     kvm_halt_in_kernel_allowed = true;
1468 
1469     kvm_init_irq_routing(s);
1470 
1471     s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
1472 }
1473 
1474 /* Find number of supported CPUs using the recommended
1475  * procedure from the kernel API documentation to cope with
1476  * older kernels that may be missing capabilities.
1477  */
1478 static int kvm_recommended_vcpus(KVMState *s)
1479 {
1480     int ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
1481     return (ret) ? ret : 4;
1482 }
1483 
1484 static int kvm_max_vcpus(KVMState *s)
1485 {
1486     int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1487     return (ret) ? ret : kvm_recommended_vcpus(s);
1488 }
1489 
1490 static int kvm_max_vcpu_id(KVMState *s)
1491 {
1492     int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
1493     return (ret) ? ret : kvm_max_vcpus(s);
1494 }
1495 
1496 bool kvm_vcpu_id_is_valid(int vcpu_id)
1497 {
1498     KVMState *s = KVM_STATE(current_machine->accelerator);
1499     return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
1500 }
1501 
1502 static int kvm_init(MachineState *ms)
1503 {
1504     MachineClass *mc = MACHINE_GET_CLASS(ms);
1505     static const char upgrade_note[] =
1506         "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1507         "(see http://sourceforge.net/projects/kvm).\n";
1508     struct {
1509         const char *name;
1510         int num;
1511     } num_cpus[] = {
1512         { "SMP",          smp_cpus },
1513         { "hotpluggable", max_cpus },
1514         { NULL, }
1515     }, *nc = num_cpus;
1516     int soft_vcpus_limit, hard_vcpus_limit;
1517     KVMState *s;
1518     const KVMCapabilityInfo *missing_cap;
1519     int ret;
1520     int type = 0;
1521     const char *kvm_type;
1522 
1523     s = KVM_STATE(ms->accelerator);
1524 
1525     /*
1526      * On systems where the kernel can support different base page
1527      * sizes, host page size may be different from TARGET_PAGE_SIZE,
1528      * even with KVM.  TARGET_PAGE_SIZE is assumed to be the minimum
1529      * page size for the system though.
1530      */
1531     assert(TARGET_PAGE_SIZE <= getpagesize());
1532 
1533     s->sigmask_len = 8;
1534 
1535 #ifdef KVM_CAP_SET_GUEST_DEBUG
1536     QTAILQ_INIT(&s->kvm_sw_breakpoints);
1537 #endif
1538     QLIST_INIT(&s->kvm_parked_vcpus);
1539     s->vmfd = -1;
1540     s->fd = qemu_open("/dev/kvm", O_RDWR);
1541     if (s->fd == -1) {
1542         fprintf(stderr, "Could not access KVM kernel module: %m\n");
1543         ret = -errno;
1544         goto err;
1545     }
1546 
1547     ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1548     if (ret < KVM_API_VERSION) {
1549         if (ret >= 0) {
1550             ret = -EINVAL;
1551         }
1552         fprintf(stderr, "kvm version too old\n");
1553         goto err;
1554     }
1555 
1556     if (ret > KVM_API_VERSION) {
1557         ret = -EINVAL;
1558         fprintf(stderr, "kvm version not supported\n");
1559         goto err;
1560     }
1561 
1562     kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
1563     s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
1564 
1565     /* If unspecified, use the default value */
1566     if (!s->nr_slots) {
1567         s->nr_slots = 32;
1568     }
1569 
1570     /* check the vcpu limits */
1571     soft_vcpus_limit = kvm_recommended_vcpus(s);
1572     hard_vcpus_limit = kvm_max_vcpus(s);
1573 
1574     while (nc->name) {
1575         if (nc->num > soft_vcpus_limit) {
1576             fprintf(stderr,
1577                     "Warning: Number of %s cpus requested (%d) exceeds "
1578                     "the recommended cpus supported by KVM (%d)\n",
1579                     nc->name, nc->num, soft_vcpus_limit);
1580 
1581             if (nc->num > hard_vcpus_limit) {
1582                 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
1583                         "the maximum cpus supported by KVM (%d)\n",
1584                         nc->name, nc->num, hard_vcpus_limit);
1585                 exit(1);
1586             }
1587         }
1588         nc++;
1589     }
1590 
1591     kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1592     if (mc->kvm_type) {
1593         type = mc->kvm_type(kvm_type);
1594     } else if (kvm_type) {
1595         ret = -EINVAL;
1596         fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1597         goto err;
1598     }
1599 
1600     do {
1601         ret = kvm_ioctl(s, KVM_CREATE_VM, type);
1602     } while (ret == -EINTR);
1603 
1604     if (ret < 0) {
1605         fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
1606                 strerror(-ret));
1607 
1608 #ifdef TARGET_S390X
1609         if (ret == -EINVAL) {
1610             fprintf(stderr,
1611                     "Host kernel setup problem detected. Please verify:\n");
1612             fprintf(stderr, "- for kernels supporting the switch_amode or"
1613                     " user_mode parameters, whether\n");
1614             fprintf(stderr,
1615                     "  user space is running in primary address space\n");
1616             fprintf(stderr,
1617                     "- for kernels supporting the vm.allocate_pgste sysctl, "
1618                     "whether it is enabled\n");
1619         }
1620 #endif
1621         goto err;
1622     }
1623 
1624     s->vmfd = ret;
1625     missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1626     if (!missing_cap) {
1627         missing_cap =
1628             kvm_check_extension_list(s, kvm_arch_required_capabilities);
1629     }
1630     if (missing_cap) {
1631         ret = -EINVAL;
1632         fprintf(stderr, "kvm does not support %s\n%s",
1633                 missing_cap->name, upgrade_note);
1634         goto err;
1635     }
1636 
1637     s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1638 
1639 #ifdef KVM_CAP_VCPU_EVENTS
1640     s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1641 #endif
1642 
1643     s->robust_singlestep =
1644         kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1645 
1646 #ifdef KVM_CAP_DEBUGREGS
1647     s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1648 #endif
1649 
1650 #ifdef KVM_CAP_IRQ_ROUTING
1651     kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1652 #endif
1653 
1654     s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1655 
1656     s->irq_set_ioctl = KVM_IRQ_LINE;
1657     if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1658         s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1659     }
1660 
1661 #ifdef KVM_CAP_READONLY_MEM
1662     kvm_readonly_mem_allowed =
1663         (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1664 #endif
1665 
1666     kvm_eventfds_allowed =
1667         (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
1668 
1669     kvm_irqfds_allowed =
1670         (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
1671 
1672     kvm_resamplefds_allowed =
1673         (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
1674 
1675     kvm_vm_attributes_allowed =
1676         (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
1677 
1678     kvm_ioeventfd_any_length_allowed =
1679         (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
1680 
1681     kvm_state = s;
1682 
1683     ret = kvm_arch_init(ms, s);
1684     if (ret < 0) {
1685         goto err;
1686     }
1687 
1688     if (machine_kernel_irqchip_allowed(ms)) {
1689         kvm_irqchip_create(ms, s);
1690     }
1691 
1692     if (kvm_eventfds_allowed) {
1693         s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
1694         s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
1695     }
1696     s->memory_listener.listener.coalesced_mmio_add = kvm_coalesce_mmio_region;
1697     s->memory_listener.listener.coalesced_mmio_del = kvm_uncoalesce_mmio_region;
1698 
1699     kvm_memory_listener_register(s, &s->memory_listener,
1700                                  &address_space_memory, 0);
1701     memory_listener_register(&kvm_io_listener,
1702                              &address_space_io);
1703 
1704     s->many_ioeventfds = kvm_check_many_ioeventfds();
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 /* Return 1 on success, 0 on failure */
2173 int kvm_has_sync_mmu(void)
2174 {
2175     return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2176 }
2177 
2178 int kvm_has_vcpu_events(void)
2179 {
2180     return kvm_state->vcpu_events;
2181 }
2182 
2183 int kvm_has_robust_singlestep(void)
2184 {
2185     return kvm_state->robust_singlestep;
2186 }
2187 
2188 int kvm_has_debugregs(void)
2189 {
2190     return kvm_state->debugregs;
2191 }
2192 
2193 int kvm_has_many_ioeventfds(void)
2194 {
2195     if (!kvm_enabled()) {
2196         return 0;
2197     }
2198     return kvm_state->many_ioeventfds;
2199 }
2200 
2201 int kvm_has_gsi_routing(void)
2202 {
2203 #ifdef KVM_CAP_IRQ_ROUTING
2204     return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
2205 #else
2206     return false;
2207 #endif
2208 }
2209 
2210 int kvm_has_intx_set_mask(void)
2211 {
2212     return kvm_state->intx_set_mask;
2213 }
2214 
2215 bool kvm_arm_supports_user_irq(void)
2216 {
2217     return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
2218 }
2219 
2220 #ifdef KVM_CAP_SET_GUEST_DEBUG
2221 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
2222                                                  target_ulong pc)
2223 {
2224     struct kvm_sw_breakpoint *bp;
2225 
2226     QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
2227         if (bp->pc == pc) {
2228             return bp;
2229         }
2230     }
2231     return NULL;
2232 }
2233 
2234 int kvm_sw_breakpoints_active(CPUState *cpu)
2235 {
2236     return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
2237 }
2238 
2239 struct kvm_set_guest_debug_data {
2240     struct kvm_guest_debug dbg;
2241     int err;
2242 };
2243 
2244 static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
2245 {
2246     struct kvm_set_guest_debug_data *dbg_data =
2247         (struct kvm_set_guest_debug_data *) data.host_ptr;
2248 
2249     dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
2250                                    &dbg_data->dbg);
2251 }
2252 
2253 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2254 {
2255     struct kvm_set_guest_debug_data data;
2256 
2257     data.dbg.control = reinject_trap;
2258 
2259     if (cpu->singlestep_enabled) {
2260         data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2261     }
2262     kvm_arch_update_guest_debug(cpu, &data.dbg);
2263 
2264     run_on_cpu(cpu, kvm_invoke_set_guest_debug,
2265                RUN_ON_CPU_HOST_PTR(&data));
2266     return data.err;
2267 }
2268 
2269 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2270                           target_ulong len, int type)
2271 {
2272     struct kvm_sw_breakpoint *bp;
2273     int err;
2274 
2275     if (type == GDB_BREAKPOINT_SW) {
2276         bp = kvm_find_sw_breakpoint(cpu, addr);
2277         if (bp) {
2278             bp->use_count++;
2279             return 0;
2280         }
2281 
2282         bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2283         bp->pc = addr;
2284         bp->use_count = 1;
2285         err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2286         if (err) {
2287             g_free(bp);
2288             return err;
2289         }
2290 
2291         QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2292     } else {
2293         err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2294         if (err) {
2295             return err;
2296         }
2297     }
2298 
2299     CPU_FOREACH(cpu) {
2300         err = kvm_update_guest_debug(cpu, 0);
2301         if (err) {
2302             return err;
2303         }
2304     }
2305     return 0;
2306 }
2307 
2308 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2309                           target_ulong len, int type)
2310 {
2311     struct kvm_sw_breakpoint *bp;
2312     int err;
2313 
2314     if (type == GDB_BREAKPOINT_SW) {
2315         bp = kvm_find_sw_breakpoint(cpu, addr);
2316         if (!bp) {
2317             return -ENOENT;
2318         }
2319 
2320         if (bp->use_count > 1) {
2321             bp->use_count--;
2322             return 0;
2323         }
2324 
2325         err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2326         if (err) {
2327             return err;
2328         }
2329 
2330         QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2331         g_free(bp);
2332     } else {
2333         err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2334         if (err) {
2335             return err;
2336         }
2337     }
2338 
2339     CPU_FOREACH(cpu) {
2340         err = kvm_update_guest_debug(cpu, 0);
2341         if (err) {
2342             return err;
2343         }
2344     }
2345     return 0;
2346 }
2347 
2348 void kvm_remove_all_breakpoints(CPUState *cpu)
2349 {
2350     struct kvm_sw_breakpoint *bp, *next;
2351     KVMState *s = cpu->kvm_state;
2352     CPUState *tmpcpu;
2353 
2354     QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2355         if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2356             /* Try harder to find a CPU that currently sees the breakpoint. */
2357             CPU_FOREACH(tmpcpu) {
2358                 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2359                     break;
2360                 }
2361             }
2362         }
2363         QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2364         g_free(bp);
2365     }
2366     kvm_arch_remove_all_hw_breakpoints();
2367 
2368     CPU_FOREACH(cpu) {
2369         kvm_update_guest_debug(cpu, 0);
2370     }
2371 }
2372 
2373 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2374 
2375 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2376 {
2377     return -EINVAL;
2378 }
2379 
2380 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2381                           target_ulong len, int type)
2382 {
2383     return -EINVAL;
2384 }
2385 
2386 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2387                           target_ulong len, int type)
2388 {
2389     return -EINVAL;
2390 }
2391 
2392 void kvm_remove_all_breakpoints(CPUState *cpu)
2393 {
2394 }
2395 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2396 
2397 static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2398 {
2399     KVMState *s = kvm_state;
2400     struct kvm_signal_mask *sigmask;
2401     int r;
2402 
2403     sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2404 
2405     sigmask->len = s->sigmask_len;
2406     memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2407     r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2408     g_free(sigmask);
2409 
2410     return r;
2411 }
2412 
2413 static void kvm_ipi_signal(int sig)
2414 {
2415     if (current_cpu) {
2416         assert(kvm_immediate_exit);
2417         kvm_cpu_kick(current_cpu);
2418     }
2419 }
2420 
2421 void kvm_init_cpu_signals(CPUState *cpu)
2422 {
2423     int r;
2424     sigset_t set;
2425     struct sigaction sigact;
2426 
2427     memset(&sigact, 0, sizeof(sigact));
2428     sigact.sa_handler = kvm_ipi_signal;
2429     sigaction(SIG_IPI, &sigact, NULL);
2430 
2431     pthread_sigmask(SIG_BLOCK, NULL, &set);
2432 #if defined KVM_HAVE_MCE_INJECTION
2433     sigdelset(&set, SIGBUS);
2434     pthread_sigmask(SIG_SETMASK, &set, NULL);
2435 #endif
2436     sigdelset(&set, SIG_IPI);
2437     if (kvm_immediate_exit) {
2438         r = pthread_sigmask(SIG_SETMASK, &set, NULL);
2439     } else {
2440         r = kvm_set_signal_mask(cpu, &set);
2441     }
2442     if (r) {
2443         fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
2444         exit(1);
2445     }
2446 }
2447 
2448 /* Called asynchronously in VCPU thread.  */
2449 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2450 {
2451 #ifdef KVM_HAVE_MCE_INJECTION
2452     if (have_sigbus_pending) {
2453         return 1;
2454     }
2455     have_sigbus_pending = true;
2456     pending_sigbus_addr = addr;
2457     pending_sigbus_code = code;
2458     atomic_set(&cpu->exit_request, 1);
2459     return 0;
2460 #else
2461     return 1;
2462 #endif
2463 }
2464 
2465 /* Called synchronously (via signalfd) in main thread.  */
2466 int kvm_on_sigbus(int code, void *addr)
2467 {
2468 #ifdef KVM_HAVE_MCE_INJECTION
2469     /* Action required MCE kills the process if SIGBUS is blocked.  Because
2470      * that's what happens in the I/O thread, where we handle MCE via signalfd,
2471      * we can only get action optional here.
2472      */
2473     assert(code != BUS_MCEERR_AR);
2474     kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
2475     return 0;
2476 #else
2477     return 1;
2478 #endif
2479 }
2480 
2481 int kvm_create_device(KVMState *s, uint64_t type, bool test)
2482 {
2483     int ret;
2484     struct kvm_create_device create_dev;
2485 
2486     create_dev.type = type;
2487     create_dev.fd = -1;
2488     create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2489 
2490     if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2491         return -ENOTSUP;
2492     }
2493 
2494     ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2495     if (ret) {
2496         return ret;
2497     }
2498 
2499     return test ? 0 : create_dev.fd;
2500 }
2501 
2502 bool kvm_device_supported(int vmfd, uint64_t type)
2503 {
2504     struct kvm_create_device create_dev = {
2505         .type = type,
2506         .fd = -1,
2507         .flags = KVM_CREATE_DEVICE_TEST,
2508     };
2509 
2510     if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
2511         return false;
2512     }
2513 
2514     return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
2515 }
2516 
2517 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2518 {
2519     struct kvm_one_reg reg;
2520     int r;
2521 
2522     reg.id = id;
2523     reg.addr = (uintptr_t) source;
2524     r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
2525     if (r) {
2526         trace_kvm_failed_reg_set(id, strerror(-r));
2527     }
2528     return r;
2529 }
2530 
2531 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2532 {
2533     struct kvm_one_reg reg;
2534     int r;
2535 
2536     reg.id = id;
2537     reg.addr = (uintptr_t) target;
2538     r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
2539     if (r) {
2540         trace_kvm_failed_reg_get(id, strerror(-r));
2541     }
2542     return r;
2543 }
2544 
2545 static void kvm_accel_class_init(ObjectClass *oc, void *data)
2546 {
2547     AccelClass *ac = ACCEL_CLASS(oc);
2548     ac->name = "KVM";
2549     ac->init_machine = kvm_init;
2550     ac->allowed = &kvm_allowed;
2551 }
2552 
2553 static const TypeInfo kvm_accel_type = {
2554     .name = TYPE_KVM_ACCEL,
2555     .parent = TYPE_ACCEL,
2556     .class_init = kvm_accel_class_init,
2557     .instance_size = sizeof(KVMState),
2558 };
2559 
2560 static void kvm_type_init(void)
2561 {
2562     type_register_static(&kvm_accel_type);
2563 }
2564 
2565 type_init(kvm_type_init);
2566