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