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