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