xref: /openbmc/qemu/accel/kvm/kvm-all.c (revision cba42d61)
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     }
2072 
2073     do {
2074         ret = kvm_ioctl(s, KVM_CREATE_VM, type);
2075     } while (ret == -EINTR);
2076 
2077     if (ret < 0) {
2078         fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
2079                 strerror(-ret));
2080 
2081 #ifdef TARGET_S390X
2082         if (ret == -EINVAL) {
2083             fprintf(stderr,
2084                     "Host kernel setup problem detected. Please verify:\n");
2085             fprintf(stderr, "- for kernels supporting the switch_amode or"
2086                     " user_mode parameters, whether\n");
2087             fprintf(stderr,
2088                     "  user space is running in primary address space\n");
2089             fprintf(stderr,
2090                     "- for kernels supporting the vm.allocate_pgste sysctl, "
2091                     "whether it is enabled\n");
2092         }
2093 #endif
2094         goto err;
2095     }
2096 
2097     s->vmfd = ret;
2098 
2099     /* check the vcpu limits */
2100     soft_vcpus_limit = kvm_recommended_vcpus(s);
2101     hard_vcpus_limit = kvm_max_vcpus(s);
2102 
2103     while (nc->name) {
2104         if (nc->num > soft_vcpus_limit) {
2105             warn_report("Number of %s cpus requested (%d) exceeds "
2106                         "the recommended cpus supported by KVM (%d)",
2107                         nc->name, nc->num, soft_vcpus_limit);
2108 
2109             if (nc->num > hard_vcpus_limit) {
2110                 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
2111                         "the maximum cpus supported by KVM (%d)\n",
2112                         nc->name, nc->num, hard_vcpus_limit);
2113                 exit(1);
2114             }
2115         }
2116         nc++;
2117     }
2118 
2119     missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
2120     if (!missing_cap) {
2121         missing_cap =
2122             kvm_check_extension_list(s, kvm_arch_required_capabilities);
2123     }
2124     if (missing_cap) {
2125         ret = -EINVAL;
2126         fprintf(stderr, "kvm does not support %s\n%s",
2127                 missing_cap->name, upgrade_note);
2128         goto err;
2129     }
2130 
2131     s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
2132     s->coalesced_pio = s->coalesced_mmio &&
2133                        kvm_check_extension(s, KVM_CAP_COALESCED_PIO);
2134 
2135     dirty_log_manual_caps =
2136         kvm_check_extension(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
2137     dirty_log_manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
2138                               KVM_DIRTY_LOG_INITIALLY_SET);
2139     s->manual_dirty_log_protect = dirty_log_manual_caps;
2140     if (dirty_log_manual_caps) {
2141         ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0,
2142                                    dirty_log_manual_caps);
2143         if (ret) {
2144             warn_report("Trying to enable capability %"PRIu64" of "
2145                         "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
2146                         "Falling back to the legacy mode. ",
2147                         dirty_log_manual_caps);
2148             s->manual_dirty_log_protect = 0;
2149         }
2150     }
2151 
2152 #ifdef KVM_CAP_VCPU_EVENTS
2153     s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
2154 #endif
2155 
2156     s->robust_singlestep =
2157         kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
2158 
2159 #ifdef KVM_CAP_DEBUGREGS
2160     s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
2161 #endif
2162 
2163     s->max_nested_state_len = kvm_check_extension(s, KVM_CAP_NESTED_STATE);
2164 
2165 #ifdef KVM_CAP_IRQ_ROUTING
2166     kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
2167 #endif
2168 
2169     s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
2170 
2171     s->irq_set_ioctl = KVM_IRQ_LINE;
2172     if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
2173         s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
2174     }
2175 
2176     kvm_readonly_mem_allowed =
2177         (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
2178 
2179     kvm_eventfds_allowed =
2180         (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
2181 
2182     kvm_irqfds_allowed =
2183         (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
2184 
2185     kvm_resamplefds_allowed =
2186         (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
2187 
2188     kvm_vm_attributes_allowed =
2189         (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
2190 
2191     kvm_ioeventfd_any_length_allowed =
2192         (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
2193 
2194     kvm_state = s;
2195 
2196     ret = kvm_arch_init(ms, s);
2197     if (ret < 0) {
2198         goto err;
2199     }
2200 
2201     if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
2202         s->kernel_irqchip_split = mc->default_kernel_irqchip_split ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
2203     }
2204 
2205     qemu_register_reset(kvm_unpoison_all, NULL);
2206 
2207     if (s->kernel_irqchip_allowed) {
2208         kvm_irqchip_create(s);
2209     }
2210 
2211     if (kvm_eventfds_allowed) {
2212         s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
2213         s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
2214     }
2215     s->memory_listener.listener.coalesced_io_add = kvm_coalesce_mmio_region;
2216     s->memory_listener.listener.coalesced_io_del = kvm_uncoalesce_mmio_region;
2217 
2218     kvm_memory_listener_register(s, &s->memory_listener,
2219                                  &address_space_memory, 0);
2220     if (kvm_eventfds_allowed) {
2221         memory_listener_register(&kvm_io_listener,
2222                                  &address_space_io);
2223     }
2224     memory_listener_register(&kvm_coalesced_pio_listener,
2225                              &address_space_io);
2226 
2227     s->many_ioeventfds = kvm_check_many_ioeventfds();
2228 
2229     s->sync_mmu = !!kvm_vm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2230     if (!s->sync_mmu) {
2231         ret = ram_block_discard_disable(true);
2232         assert(!ret);
2233     }
2234     return 0;
2235 
2236 err:
2237     assert(ret < 0);
2238     if (s->vmfd >= 0) {
2239         close(s->vmfd);
2240     }
2241     if (s->fd != -1) {
2242         close(s->fd);
2243     }
2244     g_free(s->memory_listener.slots);
2245 
2246     return ret;
2247 }
2248 
2249 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
2250 {
2251     s->sigmask_len = sigmask_len;
2252 }
2253 
2254 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
2255                           int size, uint32_t count)
2256 {
2257     int i;
2258     uint8_t *ptr = data;
2259 
2260     for (i = 0; i < count; i++) {
2261         address_space_rw(&address_space_io, port, attrs,
2262                          ptr, size,
2263                          direction == KVM_EXIT_IO_OUT);
2264         ptr += size;
2265     }
2266 }
2267 
2268 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
2269 {
2270     fprintf(stderr, "KVM internal error. Suberror: %d\n",
2271             run->internal.suberror);
2272 
2273     if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
2274         int i;
2275 
2276         for (i = 0; i < run->internal.ndata; ++i) {
2277             fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
2278                     i, (uint64_t)run->internal.data[i]);
2279         }
2280     }
2281     if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
2282         fprintf(stderr, "emulation failure\n");
2283         if (!kvm_arch_stop_on_emulation_error(cpu)) {
2284             cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2285             return EXCP_INTERRUPT;
2286         }
2287     }
2288     /* FIXME: Should trigger a qmp message to let management know
2289      * something went wrong.
2290      */
2291     return -1;
2292 }
2293 
2294 void kvm_flush_coalesced_mmio_buffer(void)
2295 {
2296     KVMState *s = kvm_state;
2297 
2298     if (s->coalesced_flush_in_progress) {
2299         return;
2300     }
2301 
2302     s->coalesced_flush_in_progress = true;
2303 
2304     if (s->coalesced_mmio_ring) {
2305         struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
2306         while (ring->first != ring->last) {
2307             struct kvm_coalesced_mmio *ent;
2308 
2309             ent = &ring->coalesced_mmio[ring->first];
2310 
2311             if (ent->pio == 1) {
2312                 address_space_write(&address_space_io, ent->phys_addr,
2313                                     MEMTXATTRS_UNSPECIFIED, ent->data,
2314                                     ent->len);
2315             } else {
2316                 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
2317             }
2318             smp_wmb();
2319             ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
2320         }
2321     }
2322 
2323     s->coalesced_flush_in_progress = false;
2324 }
2325 
2326 bool kvm_cpu_check_are_resettable(void)
2327 {
2328     return kvm_arch_cpu_check_are_resettable();
2329 }
2330 
2331 static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
2332 {
2333     if (!cpu->vcpu_dirty) {
2334         kvm_arch_get_registers(cpu);
2335         cpu->vcpu_dirty = true;
2336     }
2337 }
2338 
2339 void kvm_cpu_synchronize_state(CPUState *cpu)
2340 {
2341     if (!cpu->vcpu_dirty) {
2342         run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
2343     }
2344 }
2345 
2346 static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
2347 {
2348     kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
2349     cpu->vcpu_dirty = false;
2350 }
2351 
2352 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
2353 {
2354     run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
2355 }
2356 
2357 static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
2358 {
2359     kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
2360     cpu->vcpu_dirty = false;
2361 }
2362 
2363 void kvm_cpu_synchronize_post_init(CPUState *cpu)
2364 {
2365     run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
2366 }
2367 
2368 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
2369 {
2370     cpu->vcpu_dirty = true;
2371 }
2372 
2373 void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
2374 {
2375     run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
2376 }
2377 
2378 #ifdef KVM_HAVE_MCE_INJECTION
2379 static __thread void *pending_sigbus_addr;
2380 static __thread int pending_sigbus_code;
2381 static __thread bool have_sigbus_pending;
2382 #endif
2383 
2384 static void kvm_cpu_kick(CPUState *cpu)
2385 {
2386     qatomic_set(&cpu->kvm_run->immediate_exit, 1);
2387 }
2388 
2389 static void kvm_cpu_kick_self(void)
2390 {
2391     if (kvm_immediate_exit) {
2392         kvm_cpu_kick(current_cpu);
2393     } else {
2394         qemu_cpu_kick_self();
2395     }
2396 }
2397 
2398 static void kvm_eat_signals(CPUState *cpu)
2399 {
2400     struct timespec ts = { 0, 0 };
2401     siginfo_t siginfo;
2402     sigset_t waitset;
2403     sigset_t chkset;
2404     int r;
2405 
2406     if (kvm_immediate_exit) {
2407         qatomic_set(&cpu->kvm_run->immediate_exit, 0);
2408         /* Write kvm_run->immediate_exit before the cpu->exit_request
2409          * write in kvm_cpu_exec.
2410          */
2411         smp_wmb();
2412         return;
2413     }
2414 
2415     sigemptyset(&waitset);
2416     sigaddset(&waitset, SIG_IPI);
2417 
2418     do {
2419         r = sigtimedwait(&waitset, &siginfo, &ts);
2420         if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
2421             perror("sigtimedwait");
2422             exit(1);
2423         }
2424 
2425         r = sigpending(&chkset);
2426         if (r == -1) {
2427             perror("sigpending");
2428             exit(1);
2429         }
2430     } while (sigismember(&chkset, SIG_IPI));
2431 }
2432 
2433 int kvm_cpu_exec(CPUState *cpu)
2434 {
2435     struct kvm_run *run = cpu->kvm_run;
2436     int ret, run_ret;
2437 
2438     DPRINTF("kvm_cpu_exec()\n");
2439 
2440     if (kvm_arch_process_async_events(cpu)) {
2441         qatomic_set(&cpu->exit_request, 0);
2442         return EXCP_HLT;
2443     }
2444 
2445     qemu_mutex_unlock_iothread();
2446     cpu_exec_start(cpu);
2447 
2448     do {
2449         MemTxAttrs attrs;
2450 
2451         if (cpu->vcpu_dirty) {
2452             kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
2453             cpu->vcpu_dirty = false;
2454         }
2455 
2456         kvm_arch_pre_run(cpu, run);
2457         if (qatomic_read(&cpu->exit_request)) {
2458             DPRINTF("interrupt exit requested\n");
2459             /*
2460              * KVM requires us to reenter the kernel after IO exits to complete
2461              * instruction emulation. This self-signal will ensure that we
2462              * leave ASAP again.
2463              */
2464             kvm_cpu_kick_self();
2465         }
2466 
2467         /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2468          * Matching barrier in kvm_eat_signals.
2469          */
2470         smp_rmb();
2471 
2472         run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
2473 
2474         attrs = kvm_arch_post_run(cpu, run);
2475 
2476 #ifdef KVM_HAVE_MCE_INJECTION
2477         if (unlikely(have_sigbus_pending)) {
2478             qemu_mutex_lock_iothread();
2479             kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
2480                                     pending_sigbus_addr);
2481             have_sigbus_pending = false;
2482             qemu_mutex_unlock_iothread();
2483         }
2484 #endif
2485 
2486         if (run_ret < 0) {
2487             if (run_ret == -EINTR || run_ret == -EAGAIN) {
2488                 DPRINTF("io window exit\n");
2489                 kvm_eat_signals(cpu);
2490                 ret = EXCP_INTERRUPT;
2491                 break;
2492             }
2493             fprintf(stderr, "error: kvm run failed %s\n",
2494                     strerror(-run_ret));
2495 #ifdef TARGET_PPC
2496             if (run_ret == -EBUSY) {
2497                 fprintf(stderr,
2498                         "This is probably because your SMT is enabled.\n"
2499                         "VCPU can only run on primary threads with all "
2500                         "secondary threads offline.\n");
2501             }
2502 #endif
2503             ret = -1;
2504             break;
2505         }
2506 
2507         trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
2508         switch (run->exit_reason) {
2509         case KVM_EXIT_IO:
2510             DPRINTF("handle_io\n");
2511             /* Called outside BQL */
2512             kvm_handle_io(run->io.port, attrs,
2513                           (uint8_t *)run + run->io.data_offset,
2514                           run->io.direction,
2515                           run->io.size,
2516                           run->io.count);
2517             ret = 0;
2518             break;
2519         case KVM_EXIT_MMIO:
2520             DPRINTF("handle_mmio\n");
2521             /* Called outside BQL */
2522             address_space_rw(&address_space_memory,
2523                              run->mmio.phys_addr, attrs,
2524                              run->mmio.data,
2525                              run->mmio.len,
2526                              run->mmio.is_write);
2527             ret = 0;
2528             break;
2529         case KVM_EXIT_IRQ_WINDOW_OPEN:
2530             DPRINTF("irq_window_open\n");
2531             ret = EXCP_INTERRUPT;
2532             break;
2533         case KVM_EXIT_SHUTDOWN:
2534             DPRINTF("shutdown\n");
2535             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
2536             ret = EXCP_INTERRUPT;
2537             break;
2538         case KVM_EXIT_UNKNOWN:
2539             fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
2540                     (uint64_t)run->hw.hardware_exit_reason);
2541             ret = -1;
2542             break;
2543         case KVM_EXIT_INTERNAL_ERROR:
2544             ret = kvm_handle_internal_error(cpu, run);
2545             break;
2546         case KVM_EXIT_SYSTEM_EVENT:
2547             switch (run->system_event.type) {
2548             case KVM_SYSTEM_EVENT_SHUTDOWN:
2549                 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
2550                 ret = EXCP_INTERRUPT;
2551                 break;
2552             case KVM_SYSTEM_EVENT_RESET:
2553                 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
2554                 ret = EXCP_INTERRUPT;
2555                 break;
2556             case KVM_SYSTEM_EVENT_CRASH:
2557                 kvm_cpu_synchronize_state(cpu);
2558                 qemu_mutex_lock_iothread();
2559                 qemu_system_guest_panicked(cpu_get_crash_info(cpu));
2560                 qemu_mutex_unlock_iothread();
2561                 ret = 0;
2562                 break;
2563             default:
2564                 DPRINTF("kvm_arch_handle_exit\n");
2565                 ret = kvm_arch_handle_exit(cpu, run);
2566                 break;
2567             }
2568             break;
2569         default:
2570             DPRINTF("kvm_arch_handle_exit\n");
2571             ret = kvm_arch_handle_exit(cpu, run);
2572             break;
2573         }
2574     } while (ret == 0);
2575 
2576     cpu_exec_end(cpu);
2577     qemu_mutex_lock_iothread();
2578 
2579     if (ret < 0) {
2580         cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
2581         vm_stop(RUN_STATE_INTERNAL_ERROR);
2582     }
2583 
2584     qatomic_set(&cpu->exit_request, 0);
2585     return ret;
2586 }
2587 
2588 int kvm_ioctl(KVMState *s, int type, ...)
2589 {
2590     int ret;
2591     void *arg;
2592     va_list ap;
2593 
2594     va_start(ap, type);
2595     arg = va_arg(ap, void *);
2596     va_end(ap);
2597 
2598     trace_kvm_ioctl(type, arg);
2599     ret = ioctl(s->fd, type, arg);
2600     if (ret == -1) {
2601         ret = -errno;
2602     }
2603     return ret;
2604 }
2605 
2606 int kvm_vm_ioctl(KVMState *s, int type, ...)
2607 {
2608     int ret;
2609     void *arg;
2610     va_list ap;
2611 
2612     va_start(ap, type);
2613     arg = va_arg(ap, void *);
2614     va_end(ap);
2615 
2616     trace_kvm_vm_ioctl(type, arg);
2617     ret = ioctl(s->vmfd, type, arg);
2618     if (ret == -1) {
2619         ret = -errno;
2620     }
2621     return ret;
2622 }
2623 
2624 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
2625 {
2626     int ret;
2627     void *arg;
2628     va_list ap;
2629 
2630     va_start(ap, type);
2631     arg = va_arg(ap, void *);
2632     va_end(ap);
2633 
2634     trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
2635     ret = ioctl(cpu->kvm_fd, type, arg);
2636     if (ret == -1) {
2637         ret = -errno;
2638     }
2639     return ret;
2640 }
2641 
2642 int kvm_device_ioctl(int fd, int type, ...)
2643 {
2644     int ret;
2645     void *arg;
2646     va_list ap;
2647 
2648     va_start(ap, type);
2649     arg = va_arg(ap, void *);
2650     va_end(ap);
2651 
2652     trace_kvm_device_ioctl(fd, type, arg);
2653     ret = ioctl(fd, type, arg);
2654     if (ret == -1) {
2655         ret = -errno;
2656     }
2657     return ret;
2658 }
2659 
2660 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
2661 {
2662     int ret;
2663     struct kvm_device_attr attribute = {
2664         .group = group,
2665         .attr = attr,
2666     };
2667 
2668     if (!kvm_vm_attributes_allowed) {
2669         return 0;
2670     }
2671 
2672     ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
2673     /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2674     return ret ? 0 : 1;
2675 }
2676 
2677 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
2678 {
2679     struct kvm_device_attr attribute = {
2680         .group = group,
2681         .attr = attr,
2682         .flags = 0,
2683     };
2684 
2685     return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
2686 }
2687 
2688 int kvm_device_access(int fd, int group, uint64_t attr,
2689                       void *val, bool write, Error **errp)
2690 {
2691     struct kvm_device_attr kvmattr;
2692     int err;
2693 
2694     kvmattr.flags = 0;
2695     kvmattr.group = group;
2696     kvmattr.attr = attr;
2697     kvmattr.addr = (uintptr_t)val;
2698 
2699     err = kvm_device_ioctl(fd,
2700                            write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
2701                            &kvmattr);
2702     if (err < 0) {
2703         error_setg_errno(errp, -err,
2704                          "KVM_%s_DEVICE_ATTR failed: Group %d "
2705                          "attr 0x%016" PRIx64,
2706                          write ? "SET" : "GET", group, attr);
2707     }
2708     return err;
2709 }
2710 
2711 bool kvm_has_sync_mmu(void)
2712 {
2713     return kvm_state->sync_mmu;
2714 }
2715 
2716 int kvm_has_vcpu_events(void)
2717 {
2718     return kvm_state->vcpu_events;
2719 }
2720 
2721 int kvm_has_robust_singlestep(void)
2722 {
2723     return kvm_state->robust_singlestep;
2724 }
2725 
2726 int kvm_has_debugregs(void)
2727 {
2728     return kvm_state->debugregs;
2729 }
2730 
2731 int kvm_max_nested_state_length(void)
2732 {
2733     return kvm_state->max_nested_state_len;
2734 }
2735 
2736 int kvm_has_many_ioeventfds(void)
2737 {
2738     if (!kvm_enabled()) {
2739         return 0;
2740     }
2741     return kvm_state->many_ioeventfds;
2742 }
2743 
2744 int kvm_has_gsi_routing(void)
2745 {
2746 #ifdef KVM_CAP_IRQ_ROUTING
2747     return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
2748 #else
2749     return false;
2750 #endif
2751 }
2752 
2753 int kvm_has_intx_set_mask(void)
2754 {
2755     return kvm_state->intx_set_mask;
2756 }
2757 
2758 bool kvm_arm_supports_user_irq(void)
2759 {
2760     return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
2761 }
2762 
2763 #ifdef KVM_CAP_SET_GUEST_DEBUG
2764 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
2765                                                  target_ulong pc)
2766 {
2767     struct kvm_sw_breakpoint *bp;
2768 
2769     QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
2770         if (bp->pc == pc) {
2771             return bp;
2772         }
2773     }
2774     return NULL;
2775 }
2776 
2777 int kvm_sw_breakpoints_active(CPUState *cpu)
2778 {
2779     return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
2780 }
2781 
2782 struct kvm_set_guest_debug_data {
2783     struct kvm_guest_debug dbg;
2784     int err;
2785 };
2786 
2787 static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
2788 {
2789     struct kvm_set_guest_debug_data *dbg_data =
2790         (struct kvm_set_guest_debug_data *) data.host_ptr;
2791 
2792     dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
2793                                    &dbg_data->dbg);
2794 }
2795 
2796 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2797 {
2798     struct kvm_set_guest_debug_data data;
2799 
2800     data.dbg.control = reinject_trap;
2801 
2802     if (cpu->singlestep_enabled) {
2803         data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2804     }
2805     kvm_arch_update_guest_debug(cpu, &data.dbg);
2806 
2807     run_on_cpu(cpu, kvm_invoke_set_guest_debug,
2808                RUN_ON_CPU_HOST_PTR(&data));
2809     return data.err;
2810 }
2811 
2812 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2813                           target_ulong len, int type)
2814 {
2815     struct kvm_sw_breakpoint *bp;
2816     int err;
2817 
2818     if (type == GDB_BREAKPOINT_SW) {
2819         bp = kvm_find_sw_breakpoint(cpu, addr);
2820         if (bp) {
2821             bp->use_count++;
2822             return 0;
2823         }
2824 
2825         bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2826         bp->pc = addr;
2827         bp->use_count = 1;
2828         err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2829         if (err) {
2830             g_free(bp);
2831             return err;
2832         }
2833 
2834         QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2835     } else {
2836         err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2837         if (err) {
2838             return err;
2839         }
2840     }
2841 
2842     CPU_FOREACH(cpu) {
2843         err = kvm_update_guest_debug(cpu, 0);
2844         if (err) {
2845             return err;
2846         }
2847     }
2848     return 0;
2849 }
2850 
2851 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2852                           target_ulong len, int type)
2853 {
2854     struct kvm_sw_breakpoint *bp;
2855     int err;
2856 
2857     if (type == GDB_BREAKPOINT_SW) {
2858         bp = kvm_find_sw_breakpoint(cpu, addr);
2859         if (!bp) {
2860             return -ENOENT;
2861         }
2862 
2863         if (bp->use_count > 1) {
2864             bp->use_count--;
2865             return 0;
2866         }
2867 
2868         err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2869         if (err) {
2870             return err;
2871         }
2872 
2873         QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2874         g_free(bp);
2875     } else {
2876         err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2877         if (err) {
2878             return err;
2879         }
2880     }
2881 
2882     CPU_FOREACH(cpu) {
2883         err = kvm_update_guest_debug(cpu, 0);
2884         if (err) {
2885             return err;
2886         }
2887     }
2888     return 0;
2889 }
2890 
2891 void kvm_remove_all_breakpoints(CPUState *cpu)
2892 {
2893     struct kvm_sw_breakpoint *bp, *next;
2894     KVMState *s = cpu->kvm_state;
2895     CPUState *tmpcpu;
2896 
2897     QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2898         if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2899             /* Try harder to find a CPU that currently sees the breakpoint. */
2900             CPU_FOREACH(tmpcpu) {
2901                 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2902                     break;
2903                 }
2904             }
2905         }
2906         QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2907         g_free(bp);
2908     }
2909     kvm_arch_remove_all_hw_breakpoints();
2910 
2911     CPU_FOREACH(cpu) {
2912         kvm_update_guest_debug(cpu, 0);
2913     }
2914 }
2915 
2916 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2917 
2918 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2919 {
2920     return -EINVAL;
2921 }
2922 
2923 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2924                           target_ulong len, int type)
2925 {
2926     return -EINVAL;
2927 }
2928 
2929 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2930                           target_ulong len, int type)
2931 {
2932     return -EINVAL;
2933 }
2934 
2935 void kvm_remove_all_breakpoints(CPUState *cpu)
2936 {
2937 }
2938 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2939 
2940 static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2941 {
2942     KVMState *s = kvm_state;
2943     struct kvm_signal_mask *sigmask;
2944     int r;
2945 
2946     sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2947 
2948     sigmask->len = s->sigmask_len;
2949     memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2950     r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2951     g_free(sigmask);
2952 
2953     return r;
2954 }
2955 
2956 static void kvm_ipi_signal(int sig)
2957 {
2958     if (current_cpu) {
2959         assert(kvm_immediate_exit);
2960         kvm_cpu_kick(current_cpu);
2961     }
2962 }
2963 
2964 void kvm_init_cpu_signals(CPUState *cpu)
2965 {
2966     int r;
2967     sigset_t set;
2968     struct sigaction sigact;
2969 
2970     memset(&sigact, 0, sizeof(sigact));
2971     sigact.sa_handler = kvm_ipi_signal;
2972     sigaction(SIG_IPI, &sigact, NULL);
2973 
2974     pthread_sigmask(SIG_BLOCK, NULL, &set);
2975 #if defined KVM_HAVE_MCE_INJECTION
2976     sigdelset(&set, SIGBUS);
2977     pthread_sigmask(SIG_SETMASK, &set, NULL);
2978 #endif
2979     sigdelset(&set, SIG_IPI);
2980     if (kvm_immediate_exit) {
2981         r = pthread_sigmask(SIG_SETMASK, &set, NULL);
2982     } else {
2983         r = kvm_set_signal_mask(cpu, &set);
2984     }
2985     if (r) {
2986         fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
2987         exit(1);
2988     }
2989 }
2990 
2991 /* Called asynchronously in VCPU thread.  */
2992 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2993 {
2994 #ifdef KVM_HAVE_MCE_INJECTION
2995     if (have_sigbus_pending) {
2996         return 1;
2997     }
2998     have_sigbus_pending = true;
2999     pending_sigbus_addr = addr;
3000     pending_sigbus_code = code;
3001     qatomic_set(&cpu->exit_request, 1);
3002     return 0;
3003 #else
3004     return 1;
3005 #endif
3006 }
3007 
3008 /* Called synchronously (via signalfd) in main thread.  */
3009 int kvm_on_sigbus(int code, void *addr)
3010 {
3011 #ifdef KVM_HAVE_MCE_INJECTION
3012     /* Action required MCE kills the process if SIGBUS is blocked.  Because
3013      * that's what happens in the I/O thread, where we handle MCE via signalfd,
3014      * we can only get action optional here.
3015      */
3016     assert(code != BUS_MCEERR_AR);
3017     kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
3018     return 0;
3019 #else
3020     return 1;
3021 #endif
3022 }
3023 
3024 int kvm_create_device(KVMState *s, uint64_t type, bool test)
3025 {
3026     int ret;
3027     struct kvm_create_device create_dev;
3028 
3029     create_dev.type = type;
3030     create_dev.fd = -1;
3031     create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
3032 
3033     if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
3034         return -ENOTSUP;
3035     }
3036 
3037     ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
3038     if (ret) {
3039         return ret;
3040     }
3041 
3042     return test ? 0 : create_dev.fd;
3043 }
3044 
3045 bool kvm_device_supported(int vmfd, uint64_t type)
3046 {
3047     struct kvm_create_device create_dev = {
3048         .type = type,
3049         .fd = -1,
3050         .flags = KVM_CREATE_DEVICE_TEST,
3051     };
3052 
3053     if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
3054         return false;
3055     }
3056 
3057     return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
3058 }
3059 
3060 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
3061 {
3062     struct kvm_one_reg reg;
3063     int r;
3064 
3065     reg.id = id;
3066     reg.addr = (uintptr_t) source;
3067     r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
3068     if (r) {
3069         trace_kvm_failed_reg_set(id, strerror(-r));
3070     }
3071     return r;
3072 }
3073 
3074 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
3075 {
3076     struct kvm_one_reg reg;
3077     int r;
3078 
3079     reg.id = id;
3080     reg.addr = (uintptr_t) target;
3081     r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
3082     if (r) {
3083         trace_kvm_failed_reg_get(id, strerror(-r));
3084     }
3085     return r;
3086 }
3087 
3088 static bool kvm_accel_has_memory(MachineState *ms, AddressSpace *as,
3089                                  hwaddr start_addr, hwaddr size)
3090 {
3091     KVMState *kvm = KVM_STATE(ms->accelerator);
3092     int i;
3093 
3094     for (i = 0; i < kvm->nr_as; ++i) {
3095         if (kvm->as[i].as == as && kvm->as[i].ml) {
3096             size = MIN(kvm_max_slot_size, size);
3097             return NULL != kvm_lookup_matching_slot(kvm->as[i].ml,
3098                                                     start_addr, size);
3099         }
3100     }
3101 
3102     return false;
3103 }
3104 
3105 static void kvm_get_kvm_shadow_mem(Object *obj, Visitor *v,
3106                                    const char *name, void *opaque,
3107                                    Error **errp)
3108 {
3109     KVMState *s = KVM_STATE(obj);
3110     int64_t value = s->kvm_shadow_mem;
3111 
3112     visit_type_int(v, name, &value, errp);
3113 }
3114 
3115 static void kvm_set_kvm_shadow_mem(Object *obj, Visitor *v,
3116                                    const char *name, void *opaque,
3117                                    Error **errp)
3118 {
3119     KVMState *s = KVM_STATE(obj);
3120     int64_t value;
3121 
3122     if (!visit_type_int(v, name, &value, errp)) {
3123         return;
3124     }
3125 
3126     s->kvm_shadow_mem = value;
3127 }
3128 
3129 static void kvm_set_kernel_irqchip(Object *obj, Visitor *v,
3130                                    const char *name, void *opaque,
3131                                    Error **errp)
3132 {
3133     KVMState *s = KVM_STATE(obj);
3134     OnOffSplit mode;
3135 
3136     if (!visit_type_OnOffSplit(v, name, &mode, errp)) {
3137         return;
3138     }
3139     switch (mode) {
3140     case ON_OFF_SPLIT_ON:
3141         s->kernel_irqchip_allowed = true;
3142         s->kernel_irqchip_required = true;
3143         s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3144         break;
3145     case ON_OFF_SPLIT_OFF:
3146         s->kernel_irqchip_allowed = false;
3147         s->kernel_irqchip_required = false;
3148         s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3149         break;
3150     case ON_OFF_SPLIT_SPLIT:
3151         s->kernel_irqchip_allowed = true;
3152         s->kernel_irqchip_required = true;
3153         s->kernel_irqchip_split = ON_OFF_AUTO_ON;
3154         break;
3155     default:
3156         /* The value was checked in visit_type_OnOffSplit() above. If
3157          * we get here, then something is wrong in QEMU.
3158          */
3159         abort();
3160     }
3161 }
3162 
3163 bool kvm_kernel_irqchip_allowed(void)
3164 {
3165     return kvm_state->kernel_irqchip_allowed;
3166 }
3167 
3168 bool kvm_kernel_irqchip_required(void)
3169 {
3170     return kvm_state->kernel_irqchip_required;
3171 }
3172 
3173 bool kvm_kernel_irqchip_split(void)
3174 {
3175     return kvm_state->kernel_irqchip_split == ON_OFF_AUTO_ON;
3176 }
3177 
3178 static void kvm_accel_instance_init(Object *obj)
3179 {
3180     KVMState *s = KVM_STATE(obj);
3181 
3182     s->kvm_shadow_mem = -1;
3183     s->kernel_irqchip_allowed = true;
3184     s->kernel_irqchip_split = ON_OFF_AUTO_AUTO;
3185 }
3186 
3187 static void kvm_accel_class_init(ObjectClass *oc, void *data)
3188 {
3189     AccelClass *ac = ACCEL_CLASS(oc);
3190     ac->name = "KVM";
3191     ac->init_machine = kvm_init;
3192     ac->has_memory = kvm_accel_has_memory;
3193     ac->allowed = &kvm_allowed;
3194 
3195     object_class_property_add(oc, "kernel-irqchip", "on|off|split",
3196         NULL, kvm_set_kernel_irqchip,
3197         NULL, NULL);
3198     object_class_property_set_description(oc, "kernel-irqchip",
3199         "Configure KVM in-kernel irqchip");
3200 
3201     object_class_property_add(oc, "kvm-shadow-mem", "int",
3202         kvm_get_kvm_shadow_mem, kvm_set_kvm_shadow_mem,
3203         NULL, NULL);
3204     object_class_property_set_description(oc, "kvm-shadow-mem",
3205         "KVM shadow MMU size");
3206 }
3207 
3208 static const TypeInfo kvm_accel_type = {
3209     .name = TYPE_KVM_ACCEL,
3210     .parent = TYPE_ACCEL,
3211     .instance_init = kvm_accel_instance_init,
3212     .class_init = kvm_accel_class_init,
3213     .instance_size = sizeof(KVMState),
3214 };
3215 
3216 static void kvm_type_init(void)
3217 {
3218     type_register_static(&kvm_accel_type);
3219 }
3220 
3221 type_init(kvm_type_init);
3222