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