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