xref: /openbmc/qemu/accel/kvm/kvm-all.c (revision 2182e405)
1 /*
2  * QEMU KVM support
3  *
4  * Copyright IBM, Corp. 2008
5  *           Red Hat, Inc. 2008
6  *
7  * Authors:
8  *  Anthony Liguori   <aliguori@us.ibm.com>
9  *  Glauber Costa     <gcosta@redhat.com>
10  *
11  * This work is licensed under the terms of the GNU GPL, version 2 or later.
12  * See the COPYING file in the top-level directory.
13  *
14  */
15 
16 #include "qemu/osdep.h"
17 #include <sys/ioctl.h>
18 
19 #include <linux/kvm.h>
20 
21 #include "qemu/atomic.h"
22 #include "qemu/option.h"
23 #include "qemu/config-file.h"
24 #include "qemu/error-report.h"
25 #include "qapi/error.h"
26 #include "hw/pci/msi.h"
27 #include "hw/pci/msix.h"
28 #include "hw/s390x/adapter.h"
29 #include "exec/gdbstub.h"
30 #include "sysemu/kvm_int.h"
31 #include "sysemu/runstate.h"
32 #include "sysemu/cpus.h"
33 #include "sysemu/sysemu.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 "qemu/main-loop.h"
40 #include "trace.h"
41 #include "hw/irq.h"
42 #include "qapi/visitor.h"
43 #include "qapi/qapi-types-common.h"
44 #include "qapi/qapi-visit-common.h"
45 #include "sysemu/reset.h"
46 #include "qemu/guest-random.h"
47 #include "sysemu/hw_accel.h"
48 #include "kvm-cpus.h"
49 
50 #include "hw/boards.h"
51 
52 /* This check must be after config-host.h is included */
53 #ifdef CONFIG_EVENTFD
54 #include <sys/eventfd.h>
55 #endif
56 
57 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
58  * need to use the real host PAGE_SIZE, as that's what KVM will use.
59  */
60 #ifdef PAGE_SIZE
61 #undef PAGE_SIZE
62 #endif
63 #define PAGE_SIZE qemu_real_host_page_size
64 
65 //#define DEBUG_KVM
66 
67 #ifdef DEBUG_KVM
68 #define DPRINTF(fmt, ...) \
69     do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
70 #else
71 #define DPRINTF(fmt, ...) \
72     do { } while (0)
73 #endif
74 
75 #define KVM_MSI_HASHTAB_SIZE    256
76 
77 struct KVMParkedVcpu {
78     unsigned long vcpu_id;
79     int kvm_fd;
80     QLIST_ENTRY(KVMParkedVcpu) node;
81 };
82 
83 struct KVMState
84 {
85     AccelState parent_obj;
86 
87     int nr_slots;
88     int fd;
89     int vmfd;
90     int coalesced_mmio;
91     int coalesced_pio;
92     struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
93     bool coalesced_flush_in_progress;
94     int vcpu_events;
95     int robust_singlestep;
96     int debugregs;
97 #ifdef KVM_CAP_SET_GUEST_DEBUG
98     QTAILQ_HEAD(, kvm_sw_breakpoint) kvm_sw_breakpoints;
99 #endif
100     int max_nested_state_len;
101     int many_ioeventfds;
102     int intx_set_mask;
103     int kvm_shadow_mem;
104     bool kernel_irqchip_allowed;
105     bool kernel_irqchip_required;
106     OnOffAuto kernel_irqchip_split;
107     bool sync_mmu;
108     uint64_t manual_dirty_log_protect;
109     /* The man page (and posix) say ioctl numbers are signed int, but
110      * they're not.  Linux, glibc and *BSD all treat ioctl numbers as
111      * unsigned, and treating them as signed here can break things */
112     unsigned irq_set_ioctl;
113     unsigned int sigmask_len;
114     GHashTable *gsimap;
115 #ifdef KVM_CAP_IRQ_ROUTING
116     struct kvm_irq_routing *irq_routes;
117     int nr_allocated_irq_routes;
118     unsigned long *used_gsi_bitmap;
119     unsigned int gsi_count;
120     QTAILQ_HEAD(, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
121 #endif
122     KVMMemoryListener memory_listener;
123     QLIST_HEAD(, KVMParkedVcpu) kvm_parked_vcpus;
124 
125     /* For "info mtree -f" to tell if an MR is registered in KVM */
126     int nr_as;
127     struct KVMAs {
128         KVMMemoryListener *ml;
129         AddressSpace *as;
130     } *as;
131 };
132 
133 KVMState *kvm_state;
134 bool kvm_kernel_irqchip;
135 bool kvm_split_irqchip;
136 bool kvm_async_interrupts_allowed;
137 bool kvm_halt_in_kernel_allowed;
138 bool kvm_eventfds_allowed;
139 bool kvm_irqfds_allowed;
140 bool kvm_resamplefds_allowed;
141 bool kvm_msi_via_irqfd_allowed;
142 bool kvm_gsi_routing_allowed;
143 bool kvm_gsi_direct_mapping;
144 bool kvm_allowed;
145 bool kvm_readonly_mem_allowed;
146 bool kvm_vm_attributes_allowed;
147 bool kvm_direct_msi_allowed;
148 bool kvm_ioeventfd_any_length_allowed;
149 bool kvm_msi_use_devid;
150 static bool kvm_immediate_exit;
151 static hwaddr kvm_max_slot_size = ~0;
152 
153 static const KVMCapabilityInfo kvm_required_capabilites[] = {
154     KVM_CAP_INFO(USER_MEMORY),
155     KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
156     KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS),
157     KVM_CAP_LAST_INFO
158 };
159 
160 static NotifierList kvm_irqchip_change_notifiers =
161     NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers);
162 
163 struct KVMResampleFd {
164     int gsi;
165     EventNotifier *resample_event;
166     QLIST_ENTRY(KVMResampleFd) node;
167 };
168 typedef struct KVMResampleFd KVMResampleFd;
169 
170 /*
171  * Only used with split irqchip where we need to do the resample fd
172  * kick for the kernel from userspace.
173  */
174 static QLIST_HEAD(, KVMResampleFd) kvm_resample_fd_list =
175     QLIST_HEAD_INITIALIZER(kvm_resample_fd_list);
176 
177 #define kvm_slots_lock(kml)      qemu_mutex_lock(&(kml)->slots_lock)
178 #define kvm_slots_unlock(kml)    qemu_mutex_unlock(&(kml)->slots_lock)
179 
180 static inline void kvm_resample_fd_remove(int gsi)
181 {
182     KVMResampleFd *rfd;
183 
184     QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
185         if (rfd->gsi == gsi) {
186             QLIST_REMOVE(rfd, node);
187             g_free(rfd);
188             break;
189         }
190     }
191 }
192 
193 static inline void kvm_resample_fd_insert(int gsi, EventNotifier *event)
194 {
195     KVMResampleFd *rfd = g_new0(KVMResampleFd, 1);
196 
197     rfd->gsi = gsi;
198     rfd->resample_event = event;
199 
200     QLIST_INSERT_HEAD(&kvm_resample_fd_list, rfd, node);
201 }
202 
203 void kvm_resample_fd_notify(int gsi)
204 {
205     KVMResampleFd *rfd;
206 
207     QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
208         if (rfd->gsi == gsi) {
209             event_notifier_set(rfd->resample_event);
210             trace_kvm_resample_fd_notify(gsi);
211             return;
212         }
213     }
214 }
215 
216 int kvm_get_max_memslots(void)
217 {
218     KVMState *s = KVM_STATE(current_accel());
219 
220     return s->nr_slots;
221 }
222 
223 /* Called with KVMMemoryListener.slots_lock held */
224 static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
225 {
226     KVMState *s = kvm_state;
227     int i;
228 
229     for (i = 0; i < s->nr_slots; i++) {
230         if (kml->slots[i].memory_size == 0) {
231             return &kml->slots[i];
232         }
233     }
234 
235     return NULL;
236 }
237 
238 bool kvm_has_free_slot(MachineState *ms)
239 {
240     KVMState *s = KVM_STATE(ms->accelerator);
241     bool result;
242     KVMMemoryListener *kml = &s->memory_listener;
243 
244     kvm_slots_lock(kml);
245     result = !!kvm_get_free_slot(kml);
246     kvm_slots_unlock(kml);
247 
248     return result;
249 }
250 
251 /* Called with KVMMemoryListener.slots_lock held */
252 static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
253 {
254     KVMSlot *slot = kvm_get_free_slot(kml);
255 
256     if (slot) {
257         return slot;
258     }
259 
260     fprintf(stderr, "%s: no free slot available\n", __func__);
261     abort();
262 }
263 
264 static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
265                                          hwaddr start_addr,
266                                          hwaddr size)
267 {
268     KVMState *s = kvm_state;
269     int i;
270 
271     for (i = 0; i < s->nr_slots; i++) {
272         KVMSlot *mem = &kml->slots[i];
273 
274         if (start_addr == mem->start_addr && size == mem->memory_size) {
275             return mem;
276         }
277     }
278 
279     return NULL;
280 }
281 
282 /*
283  * Calculate and align the start address and the size of the section.
284  * Return the size. If the size is 0, the aligned section is empty.
285  */
286 static hwaddr kvm_align_section(MemoryRegionSection *section,
287                                 hwaddr *start)
288 {
289     hwaddr size = int128_get64(section->size);
290     hwaddr delta, aligned;
291 
292     /* kvm works in page size chunks, but the function may be called
293        with sub-page size and unaligned start address. Pad the start
294        address to next and truncate size to previous page boundary. */
295     aligned = ROUND_UP(section->offset_within_address_space,
296                        qemu_real_host_page_size);
297     delta = aligned - section->offset_within_address_space;
298     *start = aligned;
299     if (delta > size) {
300         return 0;
301     }
302 
303     return (size - delta) & qemu_real_host_page_mask;
304 }
305 
306 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
307                                        hwaddr *phys_addr)
308 {
309     KVMMemoryListener *kml = &s->memory_listener;
310     int i, ret = 0;
311 
312     kvm_slots_lock(kml);
313     for (i = 0; i < s->nr_slots; i++) {
314         KVMSlot *mem = &kml->slots[i];
315 
316         if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
317             *phys_addr = mem->start_addr + (ram - mem->ram);
318             ret = 1;
319             break;
320         }
321     }
322     kvm_slots_unlock(kml);
323 
324     return ret;
325 }
326 
327 static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot, bool new)
328 {
329     KVMState *s = kvm_state;
330     struct kvm_userspace_memory_region mem;
331     int ret;
332 
333     mem.slot = slot->slot | (kml->as_id << 16);
334     mem.guest_phys_addr = slot->start_addr;
335     mem.userspace_addr = (unsigned long)slot->ram;
336     mem.flags = slot->flags;
337 
338     if (slot->memory_size && !new && (mem.flags ^ slot->old_flags) & KVM_MEM_READONLY) {
339         /* Set the slot size to 0 before setting the slot to the desired
340          * value. This is needed based on KVM commit 75d61fbc. */
341         mem.memory_size = 0;
342         ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
343         if (ret < 0) {
344             goto err;
345         }
346     }
347     mem.memory_size = slot->memory_size;
348     ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
349     slot->old_flags = mem.flags;
350 err:
351     trace_kvm_set_user_memory(mem.slot, mem.flags, mem.guest_phys_addr,
352                               mem.memory_size, mem.userspace_addr, ret);
353     if (ret < 0) {
354         error_report("%s: KVM_SET_USER_MEMORY_REGION failed, slot=%d,"
355                      " start=0x%" PRIx64 ", size=0x%" PRIx64 ": %s",
356                      __func__, mem.slot, slot->start_addr,
357                      (uint64_t)mem.memory_size, strerror(errno));
358     }
359     return ret;
360 }
361 
362 static int do_kvm_destroy_vcpu(CPUState *cpu)
363 {
364     KVMState *s = kvm_state;
365     long mmap_size;
366     struct KVMParkedVcpu *vcpu = NULL;
367     int ret = 0;
368 
369     DPRINTF("kvm_destroy_vcpu\n");
370 
371     ret = kvm_arch_destroy_vcpu(cpu);
372     if (ret < 0) {
373         goto err;
374     }
375 
376     mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
377     if (mmap_size < 0) {
378         ret = mmap_size;
379         DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
380         goto err;
381     }
382 
383     ret = munmap(cpu->kvm_run, mmap_size);
384     if (ret < 0) {
385         goto err;
386     }
387 
388     vcpu = g_malloc0(sizeof(*vcpu));
389     vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
390     vcpu->kvm_fd = cpu->kvm_fd;
391     QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
392 err:
393     return ret;
394 }
395 
396 void kvm_destroy_vcpu(CPUState *cpu)
397 {
398     if (do_kvm_destroy_vcpu(cpu) < 0) {
399         error_report("kvm_destroy_vcpu failed");
400         exit(EXIT_FAILURE);
401     }
402 }
403 
404 static int kvm_get_vcpu(KVMState *s, unsigned long vcpu_id)
405 {
406     struct KVMParkedVcpu *cpu;
407 
408     QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
409         if (cpu->vcpu_id == vcpu_id) {
410             int kvm_fd;
411 
412             QLIST_REMOVE(cpu, node);
413             kvm_fd = cpu->kvm_fd;
414             g_free(cpu);
415             return kvm_fd;
416         }
417     }
418 
419     return kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)vcpu_id);
420 }
421 
422 int kvm_init_vcpu(CPUState *cpu, Error **errp)
423 {
424     KVMState *s = kvm_state;
425     long mmap_size;
426     int ret;
427 
428     trace_kvm_init_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
429 
430     ret = kvm_get_vcpu(s, kvm_arch_vcpu_id(cpu));
431     if (ret < 0) {
432         error_setg_errno(errp, -ret, "kvm_init_vcpu: kvm_get_vcpu failed (%lu)",
433                          kvm_arch_vcpu_id(cpu));
434         goto err;
435     }
436 
437     cpu->kvm_fd = ret;
438     cpu->kvm_state = s;
439     cpu->vcpu_dirty = true;
440 
441     mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
442     if (mmap_size < 0) {
443         ret = mmap_size;
444         error_setg_errno(errp, -mmap_size,
445                          "kvm_init_vcpu: KVM_GET_VCPU_MMAP_SIZE failed");
446         goto err;
447     }
448 
449     cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
450                         cpu->kvm_fd, 0);
451     if (cpu->kvm_run == MAP_FAILED) {
452         ret = -errno;
453         error_setg_errno(errp, ret,
454                          "kvm_init_vcpu: mmap'ing vcpu state failed (%lu)",
455                          kvm_arch_vcpu_id(cpu));
456         goto err;
457     }
458 
459     if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
460         s->coalesced_mmio_ring =
461             (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
462     }
463 
464     ret = kvm_arch_init_vcpu(cpu);
465     if (ret < 0) {
466         error_setg_errno(errp, -ret,
467                          "kvm_init_vcpu: kvm_arch_init_vcpu failed (%lu)",
468                          kvm_arch_vcpu_id(cpu));
469     }
470 err:
471     return ret;
472 }
473 
474 /*
475  * dirty pages logging control
476  */
477 
478 static int kvm_mem_flags(MemoryRegion *mr)
479 {
480     bool readonly = mr->readonly || memory_region_is_romd(mr);
481     int flags = 0;
482 
483     if (memory_region_get_dirty_log_mask(mr) != 0) {
484         flags |= KVM_MEM_LOG_DIRTY_PAGES;
485     }
486     if (readonly && kvm_readonly_mem_allowed) {
487         flags |= KVM_MEM_READONLY;
488     }
489     return flags;
490 }
491 
492 /* Called with KVMMemoryListener.slots_lock held */
493 static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
494                                  MemoryRegion *mr)
495 {
496     mem->flags = kvm_mem_flags(mr);
497 
498     /* If nothing changed effectively, no need to issue ioctl */
499     if (mem->flags == mem->old_flags) {
500         return 0;
501     }
502 
503     return kvm_set_user_memory_region(kml, mem, false);
504 }
505 
506 static int kvm_section_update_flags(KVMMemoryListener *kml,
507                                     MemoryRegionSection *section)
508 {
509     hwaddr start_addr, size, slot_size;
510     KVMSlot *mem;
511     int ret = 0;
512 
513     size = kvm_align_section(section, &start_addr);
514     if (!size) {
515         return 0;
516     }
517 
518     kvm_slots_lock(kml);
519 
520     while (size && !ret) {
521         slot_size = MIN(kvm_max_slot_size, size);
522         mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
523         if (!mem) {
524             /* We don't have a slot if we want to trap every access. */
525             goto out;
526         }
527 
528         ret = kvm_slot_update_flags(kml, mem, section->mr);
529         start_addr += slot_size;
530         size -= slot_size;
531     }
532 
533 out:
534     kvm_slots_unlock(kml);
535     return ret;
536 }
537 
538 static void kvm_log_start(MemoryListener *listener,
539                           MemoryRegionSection *section,
540                           int old, int new)
541 {
542     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
543     int r;
544 
545     if (old != 0) {
546         return;
547     }
548 
549     r = kvm_section_update_flags(kml, section);
550     if (r < 0) {
551         abort();
552     }
553 }
554 
555 static void kvm_log_stop(MemoryListener *listener,
556                           MemoryRegionSection *section,
557                           int old, int new)
558 {
559     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
560     int r;
561 
562     if (new != 0) {
563         return;
564     }
565 
566     r = kvm_section_update_flags(kml, section);
567     if (r < 0) {
568         abort();
569     }
570 }
571 
572 /* get kvm's dirty pages bitmap and update qemu's */
573 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
574                                          unsigned long *bitmap)
575 {
576     ram_addr_t start = section->offset_within_region +
577                        memory_region_get_ram_addr(section->mr);
578     ram_addr_t pages = int128_get64(section->size) / qemu_real_host_page_size;
579 
580     cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
581     return 0;
582 }
583 
584 #define ALIGN(x, y)  (((x)+(y)-1) & ~((y)-1))
585 
586 /* Allocate the dirty bitmap for a slot  */
587 static void kvm_memslot_init_dirty_bitmap(KVMSlot *mem)
588 {
589     /*
590      * XXX bad kernel interface alert
591      * For dirty bitmap, kernel allocates array of size aligned to
592      * bits-per-long.  But for case when the kernel is 64bits and
593      * the userspace is 32bits, userspace can't align to the same
594      * bits-per-long, since sizeof(long) is different between kernel
595      * and user space.  This way, userspace will provide buffer which
596      * may be 4 bytes less than the kernel will use, resulting in
597      * userspace memory corruption (which is not detectable by valgrind
598      * too, in most cases).
599      * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
600      * a hope that sizeof(long) won't become >8 any time soon.
601      */
602     hwaddr bitmap_size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
603                                         /*HOST_LONG_BITS*/ 64) / 8;
604     mem->dirty_bmap = g_malloc0(bitmap_size);
605 }
606 
607 /**
608  * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
609  *
610  * This function will first try to fetch dirty bitmap from the kernel,
611  * and then updates qemu's dirty bitmap.
612  *
613  * NOTE: caller must be with kml->slots_lock held.
614  *
615  * @kml: the KVM memory listener object
616  * @section: the memory section to sync the dirty bitmap with
617  */
618 static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
619                                           MemoryRegionSection *section)
620 {
621     KVMState *s = kvm_state;
622     struct kvm_dirty_log d = {};
623     KVMSlot *mem;
624     hwaddr start_addr, size;
625     hwaddr slot_size, slot_offset = 0;
626     int ret = 0;
627 
628     size = kvm_align_section(section, &start_addr);
629     while (size) {
630         MemoryRegionSection subsection = *section;
631 
632         slot_size = MIN(kvm_max_slot_size, size);
633         mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
634         if (!mem) {
635             /* We don't have a slot if we want to trap every access. */
636             goto out;
637         }
638 
639         if (!mem->dirty_bmap) {
640             /* Allocate on the first log_sync, once and for all */
641             kvm_memslot_init_dirty_bitmap(mem);
642         }
643 
644         d.dirty_bitmap = mem->dirty_bmap;
645         d.slot = mem->slot | (kml->as_id << 16);
646         ret = kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d);
647         if (ret == -ENOENT) {
648             /* kernel does not have dirty bitmap in this slot */
649             ret = 0;
650         } else if (ret < 0) {
651             error_report("ioctl KVM_GET_DIRTY_LOG failed: %d", errno);
652             goto out;
653         } else {
654             subsection.offset_within_region += slot_offset;
655             subsection.size = int128_make64(slot_size);
656             kvm_get_dirty_pages_log_range(&subsection, d.dirty_bitmap);
657         }
658 
659         slot_offset += slot_size;
660         start_addr += slot_size;
661         size -= slot_size;
662     }
663 out:
664     return ret;
665 }
666 
667 /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
668 #define KVM_CLEAR_LOG_SHIFT  6
669 #define KVM_CLEAR_LOG_ALIGN  (qemu_real_host_page_size << KVM_CLEAR_LOG_SHIFT)
670 #define KVM_CLEAR_LOG_MASK   (-KVM_CLEAR_LOG_ALIGN)
671 
672 static int kvm_log_clear_one_slot(KVMSlot *mem, int as_id, uint64_t start,
673                                   uint64_t size)
674 {
675     KVMState *s = kvm_state;
676     uint64_t end, bmap_start, start_delta, bmap_npages;
677     struct kvm_clear_dirty_log d;
678     unsigned long *bmap_clear = NULL, psize = qemu_real_host_page_size;
679     int ret;
680 
681     /*
682      * We need to extend either the start or the size or both to
683      * satisfy the KVM interface requirement.  Firstly, do the start
684      * page alignment on 64 host pages
685      */
686     bmap_start = start & KVM_CLEAR_LOG_MASK;
687     start_delta = start - bmap_start;
688     bmap_start /= psize;
689 
690     /*
691      * The kernel interface has restriction on the size too, that either:
692      *
693      * (1) the size is 64 host pages aligned (just like the start), or
694      * (2) the size fills up until the end of the KVM memslot.
695      */
696     bmap_npages = DIV_ROUND_UP(size + start_delta, KVM_CLEAR_LOG_ALIGN)
697         << KVM_CLEAR_LOG_SHIFT;
698     end = mem->memory_size / psize;
699     if (bmap_npages > end - bmap_start) {
700         bmap_npages = end - bmap_start;
701     }
702     start_delta /= psize;
703 
704     /*
705      * Prepare the bitmap to clear dirty bits.  Here we must guarantee
706      * that we won't clear any unknown dirty bits otherwise we might
707      * accidentally clear some set bits which are not yet synced from
708      * the kernel into QEMU's bitmap, then we'll lose track of the
709      * guest modifications upon those pages (which can directly lead
710      * to guest data loss or panic after migration).
711      *
712      * Layout of the KVMSlot.dirty_bmap:
713      *
714      *                   |<-------- bmap_npages -----------..>|
715      *                                                     [1]
716      *                     start_delta         size
717      *  |----------------|-------------|------------------|------------|
718      *  ^                ^             ^                               ^
719      *  |                |             |                               |
720      * start          bmap_start     (start)                         end
721      * of memslot                                             of memslot
722      *
723      * [1] bmap_npages can be aligned to either 64 pages or the end of slot
724      */
725 
726     assert(bmap_start % BITS_PER_LONG == 0);
727     /* We should never do log_clear before log_sync */
728     assert(mem->dirty_bmap);
729     if (start_delta || bmap_npages - size / psize) {
730         /* Slow path - we need to manipulate a temp bitmap */
731         bmap_clear = bitmap_new(bmap_npages);
732         bitmap_copy_with_src_offset(bmap_clear, mem->dirty_bmap,
733                                     bmap_start, start_delta + size / psize);
734         /*
735          * We need to fill the holes at start because that was not
736          * specified by the caller and we extended the bitmap only for
737          * 64 pages alignment
738          */
739         bitmap_clear(bmap_clear, 0, start_delta);
740         d.dirty_bitmap = bmap_clear;
741     } else {
742         /*
743          * Fast path - both start and size align well with BITS_PER_LONG
744          * (or the end of memory slot)
745          */
746         d.dirty_bitmap = mem->dirty_bmap + BIT_WORD(bmap_start);
747     }
748 
749     d.first_page = bmap_start;
750     /* It should never overflow.  If it happens, say something */
751     assert(bmap_npages <= UINT32_MAX);
752     d.num_pages = bmap_npages;
753     d.slot = mem->slot | (as_id << 16);
754 
755     ret = kvm_vm_ioctl(s, KVM_CLEAR_DIRTY_LOG, &d);
756     if (ret < 0 && ret != -ENOENT) {
757         error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
758                      "start=0x%"PRIx64", size=0x%"PRIx32", errno=%d",
759                      __func__, d.slot, (uint64_t)d.first_page,
760                      (uint32_t)d.num_pages, ret);
761     } else {
762         ret = 0;
763         trace_kvm_clear_dirty_log(d.slot, d.first_page, d.num_pages);
764     }
765 
766     /*
767      * After we have updated the remote dirty bitmap, we update the
768      * cached bitmap as well for the memslot, then if another user
769      * clears the same region we know we shouldn't clear it again on
770      * the remote otherwise it's data loss as well.
771      */
772     bitmap_clear(mem->dirty_bmap, bmap_start + start_delta,
773                  size / psize);
774     /* This handles the NULL case well */
775     g_free(bmap_clear);
776     return ret;
777 }
778 
779 
780 /**
781  * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
782  *
783  * NOTE: this will be a no-op if we haven't enabled manual dirty log
784  * protection in the host kernel because in that case this operation
785  * will be done within log_sync().
786  *
787  * @kml:     the kvm memory listener
788  * @section: the memory range to clear dirty bitmap
789  */
790 static int kvm_physical_log_clear(KVMMemoryListener *kml,
791                                   MemoryRegionSection *section)
792 {
793     KVMState *s = kvm_state;
794     uint64_t start, size, offset, count;
795     KVMSlot *mem;
796     int ret = 0, i;
797 
798     if (!s->manual_dirty_log_protect) {
799         /* No need to do explicit clear */
800         return ret;
801     }
802 
803     start = section->offset_within_address_space;
804     size = int128_get64(section->size);
805 
806     if (!size) {
807         /* Nothing more we can do... */
808         return ret;
809     }
810 
811     kvm_slots_lock(kml);
812 
813     for (i = 0; i < s->nr_slots; i++) {
814         mem = &kml->slots[i];
815         /* Discard slots that are empty or do not overlap the section */
816         if (!mem->memory_size ||
817             mem->start_addr > start + size - 1 ||
818             start > mem->start_addr + mem->memory_size - 1) {
819             continue;
820         }
821 
822         if (start >= mem->start_addr) {
823             /* The slot starts before section or is aligned to it.  */
824             offset = start - mem->start_addr;
825             count = MIN(mem->memory_size - offset, size);
826         } else {
827             /* The slot starts after section.  */
828             offset = 0;
829             count = MIN(mem->memory_size, size - (mem->start_addr - start));
830         }
831         ret = kvm_log_clear_one_slot(mem, kml->as_id, offset, count);
832         if (ret < 0) {
833             break;
834         }
835     }
836 
837     kvm_slots_unlock(kml);
838 
839     return ret;
840 }
841 
842 static void kvm_coalesce_mmio_region(MemoryListener *listener,
843                                      MemoryRegionSection *secion,
844                                      hwaddr start, hwaddr size)
845 {
846     KVMState *s = kvm_state;
847 
848     if (s->coalesced_mmio) {
849         struct kvm_coalesced_mmio_zone zone;
850 
851         zone.addr = start;
852         zone.size = size;
853         zone.pad = 0;
854 
855         (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
856     }
857 }
858 
859 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
860                                        MemoryRegionSection *secion,
861                                        hwaddr start, hwaddr size)
862 {
863     KVMState *s = kvm_state;
864 
865     if (s->coalesced_mmio) {
866         struct kvm_coalesced_mmio_zone zone;
867 
868         zone.addr = start;
869         zone.size = size;
870         zone.pad = 0;
871 
872         (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
873     }
874 }
875 
876 static void kvm_coalesce_pio_add(MemoryListener *listener,
877                                 MemoryRegionSection *section,
878                                 hwaddr start, hwaddr size)
879 {
880     KVMState *s = kvm_state;
881 
882     if (s->coalesced_pio) {
883         struct kvm_coalesced_mmio_zone zone;
884 
885         zone.addr = start;
886         zone.size = size;
887         zone.pio = 1;
888 
889         (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
890     }
891 }
892 
893 static void kvm_coalesce_pio_del(MemoryListener *listener,
894                                 MemoryRegionSection *section,
895                                 hwaddr start, hwaddr size)
896 {
897     KVMState *s = kvm_state;
898 
899     if (s->coalesced_pio) {
900         struct kvm_coalesced_mmio_zone zone;
901 
902         zone.addr = start;
903         zone.size = size;
904         zone.pio = 1;
905 
906         (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
907      }
908 }
909 
910 static MemoryListener kvm_coalesced_pio_listener = {
911     .coalesced_io_add = kvm_coalesce_pio_add,
912     .coalesced_io_del = kvm_coalesce_pio_del,
913 };
914 
915 int kvm_check_extension(KVMState *s, unsigned int extension)
916 {
917     int ret;
918 
919     ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
920     if (ret < 0) {
921         ret = 0;
922     }
923 
924     return ret;
925 }
926 
927 int kvm_vm_check_extension(KVMState *s, unsigned int extension)
928 {
929     int ret;
930 
931     ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
932     if (ret < 0) {
933         /* VM wide version not implemented, use global one instead */
934         ret = kvm_check_extension(s, extension);
935     }
936 
937     return ret;
938 }
939 
940 typedef struct HWPoisonPage {
941     ram_addr_t ram_addr;
942     QLIST_ENTRY(HWPoisonPage) list;
943 } HWPoisonPage;
944 
945 static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
946     QLIST_HEAD_INITIALIZER(hwpoison_page_list);
947 
948 static void kvm_unpoison_all(void *param)
949 {
950     HWPoisonPage *page, *next_page;
951 
952     QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
953         QLIST_REMOVE(page, list);
954         qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
955         g_free(page);
956     }
957 }
958 
959 void kvm_hwpoison_page_add(ram_addr_t ram_addr)
960 {
961     HWPoisonPage *page;
962 
963     QLIST_FOREACH(page, &hwpoison_page_list, list) {
964         if (page->ram_addr == ram_addr) {
965             return;
966         }
967     }
968     page = g_new(HWPoisonPage, 1);
969     page->ram_addr = ram_addr;
970     QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
971 }
972 
973 static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
974 {
975 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
976     /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
977      * endianness, but the memory core hands them in target endianness.
978      * For example, PPC is always treated as big-endian even if running
979      * on KVM and on PPC64LE.  Correct here.
980      */
981     switch (size) {
982     case 2:
983         val = bswap16(val);
984         break;
985     case 4:
986         val = bswap32(val);
987         break;
988     }
989 #endif
990     return val;
991 }
992 
993 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
994                                   bool assign, uint32_t size, bool datamatch)
995 {
996     int ret;
997     struct kvm_ioeventfd iofd = {
998         .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
999         .addr = addr,
1000         .len = size,
1001         .flags = 0,
1002         .fd = fd,
1003     };
1004 
1005     trace_kvm_set_ioeventfd_mmio(fd, (uint64_t)addr, val, assign, size,
1006                                  datamatch);
1007     if (!kvm_enabled()) {
1008         return -ENOSYS;
1009     }
1010 
1011     if (datamatch) {
1012         iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
1013     }
1014     if (!assign) {
1015         iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1016     }
1017 
1018     ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
1019 
1020     if (ret < 0) {
1021         return -errno;
1022     }
1023 
1024     return 0;
1025 }
1026 
1027 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
1028                                  bool assign, uint32_t size, bool datamatch)
1029 {
1030     struct kvm_ioeventfd kick = {
1031         .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
1032         .addr = addr,
1033         .flags = KVM_IOEVENTFD_FLAG_PIO,
1034         .len = size,
1035         .fd = fd,
1036     };
1037     int r;
1038     trace_kvm_set_ioeventfd_pio(fd, addr, val, assign, size, datamatch);
1039     if (!kvm_enabled()) {
1040         return -ENOSYS;
1041     }
1042     if (datamatch) {
1043         kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
1044     }
1045     if (!assign) {
1046         kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1047     }
1048     r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
1049     if (r < 0) {
1050         return r;
1051     }
1052     return 0;
1053 }
1054 
1055 
1056 static int kvm_check_many_ioeventfds(void)
1057 {
1058     /* Userspace can use ioeventfd for io notification.  This requires a host
1059      * that supports eventfd(2) and an I/O thread; since eventfd does not
1060      * support SIGIO it cannot interrupt the vcpu.
1061      *
1062      * Older kernels have a 6 device limit on the KVM io bus.  Find out so we
1063      * can avoid creating too many ioeventfds.
1064      */
1065 #if defined(CONFIG_EVENTFD)
1066     int ioeventfds[7];
1067     int i, ret = 0;
1068     for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
1069         ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
1070         if (ioeventfds[i] < 0) {
1071             break;
1072         }
1073         ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
1074         if (ret < 0) {
1075             close(ioeventfds[i]);
1076             break;
1077         }
1078     }
1079 
1080     /* Decide whether many devices are supported or not */
1081     ret = i == ARRAY_SIZE(ioeventfds);
1082 
1083     while (i-- > 0) {
1084         kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
1085         close(ioeventfds[i]);
1086     }
1087     return ret;
1088 #else
1089     return 0;
1090 #endif
1091 }
1092 
1093 static const KVMCapabilityInfo *
1094 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
1095 {
1096     while (list->name) {
1097         if (!kvm_check_extension(s, list->value)) {
1098             return list;
1099         }
1100         list++;
1101     }
1102     return NULL;
1103 }
1104 
1105 void kvm_set_max_memslot_size(hwaddr max_slot_size)
1106 {
1107     g_assert(
1108         ROUND_UP(max_slot_size, qemu_real_host_page_size) == max_slot_size
1109     );
1110     kvm_max_slot_size = max_slot_size;
1111 }
1112 
1113 static void kvm_set_phys_mem(KVMMemoryListener *kml,
1114                              MemoryRegionSection *section, bool add)
1115 {
1116     KVMSlot *mem;
1117     int err;
1118     MemoryRegion *mr = section->mr;
1119     bool writeable = !mr->readonly && !mr->rom_device;
1120     hwaddr start_addr, size, slot_size;
1121     void *ram;
1122 
1123     if (!memory_region_is_ram(mr)) {
1124         if (writeable || !kvm_readonly_mem_allowed) {
1125             return;
1126         } else if (!mr->romd_mode) {
1127             /* If the memory device is not in romd_mode, then we actually want
1128              * to remove the kvm memory slot so all accesses will trap. */
1129             add = false;
1130         }
1131     }
1132 
1133     size = kvm_align_section(section, &start_addr);
1134     if (!size) {
1135         return;
1136     }
1137 
1138     /* use aligned delta to align the ram address */
1139     ram = memory_region_get_ram_ptr(mr) + section->offset_within_region +
1140           (start_addr - section->offset_within_address_space);
1141 
1142     kvm_slots_lock(kml);
1143 
1144     if (!add) {
1145         do {
1146             slot_size = MIN(kvm_max_slot_size, size);
1147             mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
1148             if (!mem) {
1149                 goto out;
1150             }
1151             if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1152                 kvm_physical_sync_dirty_bitmap(kml, section);
1153             }
1154 
1155             /* unregister the slot */
1156             g_free(mem->dirty_bmap);
1157             mem->dirty_bmap = NULL;
1158             mem->memory_size = 0;
1159             mem->flags = 0;
1160             err = kvm_set_user_memory_region(kml, mem, false);
1161             if (err) {
1162                 fprintf(stderr, "%s: error unregistering slot: %s\n",
1163                         __func__, strerror(-err));
1164                 abort();
1165             }
1166             start_addr += slot_size;
1167             size -= slot_size;
1168         } while (size);
1169         goto out;
1170     }
1171 
1172     /* register the new slot */
1173     do {
1174         slot_size = MIN(kvm_max_slot_size, size);
1175         mem = kvm_alloc_slot(kml);
1176         mem->memory_size = slot_size;
1177         mem->start_addr = start_addr;
1178         mem->ram = ram;
1179         mem->flags = kvm_mem_flags(mr);
1180 
1181         if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1182             /*
1183              * Reallocate the bmap; it means it doesn't disappear in
1184              * middle of a migrate.
1185              */
1186             kvm_memslot_init_dirty_bitmap(mem);
1187         }
1188         err = kvm_set_user_memory_region(kml, mem, true);
1189         if (err) {
1190             fprintf(stderr, "%s: error registering slot: %s\n", __func__,
1191                     strerror(-err));
1192             abort();
1193         }
1194         start_addr += slot_size;
1195         ram += slot_size;
1196         size -= slot_size;
1197     } while (size);
1198 
1199 out:
1200     kvm_slots_unlock(kml);
1201 }
1202 
1203 static void kvm_region_add(MemoryListener *listener,
1204                            MemoryRegionSection *section)
1205 {
1206     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1207 
1208     memory_region_ref(section->mr);
1209     kvm_set_phys_mem(kml, section, true);
1210 }
1211 
1212 static void kvm_region_del(MemoryListener *listener,
1213                            MemoryRegionSection *section)
1214 {
1215     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1216 
1217     kvm_set_phys_mem(kml, section, false);
1218     memory_region_unref(section->mr);
1219 }
1220 
1221 static void kvm_log_sync(MemoryListener *listener,
1222                          MemoryRegionSection *section)
1223 {
1224     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1225     int r;
1226 
1227     kvm_slots_lock(kml);
1228     r = kvm_physical_sync_dirty_bitmap(kml, section);
1229     kvm_slots_unlock(kml);
1230     if (r < 0) {
1231         abort();
1232     }
1233 }
1234 
1235 static void kvm_log_clear(MemoryListener *listener,
1236                           MemoryRegionSection *section)
1237 {
1238     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1239     int r;
1240 
1241     r = kvm_physical_log_clear(kml, section);
1242     if (r < 0) {
1243         error_report_once("%s: kvm log clear failed: mr=%s "
1244                           "offset=%"HWADDR_PRIx" size=%"PRIx64, __func__,
1245                           section->mr->name, section->offset_within_region,
1246                           int128_get64(section->size));
1247         abort();
1248     }
1249 }
1250 
1251 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
1252                                   MemoryRegionSection *section,
1253                                   bool match_data, uint64_t data,
1254                                   EventNotifier *e)
1255 {
1256     int fd = event_notifier_get_fd(e);
1257     int r;
1258 
1259     r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
1260                                data, true, int128_get64(section->size),
1261                                match_data);
1262     if (r < 0) {
1263         fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1264                 __func__, strerror(-r), -r);
1265         abort();
1266     }
1267 }
1268 
1269 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
1270                                   MemoryRegionSection *section,
1271                                   bool match_data, uint64_t data,
1272                                   EventNotifier *e)
1273 {
1274     int fd = event_notifier_get_fd(e);
1275     int r;
1276 
1277     r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
1278                                data, false, int128_get64(section->size),
1279                                match_data);
1280     if (r < 0) {
1281         fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1282                 __func__, strerror(-r), -r);
1283         abort();
1284     }
1285 }
1286 
1287 static void kvm_io_ioeventfd_add(MemoryListener *listener,
1288                                  MemoryRegionSection *section,
1289                                  bool match_data, uint64_t data,
1290                                  EventNotifier *e)
1291 {
1292     int fd = event_notifier_get_fd(e);
1293     int r;
1294 
1295     r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
1296                               data, true, int128_get64(section->size),
1297                               match_data);
1298     if (r < 0) {
1299         fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1300                 __func__, strerror(-r), -r);
1301         abort();
1302     }
1303 }
1304 
1305 static void kvm_io_ioeventfd_del(MemoryListener *listener,
1306                                  MemoryRegionSection *section,
1307                                  bool match_data, uint64_t data,
1308                                  EventNotifier *e)
1309 
1310 {
1311     int fd = event_notifier_get_fd(e);
1312     int r;
1313 
1314     r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
1315                               data, false, int128_get64(section->size),
1316                               match_data);
1317     if (r < 0) {
1318         fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1319                 __func__, strerror(-r), -r);
1320         abort();
1321     }
1322 }
1323 
1324 void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
1325                                   AddressSpace *as, int as_id)
1326 {
1327     int i;
1328 
1329     qemu_mutex_init(&kml->slots_lock);
1330     kml->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
1331     kml->as_id = as_id;
1332 
1333     for (i = 0; i < s->nr_slots; i++) {
1334         kml->slots[i].slot = i;
1335     }
1336 
1337     kml->listener.region_add = kvm_region_add;
1338     kml->listener.region_del = kvm_region_del;
1339     kml->listener.log_start = kvm_log_start;
1340     kml->listener.log_stop = kvm_log_stop;
1341     kml->listener.log_sync = kvm_log_sync;
1342     kml->listener.log_clear = kvm_log_clear;
1343     kml->listener.priority = 10;
1344 
1345     memory_listener_register(&kml->listener, as);
1346 
1347     for (i = 0; i < s->nr_as; ++i) {
1348         if (!s->as[i].as) {
1349             s->as[i].as = as;
1350             s->as[i].ml = kml;
1351             break;
1352         }
1353     }
1354 }
1355 
1356 static MemoryListener kvm_io_listener = {
1357     .eventfd_add = kvm_io_ioeventfd_add,
1358     .eventfd_del = kvm_io_ioeventfd_del,
1359     .priority = 10,
1360 };
1361 
1362 int kvm_set_irq(KVMState *s, int irq, int level)
1363 {
1364     struct kvm_irq_level event;
1365     int ret;
1366 
1367     assert(kvm_async_interrupts_enabled());
1368 
1369     event.level = level;
1370     event.irq = irq;
1371     ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
1372     if (ret < 0) {
1373         perror("kvm_set_irq");
1374         abort();
1375     }
1376 
1377     return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
1378 }
1379 
1380 #ifdef KVM_CAP_IRQ_ROUTING
1381 typedef struct KVMMSIRoute {
1382     struct kvm_irq_routing_entry kroute;
1383     QTAILQ_ENTRY(KVMMSIRoute) entry;
1384 } KVMMSIRoute;
1385 
1386 static void set_gsi(KVMState *s, unsigned int gsi)
1387 {
1388     set_bit(gsi, s->used_gsi_bitmap);
1389 }
1390 
1391 static void clear_gsi(KVMState *s, unsigned int gsi)
1392 {
1393     clear_bit(gsi, s->used_gsi_bitmap);
1394 }
1395 
1396 void kvm_init_irq_routing(KVMState *s)
1397 {
1398     int gsi_count, i;
1399 
1400     gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
1401     if (gsi_count > 0) {
1402         /* Round up so we can search ints using ffs */
1403         s->used_gsi_bitmap = bitmap_new(gsi_count);
1404         s->gsi_count = gsi_count;
1405     }
1406 
1407     s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
1408     s->nr_allocated_irq_routes = 0;
1409 
1410     if (!kvm_direct_msi_allowed) {
1411         for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
1412             QTAILQ_INIT(&s->msi_hashtab[i]);
1413         }
1414     }
1415 
1416     kvm_arch_init_irq_routing(s);
1417 }
1418 
1419 void kvm_irqchip_commit_routes(KVMState *s)
1420 {
1421     int ret;
1422 
1423     if (kvm_gsi_direct_mapping()) {
1424         return;
1425     }
1426 
1427     if (!kvm_gsi_routing_enabled()) {
1428         return;
1429     }
1430 
1431     s->irq_routes->flags = 0;
1432     trace_kvm_irqchip_commit_routes();
1433     ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1434     assert(ret == 0);
1435 }
1436 
1437 static void kvm_add_routing_entry(KVMState *s,
1438                                   struct kvm_irq_routing_entry *entry)
1439 {
1440     struct kvm_irq_routing_entry *new;
1441     int n, size;
1442 
1443     if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1444         n = s->nr_allocated_irq_routes * 2;
1445         if (n < 64) {
1446             n = 64;
1447         }
1448         size = sizeof(struct kvm_irq_routing);
1449         size += n * sizeof(*new);
1450         s->irq_routes = g_realloc(s->irq_routes, size);
1451         s->nr_allocated_irq_routes = n;
1452     }
1453     n = s->irq_routes->nr++;
1454     new = &s->irq_routes->entries[n];
1455 
1456     *new = *entry;
1457 
1458     set_gsi(s, entry->gsi);
1459 }
1460 
1461 static int kvm_update_routing_entry(KVMState *s,
1462                                     struct kvm_irq_routing_entry *new_entry)
1463 {
1464     struct kvm_irq_routing_entry *entry;
1465     int n;
1466 
1467     for (n = 0; n < s->irq_routes->nr; n++) {
1468         entry = &s->irq_routes->entries[n];
1469         if (entry->gsi != new_entry->gsi) {
1470             continue;
1471         }
1472 
1473         if(!memcmp(entry, new_entry, sizeof *entry)) {
1474             return 0;
1475         }
1476 
1477         *entry = *new_entry;
1478 
1479         return 0;
1480     }
1481 
1482     return -ESRCH;
1483 }
1484 
1485 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1486 {
1487     struct kvm_irq_routing_entry e = {};
1488 
1489     assert(pin < s->gsi_count);
1490 
1491     e.gsi = irq;
1492     e.type = KVM_IRQ_ROUTING_IRQCHIP;
1493     e.flags = 0;
1494     e.u.irqchip.irqchip = irqchip;
1495     e.u.irqchip.pin = pin;
1496     kvm_add_routing_entry(s, &e);
1497 }
1498 
1499 void kvm_irqchip_release_virq(KVMState *s, int virq)
1500 {
1501     struct kvm_irq_routing_entry *e;
1502     int i;
1503 
1504     if (kvm_gsi_direct_mapping()) {
1505         return;
1506     }
1507 
1508     for (i = 0; i < s->irq_routes->nr; i++) {
1509         e = &s->irq_routes->entries[i];
1510         if (e->gsi == virq) {
1511             s->irq_routes->nr--;
1512             *e = s->irq_routes->entries[s->irq_routes->nr];
1513         }
1514     }
1515     clear_gsi(s, virq);
1516     kvm_arch_release_virq_post(virq);
1517     trace_kvm_irqchip_release_virq(virq);
1518 }
1519 
1520 void kvm_irqchip_add_change_notifier(Notifier *n)
1521 {
1522     notifier_list_add(&kvm_irqchip_change_notifiers, n);
1523 }
1524 
1525 void kvm_irqchip_remove_change_notifier(Notifier *n)
1526 {
1527     notifier_remove(n);
1528 }
1529 
1530 void kvm_irqchip_change_notify(void)
1531 {
1532     notifier_list_notify(&kvm_irqchip_change_notifiers, NULL);
1533 }
1534 
1535 static unsigned int kvm_hash_msi(uint32_t data)
1536 {
1537     /* This is optimized for IA32 MSI layout. However, no other arch shall
1538      * repeat the mistake of not providing a direct MSI injection API. */
1539     return data & 0xff;
1540 }
1541 
1542 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1543 {
1544     KVMMSIRoute *route, *next;
1545     unsigned int hash;
1546 
1547     for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1548         QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1549             kvm_irqchip_release_virq(s, route->kroute.gsi);
1550             QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1551             g_free(route);
1552         }
1553     }
1554 }
1555 
1556 static int kvm_irqchip_get_virq(KVMState *s)
1557 {
1558     int next_virq;
1559 
1560     /*
1561      * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1562      * GSI numbers are more than the number of IRQ route. Allocating a GSI
1563      * number can succeed even though a new route entry cannot be added.
1564      * When this happens, flush dynamic MSI entries to free IRQ route entries.
1565      */
1566     if (!kvm_direct_msi_allowed && s->irq_routes->nr == s->gsi_count) {
1567         kvm_flush_dynamic_msi_routes(s);
1568     }
1569 
1570     /* Return the lowest unused GSI in the bitmap */
1571     next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
1572     if (next_virq >= s->gsi_count) {
1573         return -ENOSPC;
1574     } else {
1575         return next_virq;
1576     }
1577 }
1578 
1579 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1580 {
1581     unsigned int hash = kvm_hash_msi(msg.data);
1582     KVMMSIRoute *route;
1583 
1584     QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1585         if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1586             route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1587             route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1588             return route;
1589         }
1590     }
1591     return NULL;
1592 }
1593 
1594 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1595 {
1596     struct kvm_msi msi;
1597     KVMMSIRoute *route;
1598 
1599     if (kvm_direct_msi_allowed) {
1600         msi.address_lo = (uint32_t)msg.address;
1601         msi.address_hi = msg.address >> 32;
1602         msi.data = le32_to_cpu(msg.data);
1603         msi.flags = 0;
1604         memset(msi.pad, 0, sizeof(msi.pad));
1605 
1606         return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1607     }
1608 
1609     route = kvm_lookup_msi_route(s, msg);
1610     if (!route) {
1611         int virq;
1612 
1613         virq = kvm_irqchip_get_virq(s);
1614         if (virq < 0) {
1615             return virq;
1616         }
1617 
1618         route = g_malloc0(sizeof(KVMMSIRoute));
1619         route->kroute.gsi = virq;
1620         route->kroute.type = KVM_IRQ_ROUTING_MSI;
1621         route->kroute.flags = 0;
1622         route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1623         route->kroute.u.msi.address_hi = msg.address >> 32;
1624         route->kroute.u.msi.data = le32_to_cpu(msg.data);
1625 
1626         kvm_add_routing_entry(s, &route->kroute);
1627         kvm_irqchip_commit_routes(s);
1628 
1629         QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1630                            entry);
1631     }
1632 
1633     assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1634 
1635     return kvm_set_irq(s, route->kroute.gsi, 1);
1636 }
1637 
1638 int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
1639 {
1640     struct kvm_irq_routing_entry kroute = {};
1641     int virq;
1642     MSIMessage msg = {0, 0};
1643 
1644     if (pci_available && dev) {
1645         msg = pci_get_msi_message(dev, vector);
1646     }
1647 
1648     if (kvm_gsi_direct_mapping()) {
1649         return kvm_arch_msi_data_to_gsi(msg.data);
1650     }
1651 
1652     if (!kvm_gsi_routing_enabled()) {
1653         return -ENOSYS;
1654     }
1655 
1656     virq = kvm_irqchip_get_virq(s);
1657     if (virq < 0) {
1658         return virq;
1659     }
1660 
1661     kroute.gsi = virq;
1662     kroute.type = KVM_IRQ_ROUTING_MSI;
1663     kroute.flags = 0;
1664     kroute.u.msi.address_lo = (uint32_t)msg.address;
1665     kroute.u.msi.address_hi = msg.address >> 32;
1666     kroute.u.msi.data = le32_to_cpu(msg.data);
1667     if (pci_available && kvm_msi_devid_required()) {
1668         kroute.flags = KVM_MSI_VALID_DEVID;
1669         kroute.u.msi.devid = pci_requester_id(dev);
1670     }
1671     if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1672         kvm_irqchip_release_virq(s, virq);
1673         return -EINVAL;
1674     }
1675 
1676     trace_kvm_irqchip_add_msi_route(dev ? dev->name : (char *)"N/A",
1677                                     vector, virq);
1678 
1679     kvm_add_routing_entry(s, &kroute);
1680     kvm_arch_add_msi_route_post(&kroute, vector, dev);
1681     kvm_irqchip_commit_routes(s);
1682 
1683     return virq;
1684 }
1685 
1686 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
1687                                  PCIDevice *dev)
1688 {
1689     struct kvm_irq_routing_entry kroute = {};
1690 
1691     if (kvm_gsi_direct_mapping()) {
1692         return 0;
1693     }
1694 
1695     if (!kvm_irqchip_in_kernel()) {
1696         return -ENOSYS;
1697     }
1698 
1699     kroute.gsi = virq;
1700     kroute.type = KVM_IRQ_ROUTING_MSI;
1701     kroute.flags = 0;
1702     kroute.u.msi.address_lo = (uint32_t)msg.address;
1703     kroute.u.msi.address_hi = msg.address >> 32;
1704     kroute.u.msi.data = le32_to_cpu(msg.data);
1705     if (pci_available && kvm_msi_devid_required()) {
1706         kroute.flags = KVM_MSI_VALID_DEVID;
1707         kroute.u.msi.devid = pci_requester_id(dev);
1708     }
1709     if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1710         return -EINVAL;
1711     }
1712 
1713     trace_kvm_irqchip_update_msi_route(virq);
1714 
1715     return kvm_update_routing_entry(s, &kroute);
1716 }
1717 
1718 static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
1719                                     EventNotifier *resample, int virq,
1720                                     bool assign)
1721 {
1722     int fd = event_notifier_get_fd(event);
1723     int rfd = resample ? event_notifier_get_fd(resample) : -1;
1724 
1725     struct kvm_irqfd irqfd = {
1726         .fd = fd,
1727         .gsi = virq,
1728         .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1729     };
1730 
1731     if (rfd != -1) {
1732         assert(assign);
1733         if (kvm_irqchip_is_split()) {
1734             /*
1735              * When the slow irqchip (e.g. IOAPIC) is in the
1736              * userspace, KVM kernel resamplefd will not work because
1737              * the EOI of the interrupt will be delivered to userspace
1738              * instead, so the KVM kernel resamplefd kick will be
1739              * skipped.  The userspace here mimics what the kernel
1740              * provides with resamplefd, remember the resamplefd and
1741              * kick it when we receive EOI of this IRQ.
1742              *
1743              * This is hackery because IOAPIC is mostly bypassed
1744              * (except EOI broadcasts) when irqfd is used.  However
1745              * this can bring much performance back for split irqchip
1746              * with INTx IRQs (for VFIO, this gives 93% perf of the
1747              * full fast path, which is 46% perf boost comparing to
1748              * the INTx slow path).
1749              */
1750             kvm_resample_fd_insert(virq, resample);
1751         } else {
1752             irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1753             irqfd.resamplefd = rfd;
1754         }
1755     } else if (!assign) {
1756         if (kvm_irqchip_is_split()) {
1757             kvm_resample_fd_remove(virq);
1758         }
1759     }
1760 
1761     if (!kvm_irqfds_enabled()) {
1762         return -ENOSYS;
1763     }
1764 
1765     return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1766 }
1767 
1768 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1769 {
1770     struct kvm_irq_routing_entry kroute = {};
1771     int virq;
1772 
1773     if (!kvm_gsi_routing_enabled()) {
1774         return -ENOSYS;
1775     }
1776 
1777     virq = kvm_irqchip_get_virq(s);
1778     if (virq < 0) {
1779         return virq;
1780     }
1781 
1782     kroute.gsi = virq;
1783     kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1784     kroute.flags = 0;
1785     kroute.u.adapter.summary_addr = adapter->summary_addr;
1786     kroute.u.adapter.ind_addr = adapter->ind_addr;
1787     kroute.u.adapter.summary_offset = adapter->summary_offset;
1788     kroute.u.adapter.ind_offset = adapter->ind_offset;
1789     kroute.u.adapter.adapter_id = adapter->adapter_id;
1790 
1791     kvm_add_routing_entry(s, &kroute);
1792 
1793     return virq;
1794 }
1795 
1796 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1797 {
1798     struct kvm_irq_routing_entry kroute = {};
1799     int virq;
1800 
1801     if (!kvm_gsi_routing_enabled()) {
1802         return -ENOSYS;
1803     }
1804     if (!kvm_check_extension(s, KVM_CAP_HYPERV_SYNIC)) {
1805         return -ENOSYS;
1806     }
1807     virq = kvm_irqchip_get_virq(s);
1808     if (virq < 0) {
1809         return virq;
1810     }
1811 
1812     kroute.gsi = virq;
1813     kroute.type = KVM_IRQ_ROUTING_HV_SINT;
1814     kroute.flags = 0;
1815     kroute.u.hv_sint.vcpu = vcpu;
1816     kroute.u.hv_sint.sint = sint;
1817 
1818     kvm_add_routing_entry(s, &kroute);
1819     kvm_irqchip_commit_routes(s);
1820 
1821     return virq;
1822 }
1823 
1824 #else /* !KVM_CAP_IRQ_ROUTING */
1825 
1826 void kvm_init_irq_routing(KVMState *s)
1827 {
1828 }
1829 
1830 void kvm_irqchip_release_virq(KVMState *s, int virq)
1831 {
1832 }
1833 
1834 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1835 {
1836     abort();
1837 }
1838 
1839 int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
1840 {
1841     return -ENOSYS;
1842 }
1843 
1844 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1845 {
1846     return -ENOSYS;
1847 }
1848 
1849 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1850 {
1851     return -ENOSYS;
1852 }
1853 
1854 static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
1855                                     EventNotifier *resample, int virq,
1856                                     bool assign)
1857 {
1858     abort();
1859 }
1860 
1861 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1862 {
1863     return -ENOSYS;
1864 }
1865 #endif /* !KVM_CAP_IRQ_ROUTING */
1866 
1867 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1868                                        EventNotifier *rn, int virq)
1869 {
1870     return kvm_irqchip_assign_irqfd(s, n, rn, virq, true);
1871 }
1872 
1873 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1874                                           int virq)
1875 {
1876     return kvm_irqchip_assign_irqfd(s, n, NULL, virq, false);
1877 }
1878 
1879 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1880                                    EventNotifier *rn, qemu_irq irq)
1881 {
1882     gpointer key, gsi;
1883     gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1884 
1885     if (!found) {
1886         return -ENXIO;
1887     }
1888     return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
1889 }
1890 
1891 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
1892                                       qemu_irq irq)
1893 {
1894     gpointer key, gsi;
1895     gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1896 
1897     if (!found) {
1898         return -ENXIO;
1899     }
1900     return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
1901 }
1902 
1903 void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
1904 {
1905     g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
1906 }
1907 
1908 static void kvm_irqchip_create(KVMState *s)
1909 {
1910     int ret;
1911 
1912     assert(s->kernel_irqchip_split != ON_OFF_AUTO_AUTO);
1913     if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
1914         ;
1915     } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
1916         ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
1917         if (ret < 0) {
1918             fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
1919             exit(1);
1920         }
1921     } else {
1922         return;
1923     }
1924 
1925     /* First probe and see if there's a arch-specific hook to create the
1926      * in-kernel irqchip for us */
1927     ret = kvm_arch_irqchip_create(s);
1928     if (ret == 0) {
1929         if (s->kernel_irqchip_split == ON_OFF_AUTO_ON) {
1930             perror("Split IRQ chip mode not supported.");
1931             exit(1);
1932         } else {
1933             ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1934         }
1935     }
1936     if (ret < 0) {
1937         fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
1938         exit(1);
1939     }
1940 
1941     kvm_kernel_irqchip = true;
1942     /* If we have an in-kernel IRQ chip then we must have asynchronous
1943      * interrupt delivery (though the reverse is not necessarily true)
1944      */
1945     kvm_async_interrupts_allowed = true;
1946     kvm_halt_in_kernel_allowed = true;
1947 
1948     kvm_init_irq_routing(s);
1949 
1950     s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
1951 }
1952 
1953 /* Find number of supported CPUs using the recommended
1954  * procedure from the kernel API documentation to cope with
1955  * older kernels that may be missing capabilities.
1956  */
1957 static int kvm_recommended_vcpus(KVMState *s)
1958 {
1959     int ret = kvm_vm_check_extension(s, KVM_CAP_NR_VCPUS);
1960     return (ret) ? ret : 4;
1961 }
1962 
1963 static int kvm_max_vcpus(KVMState *s)
1964 {
1965     int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1966     return (ret) ? ret : kvm_recommended_vcpus(s);
1967 }
1968 
1969 static int kvm_max_vcpu_id(KVMState *s)
1970 {
1971     int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
1972     return (ret) ? ret : kvm_max_vcpus(s);
1973 }
1974 
1975 bool kvm_vcpu_id_is_valid(int vcpu_id)
1976 {
1977     KVMState *s = KVM_STATE(current_accel());
1978     return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
1979 }
1980 
1981 static int kvm_init(MachineState *ms)
1982 {
1983     MachineClass *mc = MACHINE_GET_CLASS(ms);
1984     static const char upgrade_note[] =
1985         "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1986         "(see http://sourceforge.net/projects/kvm).\n";
1987     struct {
1988         const char *name;
1989         int num;
1990     } num_cpus[] = {
1991         { "SMP",          ms->smp.cpus },
1992         { "hotpluggable", ms->smp.max_cpus },
1993         { NULL, }
1994     }, *nc = num_cpus;
1995     int soft_vcpus_limit, hard_vcpus_limit;
1996     KVMState *s;
1997     const KVMCapabilityInfo *missing_cap;
1998     int ret;
1999     int type = 0;
2000     uint64_t dirty_log_manual_caps;
2001 
2002     s = KVM_STATE(ms->accelerator);
2003 
2004     /*
2005      * On systems where the kernel can support different base page
2006      * sizes, host page size may be different from TARGET_PAGE_SIZE,
2007      * even with KVM.  TARGET_PAGE_SIZE is assumed to be the minimum
2008      * page size for the system though.
2009      */
2010     assert(TARGET_PAGE_SIZE <= qemu_real_host_page_size);
2011 
2012     s->sigmask_len = 8;
2013 
2014 #ifdef KVM_CAP_SET_GUEST_DEBUG
2015     QTAILQ_INIT(&s->kvm_sw_breakpoints);
2016 #endif
2017     QLIST_INIT(&s->kvm_parked_vcpus);
2018     s->vmfd = -1;
2019     s->fd = qemu_open_old("/dev/kvm", O_RDWR);
2020     if (s->fd == -1) {
2021         fprintf(stderr, "Could not access KVM kernel module: %m\n");
2022         ret = -errno;
2023         goto err;
2024     }
2025 
2026     ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
2027     if (ret < KVM_API_VERSION) {
2028         if (ret >= 0) {
2029             ret = -EINVAL;
2030         }
2031         fprintf(stderr, "kvm version too old\n");
2032         goto err;
2033     }
2034 
2035     if (ret > KVM_API_VERSION) {
2036         ret = -EINVAL;
2037         fprintf(stderr, "kvm version not supported\n");
2038         goto err;
2039     }
2040 
2041     kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
2042     s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
2043 
2044     /* If unspecified, use the default value */
2045     if (!s->nr_slots) {
2046         s->nr_slots = 32;
2047     }
2048 
2049     s->nr_as = kvm_check_extension(s, KVM_CAP_MULTI_ADDRESS_SPACE);
2050     if (s->nr_as <= 1) {
2051         s->nr_as = 1;
2052     }
2053     s->as = g_new0(struct KVMAs, s->nr_as);
2054 
2055     if (object_property_find(OBJECT(current_machine), "kvm-type")) {
2056         g_autofree char *kvm_type = object_property_get_str(OBJECT(current_machine),
2057                                                             "kvm-type",
2058                                                             &error_abort);
2059         type = mc->kvm_type(ms, kvm_type);
2060     }
2061 
2062     do {
2063         ret = kvm_ioctl(s, KVM_CREATE_VM, type);
2064     } while (ret == -EINTR);
2065 
2066     if (ret < 0) {
2067         fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
2068                 strerror(-ret));
2069 
2070 #ifdef TARGET_S390X
2071         if (ret == -EINVAL) {
2072             fprintf(stderr,
2073                     "Host kernel setup problem detected. Please verify:\n");
2074             fprintf(stderr, "- for kernels supporting the switch_amode or"
2075                     " user_mode parameters, whether\n");
2076             fprintf(stderr,
2077                     "  user space is running in primary address space\n");
2078             fprintf(stderr,
2079                     "- for kernels supporting the vm.allocate_pgste sysctl, "
2080                     "whether it is enabled\n");
2081         }
2082 #endif
2083         goto err;
2084     }
2085 
2086     s->vmfd = ret;
2087 
2088     /* check the vcpu limits */
2089     soft_vcpus_limit = kvm_recommended_vcpus(s);
2090     hard_vcpus_limit = kvm_max_vcpus(s);
2091 
2092     while (nc->name) {
2093         if (nc->num > soft_vcpus_limit) {
2094             warn_report("Number of %s cpus requested (%d) exceeds "
2095                         "the recommended cpus supported by KVM (%d)",
2096                         nc->name, nc->num, soft_vcpus_limit);
2097 
2098             if (nc->num > hard_vcpus_limit) {
2099                 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
2100                         "the maximum cpus supported by KVM (%d)\n",
2101                         nc->name, nc->num, hard_vcpus_limit);
2102                 exit(1);
2103             }
2104         }
2105         nc++;
2106     }
2107 
2108     missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
2109     if (!missing_cap) {
2110         missing_cap =
2111             kvm_check_extension_list(s, kvm_arch_required_capabilities);
2112     }
2113     if (missing_cap) {
2114         ret = -EINVAL;
2115         fprintf(stderr, "kvm does not support %s\n%s",
2116                 missing_cap->name, upgrade_note);
2117         goto err;
2118     }
2119 
2120     s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
2121     s->coalesced_pio = s->coalesced_mmio &&
2122                        kvm_check_extension(s, KVM_CAP_COALESCED_PIO);
2123 
2124     dirty_log_manual_caps =
2125         kvm_check_extension(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
2126     dirty_log_manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
2127                               KVM_DIRTY_LOG_INITIALLY_SET);
2128     s->manual_dirty_log_protect = dirty_log_manual_caps;
2129     if (dirty_log_manual_caps) {
2130         ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0,
2131                                    dirty_log_manual_caps);
2132         if (ret) {
2133             warn_report("Trying to enable capability %"PRIu64" of "
2134                         "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
2135                         "Falling back to the legacy mode. ",
2136                         dirty_log_manual_caps);
2137             s->manual_dirty_log_protect = 0;
2138         }
2139     }
2140 
2141 #ifdef KVM_CAP_VCPU_EVENTS
2142     s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
2143 #endif
2144 
2145     s->robust_singlestep =
2146         kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
2147 
2148 #ifdef KVM_CAP_DEBUGREGS
2149     s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
2150 #endif
2151 
2152     s->max_nested_state_len = kvm_check_extension(s, KVM_CAP_NESTED_STATE);
2153 
2154 #ifdef KVM_CAP_IRQ_ROUTING
2155     kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
2156 #endif
2157 
2158     s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
2159 
2160     s->irq_set_ioctl = KVM_IRQ_LINE;
2161     if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
2162         s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
2163     }
2164 
2165     kvm_readonly_mem_allowed =
2166         (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
2167 
2168     kvm_eventfds_allowed =
2169         (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
2170 
2171     kvm_irqfds_allowed =
2172         (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
2173 
2174     kvm_resamplefds_allowed =
2175         (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
2176 
2177     kvm_vm_attributes_allowed =
2178         (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
2179 
2180     kvm_ioeventfd_any_length_allowed =
2181         (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
2182 
2183     kvm_state = s;
2184 
2185     ret = kvm_arch_init(ms, s);
2186     if (ret < 0) {
2187         goto err;
2188     }
2189 
2190     if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
2191         s->kernel_irqchip_split = mc->default_kernel_irqchip_split ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
2192     }
2193 
2194     qemu_register_reset(kvm_unpoison_all, NULL);
2195 
2196     if (s->kernel_irqchip_allowed) {
2197         kvm_irqchip_create(s);
2198     }
2199 
2200     if (kvm_eventfds_allowed) {
2201         s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
2202         s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
2203     }
2204     s->memory_listener.listener.coalesced_io_add = kvm_coalesce_mmio_region;
2205     s->memory_listener.listener.coalesced_io_del = kvm_uncoalesce_mmio_region;
2206 
2207     kvm_memory_listener_register(s, &s->memory_listener,
2208                                  &address_space_memory, 0);
2209     if (kvm_eventfds_allowed) {
2210         memory_listener_register(&kvm_io_listener,
2211                                  &address_space_io);
2212     }
2213     memory_listener_register(&kvm_coalesced_pio_listener,
2214                              &address_space_io);
2215 
2216     s->many_ioeventfds = kvm_check_many_ioeventfds();
2217 
2218     s->sync_mmu = !!kvm_vm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2219     if (!s->sync_mmu) {
2220         ret = ram_block_discard_disable(true);
2221         assert(!ret);
2222     }
2223     return 0;
2224 
2225 err:
2226     assert(ret < 0);
2227     if (s->vmfd >= 0) {
2228         close(s->vmfd);
2229     }
2230     if (s->fd != -1) {
2231         close(s->fd);
2232     }
2233     g_free(s->memory_listener.slots);
2234 
2235     return ret;
2236 }
2237 
2238 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
2239 {
2240     s->sigmask_len = sigmask_len;
2241 }
2242 
2243 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
2244                           int size, uint32_t count)
2245 {
2246     int i;
2247     uint8_t *ptr = data;
2248 
2249     for (i = 0; i < count; i++) {
2250         address_space_rw(&address_space_io, port, attrs,
2251                          ptr, size,
2252                          direction == KVM_EXIT_IO_OUT);
2253         ptr += size;
2254     }
2255 }
2256 
2257 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
2258 {
2259     fprintf(stderr, "KVM internal error. Suberror: %d\n",
2260             run->internal.suberror);
2261 
2262     if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
2263         int i;
2264 
2265         for (i = 0; i < run->internal.ndata; ++i) {
2266             fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
2267                     i, (uint64_t)run->internal.data[i]);
2268         }
2269     }
2270     if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
2271         fprintf(stderr, "emulation failure\n");
2272         if (!kvm_arch_stop_on_emulation_error(cpu)) {
2273             cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2274             return EXCP_INTERRUPT;
2275         }
2276     }
2277     /* FIXME: Should trigger a qmp message to let management know
2278      * something went wrong.
2279      */
2280     return -1;
2281 }
2282 
2283 void kvm_flush_coalesced_mmio_buffer(void)
2284 {
2285     KVMState *s = kvm_state;
2286 
2287     if (s->coalesced_flush_in_progress) {
2288         return;
2289     }
2290 
2291     s->coalesced_flush_in_progress = true;
2292 
2293     if (s->coalesced_mmio_ring) {
2294         struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
2295         while (ring->first != ring->last) {
2296             struct kvm_coalesced_mmio *ent;
2297 
2298             ent = &ring->coalesced_mmio[ring->first];
2299 
2300             if (ent->pio == 1) {
2301                 address_space_write(&address_space_io, ent->phys_addr,
2302                                     MEMTXATTRS_UNSPECIFIED, ent->data,
2303                                     ent->len);
2304             } else {
2305                 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
2306             }
2307             smp_wmb();
2308             ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
2309         }
2310     }
2311 
2312     s->coalesced_flush_in_progress = false;
2313 }
2314 
2315 bool kvm_cpu_check_are_resettable(void)
2316 {
2317     return kvm_arch_cpu_check_are_resettable();
2318 }
2319 
2320 static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
2321 {
2322     if (!cpu->vcpu_dirty) {
2323         kvm_arch_get_registers(cpu);
2324         cpu->vcpu_dirty = true;
2325     }
2326 }
2327 
2328 void kvm_cpu_synchronize_state(CPUState *cpu)
2329 {
2330     if (!cpu->vcpu_dirty) {
2331         run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
2332     }
2333 }
2334 
2335 static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
2336 {
2337     kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
2338     cpu->vcpu_dirty = false;
2339 }
2340 
2341 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
2342 {
2343     run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
2344 }
2345 
2346 static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
2347 {
2348     kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
2349     cpu->vcpu_dirty = false;
2350 }
2351 
2352 void kvm_cpu_synchronize_post_init(CPUState *cpu)
2353 {
2354     run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
2355 }
2356 
2357 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
2358 {
2359     cpu->vcpu_dirty = true;
2360 }
2361 
2362 void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
2363 {
2364     run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
2365 }
2366 
2367 #ifdef KVM_HAVE_MCE_INJECTION
2368 static __thread void *pending_sigbus_addr;
2369 static __thread int pending_sigbus_code;
2370 static __thread bool have_sigbus_pending;
2371 #endif
2372 
2373 static void kvm_cpu_kick(CPUState *cpu)
2374 {
2375     qatomic_set(&cpu->kvm_run->immediate_exit, 1);
2376 }
2377 
2378 static void kvm_cpu_kick_self(void)
2379 {
2380     if (kvm_immediate_exit) {
2381         kvm_cpu_kick(current_cpu);
2382     } else {
2383         qemu_cpu_kick_self();
2384     }
2385 }
2386 
2387 static void kvm_eat_signals(CPUState *cpu)
2388 {
2389     struct timespec ts = { 0, 0 };
2390     siginfo_t siginfo;
2391     sigset_t waitset;
2392     sigset_t chkset;
2393     int r;
2394 
2395     if (kvm_immediate_exit) {
2396         qatomic_set(&cpu->kvm_run->immediate_exit, 0);
2397         /* Write kvm_run->immediate_exit before the cpu->exit_request
2398          * write in kvm_cpu_exec.
2399          */
2400         smp_wmb();
2401         return;
2402     }
2403 
2404     sigemptyset(&waitset);
2405     sigaddset(&waitset, SIG_IPI);
2406 
2407     do {
2408         r = sigtimedwait(&waitset, &siginfo, &ts);
2409         if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
2410             perror("sigtimedwait");
2411             exit(1);
2412         }
2413 
2414         r = sigpending(&chkset);
2415         if (r == -1) {
2416             perror("sigpending");
2417             exit(1);
2418         }
2419     } while (sigismember(&chkset, SIG_IPI));
2420 }
2421 
2422 int kvm_cpu_exec(CPUState *cpu)
2423 {
2424     struct kvm_run *run = cpu->kvm_run;
2425     int ret, run_ret;
2426 
2427     DPRINTF("kvm_cpu_exec()\n");
2428 
2429     if (kvm_arch_process_async_events(cpu)) {
2430         qatomic_set(&cpu->exit_request, 0);
2431         return EXCP_HLT;
2432     }
2433 
2434     qemu_mutex_unlock_iothread();
2435     cpu_exec_start(cpu);
2436 
2437     do {
2438         MemTxAttrs attrs;
2439 
2440         if (cpu->vcpu_dirty) {
2441             kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
2442             cpu->vcpu_dirty = false;
2443         }
2444 
2445         kvm_arch_pre_run(cpu, run);
2446         if (qatomic_read(&cpu->exit_request)) {
2447             DPRINTF("interrupt exit requested\n");
2448             /*
2449              * KVM requires us to reenter the kernel after IO exits to complete
2450              * instruction emulation. This self-signal will ensure that we
2451              * leave ASAP again.
2452              */
2453             kvm_cpu_kick_self();
2454         }
2455 
2456         /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2457          * Matching barrier in kvm_eat_signals.
2458          */
2459         smp_rmb();
2460 
2461         run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
2462 
2463         attrs = kvm_arch_post_run(cpu, run);
2464 
2465 #ifdef KVM_HAVE_MCE_INJECTION
2466         if (unlikely(have_sigbus_pending)) {
2467             qemu_mutex_lock_iothread();
2468             kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
2469                                     pending_sigbus_addr);
2470             have_sigbus_pending = false;
2471             qemu_mutex_unlock_iothread();
2472         }
2473 #endif
2474 
2475         if (run_ret < 0) {
2476             if (run_ret == -EINTR || run_ret == -EAGAIN) {
2477                 DPRINTF("io window exit\n");
2478                 kvm_eat_signals(cpu);
2479                 ret = EXCP_INTERRUPT;
2480                 break;
2481             }
2482             fprintf(stderr, "error: kvm run failed %s\n",
2483                     strerror(-run_ret));
2484 #ifdef TARGET_PPC
2485             if (run_ret == -EBUSY) {
2486                 fprintf(stderr,
2487                         "This is probably because your SMT is enabled.\n"
2488                         "VCPU can only run on primary threads with all "
2489                         "secondary threads offline.\n");
2490             }
2491 #endif
2492             ret = -1;
2493             break;
2494         }
2495 
2496         trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
2497         switch (run->exit_reason) {
2498         case KVM_EXIT_IO:
2499             DPRINTF("handle_io\n");
2500             /* Called outside BQL */
2501             kvm_handle_io(run->io.port, attrs,
2502                           (uint8_t *)run + run->io.data_offset,
2503                           run->io.direction,
2504                           run->io.size,
2505                           run->io.count);
2506             ret = 0;
2507             break;
2508         case KVM_EXIT_MMIO:
2509             DPRINTF("handle_mmio\n");
2510             /* Called outside BQL */
2511             address_space_rw(&address_space_memory,
2512                              run->mmio.phys_addr, attrs,
2513                              run->mmio.data,
2514                              run->mmio.len,
2515                              run->mmio.is_write);
2516             ret = 0;
2517             break;
2518         case KVM_EXIT_IRQ_WINDOW_OPEN:
2519             DPRINTF("irq_window_open\n");
2520             ret = EXCP_INTERRUPT;
2521             break;
2522         case KVM_EXIT_SHUTDOWN:
2523             DPRINTF("shutdown\n");
2524             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
2525             ret = EXCP_INTERRUPT;
2526             break;
2527         case KVM_EXIT_UNKNOWN:
2528             fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
2529                     (uint64_t)run->hw.hardware_exit_reason);
2530             ret = -1;
2531             break;
2532         case KVM_EXIT_INTERNAL_ERROR:
2533             ret = kvm_handle_internal_error(cpu, run);
2534             break;
2535         case KVM_EXIT_SYSTEM_EVENT:
2536             switch (run->system_event.type) {
2537             case KVM_SYSTEM_EVENT_SHUTDOWN:
2538                 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
2539                 ret = EXCP_INTERRUPT;
2540                 break;
2541             case KVM_SYSTEM_EVENT_RESET:
2542                 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
2543                 ret = EXCP_INTERRUPT;
2544                 break;
2545             case KVM_SYSTEM_EVENT_CRASH:
2546                 kvm_cpu_synchronize_state(cpu);
2547                 qemu_mutex_lock_iothread();
2548                 qemu_system_guest_panicked(cpu_get_crash_info(cpu));
2549                 qemu_mutex_unlock_iothread();
2550                 ret = 0;
2551                 break;
2552             default:
2553                 DPRINTF("kvm_arch_handle_exit\n");
2554                 ret = kvm_arch_handle_exit(cpu, run);
2555                 break;
2556             }
2557             break;
2558         default:
2559             DPRINTF("kvm_arch_handle_exit\n");
2560             ret = kvm_arch_handle_exit(cpu, run);
2561             break;
2562         }
2563     } while (ret == 0);
2564 
2565     cpu_exec_end(cpu);
2566     qemu_mutex_lock_iothread();
2567 
2568     if (ret < 0) {
2569         cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2570         vm_stop(RUN_STATE_INTERNAL_ERROR);
2571     }
2572 
2573     qatomic_set(&cpu->exit_request, 0);
2574     return ret;
2575 }
2576 
2577 int kvm_ioctl(KVMState *s, int type, ...)
2578 {
2579     int ret;
2580     void *arg;
2581     va_list ap;
2582 
2583     va_start(ap, type);
2584     arg = va_arg(ap, void *);
2585     va_end(ap);
2586 
2587     trace_kvm_ioctl(type, arg);
2588     ret = ioctl(s->fd, type, arg);
2589     if (ret == -1) {
2590         ret = -errno;
2591     }
2592     return ret;
2593 }
2594 
2595 int kvm_vm_ioctl(KVMState *s, int type, ...)
2596 {
2597     int ret;
2598     void *arg;
2599     va_list ap;
2600 
2601     va_start(ap, type);
2602     arg = va_arg(ap, void *);
2603     va_end(ap);
2604 
2605     trace_kvm_vm_ioctl(type, arg);
2606     ret = ioctl(s->vmfd, type, arg);
2607     if (ret == -1) {
2608         ret = -errno;
2609     }
2610     return ret;
2611 }
2612 
2613 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
2614 {
2615     int ret;
2616     void *arg;
2617     va_list ap;
2618 
2619     va_start(ap, type);
2620     arg = va_arg(ap, void *);
2621     va_end(ap);
2622 
2623     trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
2624     ret = ioctl(cpu->kvm_fd, type, arg);
2625     if (ret == -1) {
2626         ret = -errno;
2627     }
2628     return ret;
2629 }
2630 
2631 int kvm_device_ioctl(int fd, int type, ...)
2632 {
2633     int ret;
2634     void *arg;
2635     va_list ap;
2636 
2637     va_start(ap, type);
2638     arg = va_arg(ap, void *);
2639     va_end(ap);
2640 
2641     trace_kvm_device_ioctl(fd, type, arg);
2642     ret = ioctl(fd, type, arg);
2643     if (ret == -1) {
2644         ret = -errno;
2645     }
2646     return ret;
2647 }
2648 
2649 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
2650 {
2651     int ret;
2652     struct kvm_device_attr attribute = {
2653         .group = group,
2654         .attr = attr,
2655     };
2656 
2657     if (!kvm_vm_attributes_allowed) {
2658         return 0;
2659     }
2660 
2661     ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
2662     /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2663     return ret ? 0 : 1;
2664 }
2665 
2666 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
2667 {
2668     struct kvm_device_attr attribute = {
2669         .group = group,
2670         .attr = attr,
2671         .flags = 0,
2672     };
2673 
2674     return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
2675 }
2676 
2677 int kvm_device_access(int fd, int group, uint64_t attr,
2678                       void *val, bool write, Error **errp)
2679 {
2680     struct kvm_device_attr kvmattr;
2681     int err;
2682 
2683     kvmattr.flags = 0;
2684     kvmattr.group = group;
2685     kvmattr.attr = attr;
2686     kvmattr.addr = (uintptr_t)val;
2687 
2688     err = kvm_device_ioctl(fd,
2689                            write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
2690                            &kvmattr);
2691     if (err < 0) {
2692         error_setg_errno(errp, -err,
2693                          "KVM_%s_DEVICE_ATTR failed: Group %d "
2694                          "attr 0x%016" PRIx64,
2695                          write ? "SET" : "GET", group, attr);
2696     }
2697     return err;
2698 }
2699 
2700 bool kvm_has_sync_mmu(void)
2701 {
2702     return kvm_state->sync_mmu;
2703 }
2704 
2705 int kvm_has_vcpu_events(void)
2706 {
2707     return kvm_state->vcpu_events;
2708 }
2709 
2710 int kvm_has_robust_singlestep(void)
2711 {
2712     return kvm_state->robust_singlestep;
2713 }
2714 
2715 int kvm_has_debugregs(void)
2716 {
2717     return kvm_state->debugregs;
2718 }
2719 
2720 int kvm_max_nested_state_length(void)
2721 {
2722     return kvm_state->max_nested_state_len;
2723 }
2724 
2725 int kvm_has_many_ioeventfds(void)
2726 {
2727     if (!kvm_enabled()) {
2728         return 0;
2729     }
2730     return kvm_state->many_ioeventfds;
2731 }
2732 
2733 int kvm_has_gsi_routing(void)
2734 {
2735 #ifdef KVM_CAP_IRQ_ROUTING
2736     return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
2737 #else
2738     return false;
2739 #endif
2740 }
2741 
2742 int kvm_has_intx_set_mask(void)
2743 {
2744     return kvm_state->intx_set_mask;
2745 }
2746 
2747 bool kvm_arm_supports_user_irq(void)
2748 {
2749     return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
2750 }
2751 
2752 #ifdef KVM_CAP_SET_GUEST_DEBUG
2753 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
2754                                                  target_ulong pc)
2755 {
2756     struct kvm_sw_breakpoint *bp;
2757 
2758     QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
2759         if (bp->pc == pc) {
2760             return bp;
2761         }
2762     }
2763     return NULL;
2764 }
2765 
2766 int kvm_sw_breakpoints_active(CPUState *cpu)
2767 {
2768     return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
2769 }
2770 
2771 struct kvm_set_guest_debug_data {
2772     struct kvm_guest_debug dbg;
2773     int err;
2774 };
2775 
2776 static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
2777 {
2778     struct kvm_set_guest_debug_data *dbg_data =
2779         (struct kvm_set_guest_debug_data *) data.host_ptr;
2780 
2781     dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
2782                                    &dbg_data->dbg);
2783 }
2784 
2785 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2786 {
2787     struct kvm_set_guest_debug_data data;
2788 
2789     data.dbg.control = reinject_trap;
2790 
2791     if (cpu->singlestep_enabled) {
2792         data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2793     }
2794     kvm_arch_update_guest_debug(cpu, &data.dbg);
2795 
2796     run_on_cpu(cpu, kvm_invoke_set_guest_debug,
2797                RUN_ON_CPU_HOST_PTR(&data));
2798     return data.err;
2799 }
2800 
2801 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2802                           target_ulong len, int type)
2803 {
2804     struct kvm_sw_breakpoint *bp;
2805     int err;
2806 
2807     if (type == GDB_BREAKPOINT_SW) {
2808         bp = kvm_find_sw_breakpoint(cpu, addr);
2809         if (bp) {
2810             bp->use_count++;
2811             return 0;
2812         }
2813 
2814         bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2815         bp->pc = addr;
2816         bp->use_count = 1;
2817         err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2818         if (err) {
2819             g_free(bp);
2820             return err;
2821         }
2822 
2823         QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2824     } else {
2825         err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2826         if (err) {
2827             return err;
2828         }
2829     }
2830 
2831     CPU_FOREACH(cpu) {
2832         err = kvm_update_guest_debug(cpu, 0);
2833         if (err) {
2834             return err;
2835         }
2836     }
2837     return 0;
2838 }
2839 
2840 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2841                           target_ulong len, int type)
2842 {
2843     struct kvm_sw_breakpoint *bp;
2844     int err;
2845 
2846     if (type == GDB_BREAKPOINT_SW) {
2847         bp = kvm_find_sw_breakpoint(cpu, addr);
2848         if (!bp) {
2849             return -ENOENT;
2850         }
2851 
2852         if (bp->use_count > 1) {
2853             bp->use_count--;
2854             return 0;
2855         }
2856 
2857         err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2858         if (err) {
2859             return err;
2860         }
2861 
2862         QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2863         g_free(bp);
2864     } else {
2865         err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2866         if (err) {
2867             return err;
2868         }
2869     }
2870 
2871     CPU_FOREACH(cpu) {
2872         err = kvm_update_guest_debug(cpu, 0);
2873         if (err) {
2874             return err;
2875         }
2876     }
2877     return 0;
2878 }
2879 
2880 void kvm_remove_all_breakpoints(CPUState *cpu)
2881 {
2882     struct kvm_sw_breakpoint *bp, *next;
2883     KVMState *s = cpu->kvm_state;
2884     CPUState *tmpcpu;
2885 
2886     QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2887         if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2888             /* Try harder to find a CPU that currently sees the breakpoint. */
2889             CPU_FOREACH(tmpcpu) {
2890                 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2891                     break;
2892                 }
2893             }
2894         }
2895         QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2896         g_free(bp);
2897     }
2898     kvm_arch_remove_all_hw_breakpoints();
2899 
2900     CPU_FOREACH(cpu) {
2901         kvm_update_guest_debug(cpu, 0);
2902     }
2903 }
2904 
2905 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2906 
2907 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2908 {
2909     return -EINVAL;
2910 }
2911 
2912 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2913                           target_ulong len, int type)
2914 {
2915     return -EINVAL;
2916 }
2917 
2918 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2919                           target_ulong len, int type)
2920 {
2921     return -EINVAL;
2922 }
2923 
2924 void kvm_remove_all_breakpoints(CPUState *cpu)
2925 {
2926 }
2927 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2928 
2929 static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2930 {
2931     KVMState *s = kvm_state;
2932     struct kvm_signal_mask *sigmask;
2933     int r;
2934 
2935     sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2936 
2937     sigmask->len = s->sigmask_len;
2938     memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2939     r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2940     g_free(sigmask);
2941 
2942     return r;
2943 }
2944 
2945 static void kvm_ipi_signal(int sig)
2946 {
2947     if (current_cpu) {
2948         assert(kvm_immediate_exit);
2949         kvm_cpu_kick(current_cpu);
2950     }
2951 }
2952 
2953 void kvm_init_cpu_signals(CPUState *cpu)
2954 {
2955     int r;
2956     sigset_t set;
2957     struct sigaction sigact;
2958 
2959     memset(&sigact, 0, sizeof(sigact));
2960     sigact.sa_handler = kvm_ipi_signal;
2961     sigaction(SIG_IPI, &sigact, NULL);
2962 
2963     pthread_sigmask(SIG_BLOCK, NULL, &set);
2964 #if defined KVM_HAVE_MCE_INJECTION
2965     sigdelset(&set, SIGBUS);
2966     pthread_sigmask(SIG_SETMASK, &set, NULL);
2967 #endif
2968     sigdelset(&set, SIG_IPI);
2969     if (kvm_immediate_exit) {
2970         r = pthread_sigmask(SIG_SETMASK, &set, NULL);
2971     } else {
2972         r = kvm_set_signal_mask(cpu, &set);
2973     }
2974     if (r) {
2975         fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
2976         exit(1);
2977     }
2978 }
2979 
2980 /* Called asynchronously in VCPU thread.  */
2981 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2982 {
2983 #ifdef KVM_HAVE_MCE_INJECTION
2984     if (have_sigbus_pending) {
2985         return 1;
2986     }
2987     have_sigbus_pending = true;
2988     pending_sigbus_addr = addr;
2989     pending_sigbus_code = code;
2990     qatomic_set(&cpu->exit_request, 1);
2991     return 0;
2992 #else
2993     return 1;
2994 #endif
2995 }
2996 
2997 /* Called synchronously (via signalfd) in main thread.  */
2998 int kvm_on_sigbus(int code, void *addr)
2999 {
3000 #ifdef KVM_HAVE_MCE_INJECTION
3001     /* Action required MCE kills the process if SIGBUS is blocked.  Because
3002      * that's what happens in the I/O thread, where we handle MCE via signalfd,
3003      * we can only get action optional here.
3004      */
3005     assert(code != BUS_MCEERR_AR);
3006     kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
3007     return 0;
3008 #else
3009     return 1;
3010 #endif
3011 }
3012 
3013 int kvm_create_device(KVMState *s, uint64_t type, bool test)
3014 {
3015     int ret;
3016     struct kvm_create_device create_dev;
3017 
3018     create_dev.type = type;
3019     create_dev.fd = -1;
3020     create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
3021 
3022     if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
3023         return -ENOTSUP;
3024     }
3025 
3026     ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
3027     if (ret) {
3028         return ret;
3029     }
3030 
3031     return test ? 0 : create_dev.fd;
3032 }
3033 
3034 bool kvm_device_supported(int vmfd, uint64_t type)
3035 {
3036     struct kvm_create_device create_dev = {
3037         .type = type,
3038         .fd = -1,
3039         .flags = KVM_CREATE_DEVICE_TEST,
3040     };
3041 
3042     if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
3043         return false;
3044     }
3045 
3046     return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
3047 }
3048 
3049 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
3050 {
3051     struct kvm_one_reg reg;
3052     int r;
3053 
3054     reg.id = id;
3055     reg.addr = (uintptr_t) source;
3056     r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
3057     if (r) {
3058         trace_kvm_failed_reg_set(id, strerror(-r));
3059     }
3060     return r;
3061 }
3062 
3063 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
3064 {
3065     struct kvm_one_reg reg;
3066     int r;
3067 
3068     reg.id = id;
3069     reg.addr = (uintptr_t) target;
3070     r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
3071     if (r) {
3072         trace_kvm_failed_reg_get(id, strerror(-r));
3073     }
3074     return r;
3075 }
3076 
3077 static bool kvm_accel_has_memory(MachineState *ms, AddressSpace *as,
3078                                  hwaddr start_addr, hwaddr size)
3079 {
3080     KVMState *kvm = KVM_STATE(ms->accelerator);
3081     int i;
3082 
3083     for (i = 0; i < kvm->nr_as; ++i) {
3084         if (kvm->as[i].as == as && kvm->as[i].ml) {
3085             size = MIN(kvm_max_slot_size, size);
3086             return NULL != kvm_lookup_matching_slot(kvm->as[i].ml,
3087                                                     start_addr, size);
3088         }
3089     }
3090 
3091     return false;
3092 }
3093 
3094 static void kvm_get_kvm_shadow_mem(Object *obj, Visitor *v,
3095                                    const char *name, void *opaque,
3096                                    Error **errp)
3097 {
3098     KVMState *s = KVM_STATE(obj);
3099     int64_t value = s->kvm_shadow_mem;
3100 
3101     visit_type_int(v, name, &value, errp);
3102 }
3103 
3104 static void kvm_set_kvm_shadow_mem(Object *obj, Visitor *v,
3105                                    const char *name, void *opaque,
3106                                    Error **errp)
3107 {
3108     KVMState *s = KVM_STATE(obj);
3109     int64_t value;
3110 
3111     if (!visit_type_int(v, name, &value, errp)) {
3112         return;
3113     }
3114 
3115     s->kvm_shadow_mem = value;
3116 }
3117 
3118 static void kvm_set_kernel_irqchip(Object *obj, Visitor *v,
3119                                    const char *name, void *opaque,
3120                                    Error **errp)
3121 {
3122     KVMState *s = KVM_STATE(obj);
3123     OnOffSplit mode;
3124 
3125     if (!visit_type_OnOffSplit(v, name, &mode, errp)) {
3126         return;
3127     }
3128     switch (mode) {
3129     case ON_OFF_SPLIT_ON:
3130         s->kernel_irqchip_allowed = true;
3131         s->kernel_irqchip_required = true;
3132         s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3133         break;
3134     case ON_OFF_SPLIT_OFF:
3135         s->kernel_irqchip_allowed = false;
3136         s->kernel_irqchip_required = false;
3137         s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3138         break;
3139     case ON_OFF_SPLIT_SPLIT:
3140         s->kernel_irqchip_allowed = true;
3141         s->kernel_irqchip_required = true;
3142         s->kernel_irqchip_split = ON_OFF_AUTO_ON;
3143         break;
3144     default:
3145         /* The value was checked in visit_type_OnOffSplit() above. If
3146          * we get here, then something is wrong in QEMU.
3147          */
3148         abort();
3149     }
3150 }
3151 
3152 bool kvm_kernel_irqchip_allowed(void)
3153 {
3154     return kvm_state->kernel_irqchip_allowed;
3155 }
3156 
3157 bool kvm_kernel_irqchip_required(void)
3158 {
3159     return kvm_state->kernel_irqchip_required;
3160 }
3161 
3162 bool kvm_kernel_irqchip_split(void)
3163 {
3164     return kvm_state->kernel_irqchip_split == ON_OFF_AUTO_ON;
3165 }
3166 
3167 static void kvm_accel_instance_init(Object *obj)
3168 {
3169     KVMState *s = KVM_STATE(obj);
3170 
3171     s->kvm_shadow_mem = -1;
3172     s->kernel_irqchip_allowed = true;
3173     s->kernel_irqchip_split = ON_OFF_AUTO_AUTO;
3174 }
3175 
3176 static void kvm_accel_class_init(ObjectClass *oc, void *data)
3177 {
3178     AccelClass *ac = ACCEL_CLASS(oc);
3179     ac->name = "KVM";
3180     ac->init_machine = kvm_init;
3181     ac->has_memory = kvm_accel_has_memory;
3182     ac->allowed = &kvm_allowed;
3183 
3184     object_class_property_add(oc, "kernel-irqchip", "on|off|split",
3185         NULL, kvm_set_kernel_irqchip,
3186         NULL, NULL);
3187     object_class_property_set_description(oc, "kernel-irqchip",
3188         "Configure KVM in-kernel irqchip");
3189 
3190     object_class_property_add(oc, "kvm-shadow-mem", "int",
3191         kvm_get_kvm_shadow_mem, kvm_set_kvm_shadow_mem,
3192         NULL, NULL);
3193     object_class_property_set_description(oc, "kvm-shadow-mem",
3194         "KVM shadow MMU size");
3195 }
3196 
3197 static const TypeInfo kvm_accel_type = {
3198     .name = TYPE_KVM_ACCEL,
3199     .parent = TYPE_ACCEL,
3200     .instance_init = kvm_accel_instance_init,
3201     .class_init = kvm_accel_class_init,
3202     .instance_size = sizeof(KVMState),
3203 };
3204 
3205 static void kvm_type_init(void)
3206 {
3207     type_register_static(&kvm_accel_type);
3208 }
3209 
3210 type_init(kvm_type_init);
3211