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