xref: /openbmc/qemu/accel/kvm/kvm-all.c (revision 89de4b91)
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-common.h"
22 #include "qemu/atomic.h"
23 #include "qemu/option.h"
24 #include "qemu/config-file.h"
25 #include "qemu/error-report.h"
26 #include "qapi/error.h"
27 #include "hw/hw.h"
28 #include "hw/pci/msi.h"
29 #include "hw/pci/msix.h"
30 #include "hw/s390x/adapter.h"
31 #include "exec/gdbstub.h"
32 #include "sysemu/kvm_int.h"
33 #include "sysemu/cpus.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 "trace.h"
40 #include "hw/irq.h"
41 
42 #include "hw/boards.h"
43 
44 /* This check must be after config-host.h is included */
45 #ifdef CONFIG_EVENTFD
46 #include <sys/eventfd.h>
47 #endif
48 
49 /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
50  * need to use the real host PAGE_SIZE, as that's what KVM will use.
51  */
52 #define PAGE_SIZE getpagesize()
53 
54 //#define DEBUG_KVM
55 
56 #ifdef DEBUG_KVM
57 #define DPRINTF(fmt, ...) \
58     do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
59 #else
60 #define DPRINTF(fmt, ...) \
61     do { } while (0)
62 #endif
63 
64 #define KVM_MSI_HASHTAB_SIZE    256
65 
66 struct KVMParkedVcpu {
67     unsigned long vcpu_id;
68     int kvm_fd;
69     QLIST_ENTRY(KVMParkedVcpu) node;
70 };
71 
72 struct KVMState
73 {
74     AccelState parent_obj;
75 
76     int nr_slots;
77     int fd;
78     int vmfd;
79     int coalesced_mmio;
80     struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
81     bool coalesced_flush_in_progress;
82     int vcpu_events;
83     int robust_singlestep;
84     int debugregs;
85 #ifdef KVM_CAP_SET_GUEST_DEBUG
86     struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
87 #endif
88     int many_ioeventfds;
89     int intx_set_mask;
90     /* The man page (and posix) say ioctl numbers are signed int, but
91      * they're not.  Linux, glibc and *BSD all treat ioctl numbers as
92      * unsigned, and treating them as signed here can break things */
93     unsigned irq_set_ioctl;
94     unsigned int sigmask_len;
95     GHashTable *gsimap;
96 #ifdef KVM_CAP_IRQ_ROUTING
97     struct kvm_irq_routing *irq_routes;
98     int nr_allocated_irq_routes;
99     unsigned long *used_gsi_bitmap;
100     unsigned int gsi_count;
101     QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
102 #endif
103     KVMMemoryListener memory_listener;
104     QLIST_HEAD(, KVMParkedVcpu) kvm_parked_vcpus;
105 };
106 
107 KVMState *kvm_state;
108 bool kvm_kernel_irqchip;
109 bool kvm_split_irqchip;
110 bool kvm_async_interrupts_allowed;
111 bool kvm_halt_in_kernel_allowed;
112 bool kvm_eventfds_allowed;
113 bool kvm_irqfds_allowed;
114 bool kvm_resamplefds_allowed;
115 bool kvm_msi_via_irqfd_allowed;
116 bool kvm_gsi_routing_allowed;
117 bool kvm_gsi_direct_mapping;
118 bool kvm_allowed;
119 bool kvm_readonly_mem_allowed;
120 bool kvm_vm_attributes_allowed;
121 bool kvm_direct_msi_allowed;
122 bool kvm_ioeventfd_any_length_allowed;
123 bool kvm_msi_use_devid;
124 static bool kvm_immediate_exit;
125 
126 static const KVMCapabilityInfo kvm_required_capabilites[] = {
127     KVM_CAP_INFO(USER_MEMORY),
128     KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
129     KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS),
130     KVM_CAP_LAST_INFO
131 };
132 
133 int kvm_get_max_memslots(void)
134 {
135     KVMState *s = KVM_STATE(current_machine->accelerator);
136 
137     return s->nr_slots;
138 }
139 
140 static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
141 {
142     KVMState *s = kvm_state;
143     int i;
144 
145     for (i = 0; i < s->nr_slots; i++) {
146         if (kml->slots[i].memory_size == 0) {
147             return &kml->slots[i];
148         }
149     }
150 
151     return NULL;
152 }
153 
154 bool kvm_has_free_slot(MachineState *ms)
155 {
156     KVMState *s = KVM_STATE(ms->accelerator);
157 
158     return kvm_get_free_slot(&s->memory_listener);
159 }
160 
161 static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
162 {
163     KVMSlot *slot = kvm_get_free_slot(kml);
164 
165     if (slot) {
166         return slot;
167     }
168 
169     fprintf(stderr, "%s: no free slot available\n", __func__);
170     abort();
171 }
172 
173 static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
174                                          hwaddr start_addr,
175                                          hwaddr end_addr)
176 {
177     KVMState *s = kvm_state;
178     int i;
179 
180     for (i = 0; i < s->nr_slots; i++) {
181         KVMSlot *mem = &kml->slots[i];
182 
183         if (start_addr == mem->start_addr &&
184             end_addr == mem->start_addr + mem->memory_size) {
185             return mem;
186         }
187     }
188 
189     return NULL;
190 }
191 
192 /*
193  * Find overlapping slot with lowest start address
194  */
195 static KVMSlot *kvm_lookup_overlapping_slot(KVMMemoryListener *kml,
196                                             hwaddr start_addr,
197                                             hwaddr end_addr)
198 {
199     KVMState *s = kvm_state;
200     KVMSlot *found = NULL;
201     int i;
202 
203     for (i = 0; i < s->nr_slots; i++) {
204         KVMSlot *mem = &kml->slots[i];
205 
206         if (mem->memory_size == 0 ||
207             (found && found->start_addr < mem->start_addr)) {
208             continue;
209         }
210 
211         if (end_addr > mem->start_addr &&
212             start_addr < mem->start_addr + mem->memory_size) {
213             found = mem;
214         }
215     }
216 
217     return found;
218 }
219 
220 int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
221                                        hwaddr *phys_addr)
222 {
223     KVMMemoryListener *kml = &s->memory_listener;
224     int i;
225 
226     for (i = 0; i < s->nr_slots; i++) {
227         KVMSlot *mem = &kml->slots[i];
228 
229         if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
230             *phys_addr = mem->start_addr + (ram - mem->ram);
231             return 1;
232         }
233     }
234 
235     return 0;
236 }
237 
238 static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot)
239 {
240     KVMState *s = kvm_state;
241     struct kvm_userspace_memory_region mem;
242 
243     mem.slot = slot->slot | (kml->as_id << 16);
244     mem.guest_phys_addr = slot->start_addr;
245     mem.userspace_addr = (unsigned long)slot->ram;
246     mem.flags = slot->flags;
247 
248     if (slot->memory_size && mem.flags & KVM_MEM_READONLY) {
249         /* Set the slot size to 0 before setting the slot to the desired
250          * value. This is needed based on KVM commit 75d61fbc. */
251         mem.memory_size = 0;
252         kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
253     }
254     mem.memory_size = slot->memory_size;
255     return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
256 }
257 
258 int kvm_destroy_vcpu(CPUState *cpu)
259 {
260     KVMState *s = kvm_state;
261     long mmap_size;
262     struct KVMParkedVcpu *vcpu = NULL;
263     int ret = 0;
264 
265     DPRINTF("kvm_destroy_vcpu\n");
266 
267     mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
268     if (mmap_size < 0) {
269         ret = mmap_size;
270         DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
271         goto err;
272     }
273 
274     ret = munmap(cpu->kvm_run, mmap_size);
275     if (ret < 0) {
276         goto err;
277     }
278 
279     vcpu = g_malloc0(sizeof(*vcpu));
280     vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
281     vcpu->kvm_fd = cpu->kvm_fd;
282     QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
283 err:
284     return ret;
285 }
286 
287 static int kvm_get_vcpu(KVMState *s, unsigned long vcpu_id)
288 {
289     struct KVMParkedVcpu *cpu;
290 
291     QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
292         if (cpu->vcpu_id == vcpu_id) {
293             int kvm_fd;
294 
295             QLIST_REMOVE(cpu, node);
296             kvm_fd = cpu->kvm_fd;
297             g_free(cpu);
298             return kvm_fd;
299         }
300     }
301 
302     return kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)vcpu_id);
303 }
304 
305 int kvm_init_vcpu(CPUState *cpu)
306 {
307     KVMState *s = kvm_state;
308     long mmap_size;
309     int ret;
310 
311     DPRINTF("kvm_init_vcpu\n");
312 
313     ret = kvm_get_vcpu(s, kvm_arch_vcpu_id(cpu));
314     if (ret < 0) {
315         DPRINTF("kvm_create_vcpu failed\n");
316         goto err;
317     }
318 
319     cpu->kvm_fd = ret;
320     cpu->kvm_state = s;
321     cpu->vcpu_dirty = true;
322 
323     mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
324     if (mmap_size < 0) {
325         ret = mmap_size;
326         DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
327         goto err;
328     }
329 
330     cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
331                         cpu->kvm_fd, 0);
332     if (cpu->kvm_run == MAP_FAILED) {
333         ret = -errno;
334         DPRINTF("mmap'ing vcpu state failed\n");
335         goto err;
336     }
337 
338     if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
339         s->coalesced_mmio_ring =
340             (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
341     }
342 
343     ret = kvm_arch_init_vcpu(cpu);
344 err:
345     return ret;
346 }
347 
348 /*
349  * dirty pages logging control
350  */
351 
352 static int kvm_mem_flags(MemoryRegion *mr)
353 {
354     bool readonly = mr->readonly || memory_region_is_romd(mr);
355     int flags = 0;
356 
357     if (memory_region_get_dirty_log_mask(mr) != 0) {
358         flags |= KVM_MEM_LOG_DIRTY_PAGES;
359     }
360     if (readonly && kvm_readonly_mem_allowed) {
361         flags |= KVM_MEM_READONLY;
362     }
363     return flags;
364 }
365 
366 static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
367                                  MemoryRegion *mr)
368 {
369     int old_flags;
370 
371     old_flags = mem->flags;
372     mem->flags = kvm_mem_flags(mr);
373 
374     /* If nothing changed effectively, no need to issue ioctl */
375     if (mem->flags == old_flags) {
376         return 0;
377     }
378 
379     return kvm_set_user_memory_region(kml, mem);
380 }
381 
382 static int kvm_section_update_flags(KVMMemoryListener *kml,
383                                     MemoryRegionSection *section)
384 {
385     hwaddr phys_addr = section->offset_within_address_space;
386     ram_addr_t size = int128_get64(section->size);
387     KVMSlot *mem = kvm_lookup_matching_slot(kml, phys_addr, phys_addr + size);
388 
389     if (mem == NULL)  {
390         return 0;
391     } else {
392         return kvm_slot_update_flags(kml, mem, section->mr);
393     }
394 }
395 
396 static void kvm_log_start(MemoryListener *listener,
397                           MemoryRegionSection *section,
398                           int old, int new)
399 {
400     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
401     int r;
402 
403     if (old != 0) {
404         return;
405     }
406 
407     r = kvm_section_update_flags(kml, section);
408     if (r < 0) {
409         abort();
410     }
411 }
412 
413 static void kvm_log_stop(MemoryListener *listener,
414                           MemoryRegionSection *section,
415                           int old, int new)
416 {
417     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
418     int r;
419 
420     if (new != 0) {
421         return;
422     }
423 
424     r = kvm_section_update_flags(kml, section);
425     if (r < 0) {
426         abort();
427     }
428 }
429 
430 /* get kvm's dirty pages bitmap and update qemu's */
431 static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
432                                          unsigned long *bitmap)
433 {
434     ram_addr_t start = section->offset_within_region +
435                        memory_region_get_ram_addr(section->mr);
436     ram_addr_t pages = int128_get64(section->size) / getpagesize();
437 
438     cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
439     return 0;
440 }
441 
442 #define ALIGN(x, y)  (((x)+(y)-1) & ~((y)-1))
443 
444 /**
445  * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
446  * This function updates qemu's dirty bitmap using
447  * memory_region_set_dirty().  This means all bits are set
448  * to dirty.
449  *
450  * @start_add: start of logged region.
451  * @end_addr: end of logged region.
452  */
453 static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
454                                           MemoryRegionSection *section)
455 {
456     KVMState *s = kvm_state;
457     unsigned long size, allocated_size = 0;
458     struct kvm_dirty_log d = {};
459     KVMSlot *mem;
460     int ret = 0;
461     hwaddr start_addr = section->offset_within_address_space;
462     hwaddr end_addr = start_addr + int128_get64(section->size);
463 
464     d.dirty_bitmap = NULL;
465     while (start_addr < end_addr) {
466         mem = kvm_lookup_overlapping_slot(kml, start_addr, end_addr);
467         if (mem == NULL) {
468             break;
469         }
470 
471         /* XXX bad kernel interface alert
472          * For dirty bitmap, kernel allocates array of size aligned to
473          * bits-per-long.  But for case when the kernel is 64bits and
474          * the userspace is 32bits, userspace can't align to the same
475          * bits-per-long, since sizeof(long) is different between kernel
476          * and user space.  This way, userspace will provide buffer which
477          * may be 4 bytes less than the kernel will use, resulting in
478          * userspace memory corruption (which is not detectable by valgrind
479          * too, in most cases).
480          * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
481          * a hope that sizeof(long) won't become >8 any time soon.
482          */
483         size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
484                      /*HOST_LONG_BITS*/ 64) / 8;
485         if (!d.dirty_bitmap) {
486             d.dirty_bitmap = g_malloc(size);
487         } else if (size > allocated_size) {
488             d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
489         }
490         allocated_size = size;
491         memset(d.dirty_bitmap, 0, allocated_size);
492 
493         d.slot = mem->slot | (kml->as_id << 16);
494         if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
495             DPRINTF("ioctl failed %d\n", errno);
496             ret = -1;
497             break;
498         }
499 
500         kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
501         start_addr = mem->start_addr + mem->memory_size;
502     }
503     g_free(d.dirty_bitmap);
504 
505     return ret;
506 }
507 
508 static void kvm_coalesce_mmio_region(MemoryListener *listener,
509                                      MemoryRegionSection *secion,
510                                      hwaddr start, hwaddr size)
511 {
512     KVMState *s = kvm_state;
513 
514     if (s->coalesced_mmio) {
515         struct kvm_coalesced_mmio_zone zone;
516 
517         zone.addr = start;
518         zone.size = size;
519         zone.pad = 0;
520 
521         (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
522     }
523 }
524 
525 static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
526                                        MemoryRegionSection *secion,
527                                        hwaddr start, hwaddr size)
528 {
529     KVMState *s = kvm_state;
530 
531     if (s->coalesced_mmio) {
532         struct kvm_coalesced_mmio_zone zone;
533 
534         zone.addr = start;
535         zone.size = size;
536         zone.pad = 0;
537 
538         (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
539     }
540 }
541 
542 int kvm_check_extension(KVMState *s, unsigned int extension)
543 {
544     int ret;
545 
546     ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
547     if (ret < 0) {
548         ret = 0;
549     }
550 
551     return ret;
552 }
553 
554 int kvm_vm_check_extension(KVMState *s, unsigned int extension)
555 {
556     int ret;
557 
558     ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
559     if (ret < 0) {
560         /* VM wide version not implemented, use global one instead */
561         ret = kvm_check_extension(s, extension);
562     }
563 
564     return ret;
565 }
566 
567 static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
568 {
569 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
570     /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
571      * endianness, but the memory core hands them in target endianness.
572      * For example, PPC is always treated as big-endian even if running
573      * on KVM and on PPC64LE.  Correct here.
574      */
575     switch (size) {
576     case 2:
577         val = bswap16(val);
578         break;
579     case 4:
580         val = bswap32(val);
581         break;
582     }
583 #endif
584     return val;
585 }
586 
587 static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
588                                   bool assign, uint32_t size, bool datamatch)
589 {
590     int ret;
591     struct kvm_ioeventfd iofd = {
592         .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
593         .addr = addr,
594         .len = size,
595         .flags = 0,
596         .fd = fd,
597     };
598 
599     if (!kvm_enabled()) {
600         return -ENOSYS;
601     }
602 
603     if (datamatch) {
604         iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
605     }
606     if (!assign) {
607         iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
608     }
609 
610     ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
611 
612     if (ret < 0) {
613         return -errno;
614     }
615 
616     return 0;
617 }
618 
619 static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
620                                  bool assign, uint32_t size, bool datamatch)
621 {
622     struct kvm_ioeventfd kick = {
623         .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
624         .addr = addr,
625         .flags = KVM_IOEVENTFD_FLAG_PIO,
626         .len = size,
627         .fd = fd,
628     };
629     int r;
630     if (!kvm_enabled()) {
631         return -ENOSYS;
632     }
633     if (datamatch) {
634         kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
635     }
636     if (!assign) {
637         kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
638     }
639     r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
640     if (r < 0) {
641         return r;
642     }
643     return 0;
644 }
645 
646 
647 static int kvm_check_many_ioeventfds(void)
648 {
649     /* Userspace can use ioeventfd for io notification.  This requires a host
650      * that supports eventfd(2) and an I/O thread; since eventfd does not
651      * support SIGIO it cannot interrupt the vcpu.
652      *
653      * Older kernels have a 6 device limit on the KVM io bus.  Find out so we
654      * can avoid creating too many ioeventfds.
655      */
656 #if defined(CONFIG_EVENTFD)
657     int ioeventfds[7];
658     int i, ret = 0;
659     for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
660         ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
661         if (ioeventfds[i] < 0) {
662             break;
663         }
664         ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
665         if (ret < 0) {
666             close(ioeventfds[i]);
667             break;
668         }
669     }
670 
671     /* Decide whether many devices are supported or not */
672     ret = i == ARRAY_SIZE(ioeventfds);
673 
674     while (i-- > 0) {
675         kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
676         close(ioeventfds[i]);
677     }
678     return ret;
679 #else
680     return 0;
681 #endif
682 }
683 
684 static const KVMCapabilityInfo *
685 kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
686 {
687     while (list->name) {
688         if (!kvm_check_extension(s, list->value)) {
689             return list;
690         }
691         list++;
692     }
693     return NULL;
694 }
695 
696 static void kvm_set_phys_mem(KVMMemoryListener *kml,
697                              MemoryRegionSection *section, bool add)
698 {
699     KVMSlot *mem, old;
700     int err;
701     MemoryRegion *mr = section->mr;
702     bool writeable = !mr->readonly && !mr->rom_device;
703     hwaddr start_addr = section->offset_within_address_space;
704     ram_addr_t size = int128_get64(section->size);
705     void *ram = NULL;
706     unsigned delta;
707 
708     /* kvm works in page size chunks, but the function may be called
709        with sub-page size and unaligned start address. Pad the start
710        address to next and truncate size to previous page boundary. */
711     delta = qemu_real_host_page_size - (start_addr & ~qemu_real_host_page_mask);
712     delta &= ~qemu_real_host_page_mask;
713     if (delta > size) {
714         return;
715     }
716     start_addr += delta;
717     size -= delta;
718     size &= qemu_real_host_page_mask;
719     if (!size || (start_addr & ~qemu_real_host_page_mask)) {
720         return;
721     }
722 
723     if (!memory_region_is_ram(mr)) {
724         if (writeable || !kvm_readonly_mem_allowed) {
725             return;
726         } else if (!mr->romd_mode) {
727             /* If the memory device is not in romd_mode, then we actually want
728              * to remove the kvm memory slot so all accesses will trap. */
729             add = false;
730         }
731     }
732 
733     ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
734 
735     while (1) {
736         mem = kvm_lookup_overlapping_slot(kml, start_addr, start_addr + size);
737         if (!mem) {
738             break;
739         }
740 
741         if (add && start_addr >= mem->start_addr &&
742             (start_addr + size <= mem->start_addr + mem->memory_size) &&
743             (ram - start_addr == mem->ram - mem->start_addr)) {
744             /* The new slot fits into the existing one and comes with
745              * identical parameters - update flags and done. */
746             kvm_slot_update_flags(kml, mem, mr);
747             return;
748         }
749 
750         old = *mem;
751 
752         if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
753             kvm_physical_sync_dirty_bitmap(kml, section);
754         }
755 
756         /* unregister the overlapping slot */
757         mem->memory_size = 0;
758         err = kvm_set_user_memory_region(kml, mem);
759         if (err) {
760             fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
761                     __func__, strerror(-err));
762             abort();
763         }
764 
765         /* register prefix slot */
766         if (old.start_addr < start_addr) {
767             mem = kvm_alloc_slot(kml);
768             mem->memory_size = start_addr - old.start_addr;
769             mem->start_addr = old.start_addr;
770             mem->ram = old.ram;
771             mem->flags =  kvm_mem_flags(mr);
772 
773             err = kvm_set_user_memory_region(kml, mem);
774             if (err) {
775                 fprintf(stderr, "%s: error registering prefix slot: %s\n",
776                         __func__, strerror(-err));
777 #ifdef TARGET_PPC
778                 fprintf(stderr, "%s: This is probably because your kernel's " \
779                                 "PAGE_SIZE is too big. Please try to use 4k " \
780                                 "PAGE_SIZE!\n", __func__);
781 #endif
782                 abort();
783             }
784         }
785 
786         /* register suffix slot */
787         if (old.start_addr + old.memory_size > start_addr + size) {
788             ram_addr_t size_delta;
789 
790             mem = kvm_alloc_slot(kml);
791             mem->start_addr = start_addr + size;
792             size_delta = mem->start_addr - old.start_addr;
793             mem->memory_size = old.memory_size - size_delta;
794             mem->ram = old.ram + size_delta;
795             mem->flags = kvm_mem_flags(mr);
796 
797             err = kvm_set_user_memory_region(kml, mem);
798             if (err) {
799                 fprintf(stderr, "%s: error registering suffix slot: %s\n",
800                         __func__, strerror(-err));
801                 abort();
802             }
803         }
804     }
805 
806     if (!add) {
807         return;
808     }
809     mem = kvm_alloc_slot(kml);
810     mem->memory_size = size;
811     mem->start_addr = start_addr;
812     mem->ram = ram;
813     mem->flags = kvm_mem_flags(mr);
814 
815     err = kvm_set_user_memory_region(kml, mem);
816     if (err) {
817         fprintf(stderr, "%s: error registering slot: %s\n", __func__,
818                 strerror(-err));
819         abort();
820     }
821 }
822 
823 static void kvm_region_add(MemoryListener *listener,
824                            MemoryRegionSection *section)
825 {
826     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
827 
828     memory_region_ref(section->mr);
829     kvm_set_phys_mem(kml, section, true);
830 }
831 
832 static void kvm_region_del(MemoryListener *listener,
833                            MemoryRegionSection *section)
834 {
835     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
836 
837     kvm_set_phys_mem(kml, section, false);
838     memory_region_unref(section->mr);
839 }
840 
841 static void kvm_log_sync(MemoryListener *listener,
842                          MemoryRegionSection *section)
843 {
844     KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
845     int r;
846 
847     r = kvm_physical_sync_dirty_bitmap(kml, section);
848     if (r < 0) {
849         abort();
850     }
851 }
852 
853 static void kvm_mem_ioeventfd_add(MemoryListener *listener,
854                                   MemoryRegionSection *section,
855                                   bool match_data, uint64_t data,
856                                   EventNotifier *e)
857 {
858     int fd = event_notifier_get_fd(e);
859     int r;
860 
861     r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
862                                data, true, int128_get64(section->size),
863                                match_data);
864     if (r < 0) {
865         fprintf(stderr, "%s: error adding ioeventfd: %s\n",
866                 __func__, strerror(-r));
867         abort();
868     }
869 }
870 
871 static void kvm_mem_ioeventfd_del(MemoryListener *listener,
872                                   MemoryRegionSection *section,
873                                   bool match_data, uint64_t data,
874                                   EventNotifier *e)
875 {
876     int fd = event_notifier_get_fd(e);
877     int r;
878 
879     r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
880                                data, false, int128_get64(section->size),
881                                match_data);
882     if (r < 0) {
883         abort();
884     }
885 }
886 
887 static void kvm_io_ioeventfd_add(MemoryListener *listener,
888                                  MemoryRegionSection *section,
889                                  bool match_data, uint64_t data,
890                                  EventNotifier *e)
891 {
892     int fd = event_notifier_get_fd(e);
893     int r;
894 
895     r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
896                               data, true, int128_get64(section->size),
897                               match_data);
898     if (r < 0) {
899         fprintf(stderr, "%s: error adding ioeventfd: %s\n",
900                 __func__, strerror(-r));
901         abort();
902     }
903 }
904 
905 static void kvm_io_ioeventfd_del(MemoryListener *listener,
906                                  MemoryRegionSection *section,
907                                  bool match_data, uint64_t data,
908                                  EventNotifier *e)
909 
910 {
911     int fd = event_notifier_get_fd(e);
912     int r;
913 
914     r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
915                               data, false, int128_get64(section->size),
916                               match_data);
917     if (r < 0) {
918         abort();
919     }
920 }
921 
922 void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
923                                   AddressSpace *as, int as_id)
924 {
925     int i;
926 
927     kml->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
928     kml->as_id = as_id;
929 
930     for (i = 0; i < s->nr_slots; i++) {
931         kml->slots[i].slot = i;
932     }
933 
934     kml->listener.region_add = kvm_region_add;
935     kml->listener.region_del = kvm_region_del;
936     kml->listener.log_start = kvm_log_start;
937     kml->listener.log_stop = kvm_log_stop;
938     kml->listener.log_sync = kvm_log_sync;
939     kml->listener.priority = 10;
940 
941     memory_listener_register(&kml->listener, as);
942 }
943 
944 static MemoryListener kvm_io_listener = {
945     .eventfd_add = kvm_io_ioeventfd_add,
946     .eventfd_del = kvm_io_ioeventfd_del,
947     .priority = 10,
948 };
949 
950 int kvm_set_irq(KVMState *s, int irq, int level)
951 {
952     struct kvm_irq_level event;
953     int ret;
954 
955     assert(kvm_async_interrupts_enabled());
956 
957     event.level = level;
958     event.irq = irq;
959     ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
960     if (ret < 0) {
961         perror("kvm_set_irq");
962         abort();
963     }
964 
965     return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
966 }
967 
968 #ifdef KVM_CAP_IRQ_ROUTING
969 typedef struct KVMMSIRoute {
970     struct kvm_irq_routing_entry kroute;
971     QTAILQ_ENTRY(KVMMSIRoute) entry;
972 } KVMMSIRoute;
973 
974 static void set_gsi(KVMState *s, unsigned int gsi)
975 {
976     set_bit(gsi, s->used_gsi_bitmap);
977 }
978 
979 static void clear_gsi(KVMState *s, unsigned int gsi)
980 {
981     clear_bit(gsi, s->used_gsi_bitmap);
982 }
983 
984 void kvm_init_irq_routing(KVMState *s)
985 {
986     int gsi_count, i;
987 
988     gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
989     if (gsi_count > 0) {
990         /* Round up so we can search ints using ffs */
991         s->used_gsi_bitmap = bitmap_new(gsi_count);
992         s->gsi_count = gsi_count;
993     }
994 
995     s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
996     s->nr_allocated_irq_routes = 0;
997 
998     if (!kvm_direct_msi_allowed) {
999         for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
1000             QTAILQ_INIT(&s->msi_hashtab[i]);
1001         }
1002     }
1003 
1004     kvm_arch_init_irq_routing(s);
1005 }
1006 
1007 void kvm_irqchip_commit_routes(KVMState *s)
1008 {
1009     int ret;
1010 
1011     if (kvm_gsi_direct_mapping()) {
1012         return;
1013     }
1014 
1015     if (!kvm_gsi_routing_enabled()) {
1016         return;
1017     }
1018 
1019     s->irq_routes->flags = 0;
1020     trace_kvm_irqchip_commit_routes();
1021     ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1022     assert(ret == 0);
1023 }
1024 
1025 static void kvm_add_routing_entry(KVMState *s,
1026                                   struct kvm_irq_routing_entry *entry)
1027 {
1028     struct kvm_irq_routing_entry *new;
1029     int n, size;
1030 
1031     if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1032         n = s->nr_allocated_irq_routes * 2;
1033         if (n < 64) {
1034             n = 64;
1035         }
1036         size = sizeof(struct kvm_irq_routing);
1037         size += n * sizeof(*new);
1038         s->irq_routes = g_realloc(s->irq_routes, size);
1039         s->nr_allocated_irq_routes = n;
1040     }
1041     n = s->irq_routes->nr++;
1042     new = &s->irq_routes->entries[n];
1043 
1044     *new = *entry;
1045 
1046     set_gsi(s, entry->gsi);
1047 }
1048 
1049 static int kvm_update_routing_entry(KVMState *s,
1050                                     struct kvm_irq_routing_entry *new_entry)
1051 {
1052     struct kvm_irq_routing_entry *entry;
1053     int n;
1054 
1055     for (n = 0; n < s->irq_routes->nr; n++) {
1056         entry = &s->irq_routes->entries[n];
1057         if (entry->gsi != new_entry->gsi) {
1058             continue;
1059         }
1060 
1061         if(!memcmp(entry, new_entry, sizeof *entry)) {
1062             return 0;
1063         }
1064 
1065         *entry = *new_entry;
1066 
1067         return 0;
1068     }
1069 
1070     return -ESRCH;
1071 }
1072 
1073 void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1074 {
1075     struct kvm_irq_routing_entry e = {};
1076 
1077     assert(pin < s->gsi_count);
1078 
1079     e.gsi = irq;
1080     e.type = KVM_IRQ_ROUTING_IRQCHIP;
1081     e.flags = 0;
1082     e.u.irqchip.irqchip = irqchip;
1083     e.u.irqchip.pin = pin;
1084     kvm_add_routing_entry(s, &e);
1085 }
1086 
1087 void kvm_irqchip_release_virq(KVMState *s, int virq)
1088 {
1089     struct kvm_irq_routing_entry *e;
1090     int i;
1091 
1092     if (kvm_gsi_direct_mapping()) {
1093         return;
1094     }
1095 
1096     for (i = 0; i < s->irq_routes->nr; i++) {
1097         e = &s->irq_routes->entries[i];
1098         if (e->gsi == virq) {
1099             s->irq_routes->nr--;
1100             *e = s->irq_routes->entries[s->irq_routes->nr];
1101         }
1102     }
1103     clear_gsi(s, virq);
1104     kvm_arch_release_virq_post(virq);
1105     trace_kvm_irqchip_release_virq(virq);
1106 }
1107 
1108 static unsigned int kvm_hash_msi(uint32_t data)
1109 {
1110     /* This is optimized for IA32 MSI layout. However, no other arch shall
1111      * repeat the mistake of not providing a direct MSI injection API. */
1112     return data & 0xff;
1113 }
1114 
1115 static void kvm_flush_dynamic_msi_routes(KVMState *s)
1116 {
1117     KVMMSIRoute *route, *next;
1118     unsigned int hash;
1119 
1120     for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1121         QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1122             kvm_irqchip_release_virq(s, route->kroute.gsi);
1123             QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1124             g_free(route);
1125         }
1126     }
1127 }
1128 
1129 static int kvm_irqchip_get_virq(KVMState *s)
1130 {
1131     int next_virq;
1132 
1133     /*
1134      * PIC and IOAPIC share the first 16 GSI numbers, thus the available
1135      * GSI numbers are more than the number of IRQ route. Allocating a GSI
1136      * number can succeed even though a new route entry cannot be added.
1137      * When this happens, flush dynamic MSI entries to free IRQ route entries.
1138      */
1139     if (!kvm_direct_msi_allowed && s->irq_routes->nr == s->gsi_count) {
1140         kvm_flush_dynamic_msi_routes(s);
1141     }
1142 
1143     /* Return the lowest unused GSI in the bitmap */
1144     next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
1145     if (next_virq >= s->gsi_count) {
1146         return -ENOSPC;
1147     } else {
1148         return next_virq;
1149     }
1150 }
1151 
1152 static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1153 {
1154     unsigned int hash = kvm_hash_msi(msg.data);
1155     KVMMSIRoute *route;
1156 
1157     QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1158         if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1159             route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1160             route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1161             return route;
1162         }
1163     }
1164     return NULL;
1165 }
1166 
1167 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1168 {
1169     struct kvm_msi msi;
1170     KVMMSIRoute *route;
1171 
1172     if (kvm_direct_msi_allowed) {
1173         msi.address_lo = (uint32_t)msg.address;
1174         msi.address_hi = msg.address >> 32;
1175         msi.data = le32_to_cpu(msg.data);
1176         msi.flags = 0;
1177         memset(msi.pad, 0, sizeof(msi.pad));
1178 
1179         return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1180     }
1181 
1182     route = kvm_lookup_msi_route(s, msg);
1183     if (!route) {
1184         int virq;
1185 
1186         virq = kvm_irqchip_get_virq(s);
1187         if (virq < 0) {
1188             return virq;
1189         }
1190 
1191         route = g_malloc0(sizeof(KVMMSIRoute));
1192         route->kroute.gsi = virq;
1193         route->kroute.type = KVM_IRQ_ROUTING_MSI;
1194         route->kroute.flags = 0;
1195         route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1196         route->kroute.u.msi.address_hi = msg.address >> 32;
1197         route->kroute.u.msi.data = le32_to_cpu(msg.data);
1198 
1199         kvm_add_routing_entry(s, &route->kroute);
1200         kvm_irqchip_commit_routes(s);
1201 
1202         QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1203                            entry);
1204     }
1205 
1206     assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1207 
1208     return kvm_set_irq(s, route->kroute.gsi, 1);
1209 }
1210 
1211 int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
1212 {
1213     struct kvm_irq_routing_entry kroute = {};
1214     int virq;
1215     MSIMessage msg = {0, 0};
1216 
1217     if (pci_available && dev) {
1218         msg = pci_get_msi_message(dev, vector);
1219     }
1220 
1221     if (kvm_gsi_direct_mapping()) {
1222         return kvm_arch_msi_data_to_gsi(msg.data);
1223     }
1224 
1225     if (!kvm_gsi_routing_enabled()) {
1226         return -ENOSYS;
1227     }
1228 
1229     virq = kvm_irqchip_get_virq(s);
1230     if (virq < 0) {
1231         return virq;
1232     }
1233 
1234     kroute.gsi = virq;
1235     kroute.type = KVM_IRQ_ROUTING_MSI;
1236     kroute.flags = 0;
1237     kroute.u.msi.address_lo = (uint32_t)msg.address;
1238     kroute.u.msi.address_hi = msg.address >> 32;
1239     kroute.u.msi.data = le32_to_cpu(msg.data);
1240     if (pci_available && kvm_msi_devid_required()) {
1241         kroute.flags = KVM_MSI_VALID_DEVID;
1242         kroute.u.msi.devid = pci_requester_id(dev);
1243     }
1244     if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1245         kvm_irqchip_release_virq(s, virq);
1246         return -EINVAL;
1247     }
1248 
1249     trace_kvm_irqchip_add_msi_route(dev ? dev->name : (char *)"N/A",
1250                                     vector, virq);
1251 
1252     kvm_add_routing_entry(s, &kroute);
1253     kvm_arch_add_msi_route_post(&kroute, vector, dev);
1254     kvm_irqchip_commit_routes(s);
1255 
1256     return virq;
1257 }
1258 
1259 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
1260                                  PCIDevice *dev)
1261 {
1262     struct kvm_irq_routing_entry kroute = {};
1263 
1264     if (kvm_gsi_direct_mapping()) {
1265         return 0;
1266     }
1267 
1268     if (!kvm_irqchip_in_kernel()) {
1269         return -ENOSYS;
1270     }
1271 
1272     kroute.gsi = virq;
1273     kroute.type = KVM_IRQ_ROUTING_MSI;
1274     kroute.flags = 0;
1275     kroute.u.msi.address_lo = (uint32_t)msg.address;
1276     kroute.u.msi.address_hi = msg.address >> 32;
1277     kroute.u.msi.data = le32_to_cpu(msg.data);
1278     if (pci_available && kvm_msi_devid_required()) {
1279         kroute.flags = KVM_MSI_VALID_DEVID;
1280         kroute.u.msi.devid = pci_requester_id(dev);
1281     }
1282     if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
1283         return -EINVAL;
1284     }
1285 
1286     trace_kvm_irqchip_update_msi_route(virq);
1287 
1288     return kvm_update_routing_entry(s, &kroute);
1289 }
1290 
1291 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int rfd, int virq,
1292                                     bool assign)
1293 {
1294     struct kvm_irqfd irqfd = {
1295         .fd = fd,
1296         .gsi = virq,
1297         .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1298     };
1299 
1300     if (rfd != -1) {
1301         irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1302         irqfd.resamplefd = rfd;
1303     }
1304 
1305     if (!kvm_irqfds_enabled()) {
1306         return -ENOSYS;
1307     }
1308 
1309     return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1310 }
1311 
1312 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1313 {
1314     struct kvm_irq_routing_entry kroute = {};
1315     int virq;
1316 
1317     if (!kvm_gsi_routing_enabled()) {
1318         return -ENOSYS;
1319     }
1320 
1321     virq = kvm_irqchip_get_virq(s);
1322     if (virq < 0) {
1323         return virq;
1324     }
1325 
1326     kroute.gsi = virq;
1327     kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1328     kroute.flags = 0;
1329     kroute.u.adapter.summary_addr = adapter->summary_addr;
1330     kroute.u.adapter.ind_addr = adapter->ind_addr;
1331     kroute.u.adapter.summary_offset = adapter->summary_offset;
1332     kroute.u.adapter.ind_offset = adapter->ind_offset;
1333     kroute.u.adapter.adapter_id = adapter->adapter_id;
1334 
1335     kvm_add_routing_entry(s, &kroute);
1336 
1337     return virq;
1338 }
1339 
1340 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1341 {
1342     struct kvm_irq_routing_entry kroute = {};
1343     int virq;
1344 
1345     if (!kvm_gsi_routing_enabled()) {
1346         return -ENOSYS;
1347     }
1348     if (!kvm_check_extension(s, KVM_CAP_HYPERV_SYNIC)) {
1349         return -ENOSYS;
1350     }
1351     virq = kvm_irqchip_get_virq(s);
1352     if (virq < 0) {
1353         return virq;
1354     }
1355 
1356     kroute.gsi = virq;
1357     kroute.type = KVM_IRQ_ROUTING_HV_SINT;
1358     kroute.flags = 0;
1359     kroute.u.hv_sint.vcpu = vcpu;
1360     kroute.u.hv_sint.sint = sint;
1361 
1362     kvm_add_routing_entry(s, &kroute);
1363     kvm_irqchip_commit_routes(s);
1364 
1365     return virq;
1366 }
1367 
1368 #else /* !KVM_CAP_IRQ_ROUTING */
1369 
1370 void kvm_init_irq_routing(KVMState *s)
1371 {
1372 }
1373 
1374 void kvm_irqchip_release_virq(KVMState *s, int virq)
1375 {
1376 }
1377 
1378 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1379 {
1380     abort();
1381 }
1382 
1383 int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
1384 {
1385     return -ENOSYS;
1386 }
1387 
1388 int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1389 {
1390     return -ENOSYS;
1391 }
1392 
1393 int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
1394 {
1395     return -ENOSYS;
1396 }
1397 
1398 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1399 {
1400     abort();
1401 }
1402 
1403 int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1404 {
1405     return -ENOSYS;
1406 }
1407 #endif /* !KVM_CAP_IRQ_ROUTING */
1408 
1409 int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1410                                        EventNotifier *rn, int virq)
1411 {
1412     return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n),
1413            rn ? event_notifier_get_fd(rn) : -1, virq, true);
1414 }
1415 
1416 int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
1417                                           int virq)
1418 {
1419     return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), -1, virq,
1420            false);
1421 }
1422 
1423 int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1424                                    EventNotifier *rn, qemu_irq irq)
1425 {
1426     gpointer key, gsi;
1427     gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1428 
1429     if (!found) {
1430         return -ENXIO;
1431     }
1432     return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
1433 }
1434 
1435 int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
1436                                       qemu_irq irq)
1437 {
1438     gpointer key, gsi;
1439     gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
1440 
1441     if (!found) {
1442         return -ENXIO;
1443     }
1444     return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
1445 }
1446 
1447 void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
1448 {
1449     g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
1450 }
1451 
1452 static void kvm_irqchip_create(MachineState *machine, KVMState *s)
1453 {
1454     int ret;
1455 
1456     if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
1457         ;
1458     } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
1459         ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
1460         if (ret < 0) {
1461             fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
1462             exit(1);
1463         }
1464     } else {
1465         return;
1466     }
1467 
1468     /* First probe and see if there's a arch-specific hook to create the
1469      * in-kernel irqchip for us */
1470     ret = kvm_arch_irqchip_create(machine, s);
1471     if (ret == 0) {
1472         if (machine_kernel_irqchip_split(machine)) {
1473             perror("Split IRQ chip mode not supported.");
1474             exit(1);
1475         } else {
1476             ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1477         }
1478     }
1479     if (ret < 0) {
1480         fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
1481         exit(1);
1482     }
1483 
1484     kvm_kernel_irqchip = true;
1485     /* If we have an in-kernel IRQ chip then we must have asynchronous
1486      * interrupt delivery (though the reverse is not necessarily true)
1487      */
1488     kvm_async_interrupts_allowed = true;
1489     kvm_halt_in_kernel_allowed = true;
1490 
1491     kvm_init_irq_routing(s);
1492 
1493     s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
1494 }
1495 
1496 /* Find number of supported CPUs using the recommended
1497  * procedure from the kernel API documentation to cope with
1498  * older kernels that may be missing capabilities.
1499  */
1500 static int kvm_recommended_vcpus(KVMState *s)
1501 {
1502     int ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
1503     return (ret) ? ret : 4;
1504 }
1505 
1506 static int kvm_max_vcpus(KVMState *s)
1507 {
1508     int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1509     return (ret) ? ret : kvm_recommended_vcpus(s);
1510 }
1511 
1512 static int kvm_max_vcpu_id(KVMState *s)
1513 {
1514     int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
1515     return (ret) ? ret : kvm_max_vcpus(s);
1516 }
1517 
1518 bool kvm_vcpu_id_is_valid(int vcpu_id)
1519 {
1520     KVMState *s = KVM_STATE(current_machine->accelerator);
1521     return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
1522 }
1523 
1524 static int kvm_init(MachineState *ms)
1525 {
1526     MachineClass *mc = MACHINE_GET_CLASS(ms);
1527     static const char upgrade_note[] =
1528         "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1529         "(see http://sourceforge.net/projects/kvm).\n";
1530     struct {
1531         const char *name;
1532         int num;
1533     } num_cpus[] = {
1534         { "SMP",          smp_cpus },
1535         { "hotpluggable", max_cpus },
1536         { NULL, }
1537     }, *nc = num_cpus;
1538     int soft_vcpus_limit, hard_vcpus_limit;
1539     KVMState *s;
1540     const KVMCapabilityInfo *missing_cap;
1541     int ret;
1542     int type = 0;
1543     const char *kvm_type;
1544 
1545     s = KVM_STATE(ms->accelerator);
1546 
1547     /*
1548      * On systems where the kernel can support different base page
1549      * sizes, host page size may be different from TARGET_PAGE_SIZE,
1550      * even with KVM.  TARGET_PAGE_SIZE is assumed to be the minimum
1551      * page size for the system though.
1552      */
1553     assert(TARGET_PAGE_SIZE <= getpagesize());
1554 
1555     s->sigmask_len = 8;
1556 
1557 #ifdef KVM_CAP_SET_GUEST_DEBUG
1558     QTAILQ_INIT(&s->kvm_sw_breakpoints);
1559 #endif
1560     QLIST_INIT(&s->kvm_parked_vcpus);
1561     s->vmfd = -1;
1562     s->fd = qemu_open("/dev/kvm", O_RDWR);
1563     if (s->fd == -1) {
1564         fprintf(stderr, "Could not access KVM kernel module: %m\n");
1565         ret = -errno;
1566         goto err;
1567     }
1568 
1569     ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1570     if (ret < KVM_API_VERSION) {
1571         if (ret >= 0) {
1572             ret = -EINVAL;
1573         }
1574         fprintf(stderr, "kvm version too old\n");
1575         goto err;
1576     }
1577 
1578     if (ret > KVM_API_VERSION) {
1579         ret = -EINVAL;
1580         fprintf(stderr, "kvm version not supported\n");
1581         goto err;
1582     }
1583 
1584     kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
1585     s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
1586 
1587     /* If unspecified, use the default value */
1588     if (!s->nr_slots) {
1589         s->nr_slots = 32;
1590     }
1591 
1592     /* check the vcpu limits */
1593     soft_vcpus_limit = kvm_recommended_vcpus(s);
1594     hard_vcpus_limit = kvm_max_vcpus(s);
1595 
1596     while (nc->name) {
1597         if (nc->num > soft_vcpus_limit) {
1598             fprintf(stderr,
1599                     "Warning: Number of %s cpus requested (%d) exceeds "
1600                     "the recommended cpus supported by KVM (%d)\n",
1601                     nc->name, nc->num, soft_vcpus_limit);
1602 
1603             if (nc->num > hard_vcpus_limit) {
1604                 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
1605                         "the maximum cpus supported by KVM (%d)\n",
1606                         nc->name, nc->num, hard_vcpus_limit);
1607                 exit(1);
1608             }
1609         }
1610         nc++;
1611     }
1612 
1613     kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1614     if (mc->kvm_type) {
1615         type = mc->kvm_type(kvm_type);
1616     } else if (kvm_type) {
1617         ret = -EINVAL;
1618         fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1619         goto err;
1620     }
1621 
1622     do {
1623         ret = kvm_ioctl(s, KVM_CREATE_VM, type);
1624     } while (ret == -EINTR);
1625 
1626     if (ret < 0) {
1627         fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
1628                 strerror(-ret));
1629 
1630 #ifdef TARGET_S390X
1631         if (ret == -EINVAL) {
1632             fprintf(stderr,
1633                     "Host kernel setup problem detected. Please verify:\n");
1634             fprintf(stderr, "- for kernels supporting the switch_amode or"
1635                     " user_mode parameters, whether\n");
1636             fprintf(stderr,
1637                     "  user space is running in primary address space\n");
1638             fprintf(stderr,
1639                     "- for kernels supporting the vm.allocate_pgste sysctl, "
1640                     "whether it is enabled\n");
1641         }
1642 #endif
1643         goto err;
1644     }
1645 
1646     s->vmfd = ret;
1647     missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1648     if (!missing_cap) {
1649         missing_cap =
1650             kvm_check_extension_list(s, kvm_arch_required_capabilities);
1651     }
1652     if (missing_cap) {
1653         ret = -EINVAL;
1654         fprintf(stderr, "kvm does not support %s\n%s",
1655                 missing_cap->name, upgrade_note);
1656         goto err;
1657     }
1658 
1659     s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1660 
1661 #ifdef KVM_CAP_VCPU_EVENTS
1662     s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1663 #endif
1664 
1665     s->robust_singlestep =
1666         kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1667 
1668 #ifdef KVM_CAP_DEBUGREGS
1669     s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1670 #endif
1671 
1672 #ifdef KVM_CAP_IRQ_ROUTING
1673     kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1674 #endif
1675 
1676     s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1677 
1678     s->irq_set_ioctl = KVM_IRQ_LINE;
1679     if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1680         s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1681     }
1682 
1683 #ifdef KVM_CAP_READONLY_MEM
1684     kvm_readonly_mem_allowed =
1685         (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1686 #endif
1687 
1688     kvm_eventfds_allowed =
1689         (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
1690 
1691     kvm_irqfds_allowed =
1692         (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
1693 
1694     kvm_resamplefds_allowed =
1695         (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
1696 
1697     kvm_vm_attributes_allowed =
1698         (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
1699 
1700     kvm_ioeventfd_any_length_allowed =
1701         (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
1702 
1703     kvm_state = s;
1704 
1705     ret = kvm_arch_init(ms, s);
1706     if (ret < 0) {
1707         goto err;
1708     }
1709 
1710     if (machine_kernel_irqchip_allowed(ms)) {
1711         kvm_irqchip_create(ms, s);
1712     }
1713 
1714     if (kvm_eventfds_allowed) {
1715         s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
1716         s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
1717     }
1718     s->memory_listener.listener.coalesced_mmio_add = kvm_coalesce_mmio_region;
1719     s->memory_listener.listener.coalesced_mmio_del = kvm_uncoalesce_mmio_region;
1720 
1721     kvm_memory_listener_register(s, &s->memory_listener,
1722                                  &address_space_memory, 0);
1723     memory_listener_register(&kvm_io_listener,
1724                              &address_space_io);
1725 
1726     s->many_ioeventfds = kvm_check_many_ioeventfds();
1727 
1728     return 0;
1729 
1730 err:
1731     assert(ret < 0);
1732     if (s->vmfd >= 0) {
1733         close(s->vmfd);
1734     }
1735     if (s->fd != -1) {
1736         close(s->fd);
1737     }
1738     g_free(s->memory_listener.slots);
1739 
1740     return ret;
1741 }
1742 
1743 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
1744 {
1745     s->sigmask_len = sigmask_len;
1746 }
1747 
1748 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
1749                           int size, uint32_t count)
1750 {
1751     int i;
1752     uint8_t *ptr = data;
1753 
1754     for (i = 0; i < count; i++) {
1755         address_space_rw(&address_space_io, port, attrs,
1756                          ptr, size,
1757                          direction == KVM_EXIT_IO_OUT);
1758         ptr += size;
1759     }
1760 }
1761 
1762 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
1763 {
1764     fprintf(stderr, "KVM internal error. Suberror: %d\n",
1765             run->internal.suberror);
1766 
1767     if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1768         int i;
1769 
1770         for (i = 0; i < run->internal.ndata; ++i) {
1771             fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1772                     i, (uint64_t)run->internal.data[i]);
1773         }
1774     }
1775     if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1776         fprintf(stderr, "emulation failure\n");
1777         if (!kvm_arch_stop_on_emulation_error(cpu)) {
1778             cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1779             return EXCP_INTERRUPT;
1780         }
1781     }
1782     /* FIXME: Should trigger a qmp message to let management know
1783      * something went wrong.
1784      */
1785     return -1;
1786 }
1787 
1788 void kvm_flush_coalesced_mmio_buffer(void)
1789 {
1790     KVMState *s = kvm_state;
1791 
1792     if (s->coalesced_flush_in_progress) {
1793         return;
1794     }
1795 
1796     s->coalesced_flush_in_progress = true;
1797 
1798     if (s->coalesced_mmio_ring) {
1799         struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1800         while (ring->first != ring->last) {
1801             struct kvm_coalesced_mmio *ent;
1802 
1803             ent = &ring->coalesced_mmio[ring->first];
1804 
1805             cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1806             smp_wmb();
1807             ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1808         }
1809     }
1810 
1811     s->coalesced_flush_in_progress = false;
1812 }
1813 
1814 static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
1815 {
1816     if (!cpu->vcpu_dirty) {
1817         kvm_arch_get_registers(cpu);
1818         cpu->vcpu_dirty = true;
1819     }
1820 }
1821 
1822 void kvm_cpu_synchronize_state(CPUState *cpu)
1823 {
1824     if (!cpu->vcpu_dirty) {
1825         run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
1826     }
1827 }
1828 
1829 static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
1830 {
1831     kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1832     cpu->vcpu_dirty = false;
1833 }
1834 
1835 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
1836 {
1837     run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
1838 }
1839 
1840 static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
1841 {
1842     kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1843     cpu->vcpu_dirty = false;
1844 }
1845 
1846 void kvm_cpu_synchronize_post_init(CPUState *cpu)
1847 {
1848     run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
1849 }
1850 
1851 static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
1852 {
1853     cpu->vcpu_dirty = true;
1854 }
1855 
1856 void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
1857 {
1858     run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
1859 }
1860 
1861 #ifdef KVM_HAVE_MCE_INJECTION
1862 static __thread void *pending_sigbus_addr;
1863 static __thread int pending_sigbus_code;
1864 static __thread bool have_sigbus_pending;
1865 #endif
1866 
1867 static void kvm_cpu_kick(CPUState *cpu)
1868 {
1869     atomic_set(&cpu->kvm_run->immediate_exit, 1);
1870 }
1871 
1872 static void kvm_cpu_kick_self(void)
1873 {
1874     if (kvm_immediate_exit) {
1875         kvm_cpu_kick(current_cpu);
1876     } else {
1877         qemu_cpu_kick_self();
1878     }
1879 }
1880 
1881 static void kvm_eat_signals(CPUState *cpu)
1882 {
1883     struct timespec ts = { 0, 0 };
1884     siginfo_t siginfo;
1885     sigset_t waitset;
1886     sigset_t chkset;
1887     int r;
1888 
1889     if (kvm_immediate_exit) {
1890         atomic_set(&cpu->kvm_run->immediate_exit, 0);
1891         /* Write kvm_run->immediate_exit before the cpu->exit_request
1892          * write in kvm_cpu_exec.
1893          */
1894         smp_wmb();
1895         return;
1896     }
1897 
1898     sigemptyset(&waitset);
1899     sigaddset(&waitset, SIG_IPI);
1900 
1901     do {
1902         r = sigtimedwait(&waitset, &siginfo, &ts);
1903         if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
1904             perror("sigtimedwait");
1905             exit(1);
1906         }
1907 
1908         r = sigpending(&chkset);
1909         if (r == -1) {
1910             perror("sigpending");
1911             exit(1);
1912         }
1913     } while (sigismember(&chkset, SIG_IPI));
1914 }
1915 
1916 int kvm_cpu_exec(CPUState *cpu)
1917 {
1918     struct kvm_run *run = cpu->kvm_run;
1919     int ret, run_ret;
1920 
1921     DPRINTF("kvm_cpu_exec()\n");
1922 
1923     if (kvm_arch_process_async_events(cpu)) {
1924         atomic_set(&cpu->exit_request, 0);
1925         return EXCP_HLT;
1926     }
1927 
1928     qemu_mutex_unlock_iothread();
1929     cpu_exec_start(cpu);
1930 
1931     do {
1932         MemTxAttrs attrs;
1933 
1934         if (cpu->vcpu_dirty) {
1935             kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1936             cpu->vcpu_dirty = false;
1937         }
1938 
1939         kvm_arch_pre_run(cpu, run);
1940         if (atomic_read(&cpu->exit_request)) {
1941             DPRINTF("interrupt exit requested\n");
1942             /*
1943              * KVM requires us to reenter the kernel after IO exits to complete
1944              * instruction emulation. This self-signal will ensure that we
1945              * leave ASAP again.
1946              */
1947             kvm_cpu_kick_self();
1948         }
1949 
1950         /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
1951          * Matching barrier in kvm_eat_signals.
1952          */
1953         smp_rmb();
1954 
1955         run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
1956 
1957         attrs = kvm_arch_post_run(cpu, run);
1958 
1959 #ifdef KVM_HAVE_MCE_INJECTION
1960         if (unlikely(have_sigbus_pending)) {
1961             qemu_mutex_lock_iothread();
1962             kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
1963                                     pending_sigbus_addr);
1964             have_sigbus_pending = false;
1965             qemu_mutex_unlock_iothread();
1966         }
1967 #endif
1968 
1969         if (run_ret < 0) {
1970             if (run_ret == -EINTR || run_ret == -EAGAIN) {
1971                 DPRINTF("io window exit\n");
1972                 kvm_eat_signals(cpu);
1973                 ret = EXCP_INTERRUPT;
1974                 break;
1975             }
1976             fprintf(stderr, "error: kvm run failed %s\n",
1977                     strerror(-run_ret));
1978 #ifdef TARGET_PPC
1979             if (run_ret == -EBUSY) {
1980                 fprintf(stderr,
1981                         "This is probably because your SMT is enabled.\n"
1982                         "VCPU can only run on primary threads with all "
1983                         "secondary threads offline.\n");
1984             }
1985 #endif
1986             ret = -1;
1987             break;
1988         }
1989 
1990         trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
1991         switch (run->exit_reason) {
1992         case KVM_EXIT_IO:
1993             DPRINTF("handle_io\n");
1994             /* Called outside BQL */
1995             kvm_handle_io(run->io.port, attrs,
1996                           (uint8_t *)run + run->io.data_offset,
1997                           run->io.direction,
1998                           run->io.size,
1999                           run->io.count);
2000             ret = 0;
2001             break;
2002         case KVM_EXIT_MMIO:
2003             DPRINTF("handle_mmio\n");
2004             /* Called outside BQL */
2005             address_space_rw(&address_space_memory,
2006                              run->mmio.phys_addr, attrs,
2007                              run->mmio.data,
2008                              run->mmio.len,
2009                              run->mmio.is_write);
2010             ret = 0;
2011             break;
2012         case KVM_EXIT_IRQ_WINDOW_OPEN:
2013             DPRINTF("irq_window_open\n");
2014             ret = EXCP_INTERRUPT;
2015             break;
2016         case KVM_EXIT_SHUTDOWN:
2017             DPRINTF("shutdown\n");
2018             qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
2019             ret = EXCP_INTERRUPT;
2020             break;
2021         case KVM_EXIT_UNKNOWN:
2022             fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
2023                     (uint64_t)run->hw.hardware_exit_reason);
2024             ret = -1;
2025             break;
2026         case KVM_EXIT_INTERNAL_ERROR:
2027             ret = kvm_handle_internal_error(cpu, run);
2028             break;
2029         case KVM_EXIT_SYSTEM_EVENT:
2030             switch (run->system_event.type) {
2031             case KVM_SYSTEM_EVENT_SHUTDOWN:
2032                 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
2033                 ret = EXCP_INTERRUPT;
2034                 break;
2035             case KVM_SYSTEM_EVENT_RESET:
2036                 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
2037                 ret = EXCP_INTERRUPT;
2038                 break;
2039             case KVM_SYSTEM_EVENT_CRASH:
2040                 kvm_cpu_synchronize_state(cpu);
2041                 qemu_mutex_lock_iothread();
2042                 qemu_system_guest_panicked(cpu_get_crash_info(cpu));
2043                 qemu_mutex_unlock_iothread();
2044                 ret = 0;
2045                 break;
2046             default:
2047                 DPRINTF("kvm_arch_handle_exit\n");
2048                 ret = kvm_arch_handle_exit(cpu, run);
2049                 break;
2050             }
2051             break;
2052         default:
2053             DPRINTF("kvm_arch_handle_exit\n");
2054             ret = kvm_arch_handle_exit(cpu, run);
2055             break;
2056         }
2057     } while (ret == 0);
2058 
2059     cpu_exec_end(cpu);
2060     qemu_mutex_lock_iothread();
2061 
2062     if (ret < 0) {
2063         cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
2064         vm_stop(RUN_STATE_INTERNAL_ERROR);
2065     }
2066 
2067     atomic_set(&cpu->exit_request, 0);
2068     return ret;
2069 }
2070 
2071 int kvm_ioctl(KVMState *s, int type, ...)
2072 {
2073     int ret;
2074     void *arg;
2075     va_list ap;
2076 
2077     va_start(ap, type);
2078     arg = va_arg(ap, void *);
2079     va_end(ap);
2080 
2081     trace_kvm_ioctl(type, arg);
2082     ret = ioctl(s->fd, type, arg);
2083     if (ret == -1) {
2084         ret = -errno;
2085     }
2086     return ret;
2087 }
2088 
2089 int kvm_vm_ioctl(KVMState *s, int type, ...)
2090 {
2091     int ret;
2092     void *arg;
2093     va_list ap;
2094 
2095     va_start(ap, type);
2096     arg = va_arg(ap, void *);
2097     va_end(ap);
2098 
2099     trace_kvm_vm_ioctl(type, arg);
2100     ret = ioctl(s->vmfd, type, arg);
2101     if (ret == -1) {
2102         ret = -errno;
2103     }
2104     return ret;
2105 }
2106 
2107 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
2108 {
2109     int ret;
2110     void *arg;
2111     va_list ap;
2112 
2113     va_start(ap, type);
2114     arg = va_arg(ap, void *);
2115     va_end(ap);
2116 
2117     trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
2118     ret = ioctl(cpu->kvm_fd, type, arg);
2119     if (ret == -1) {
2120         ret = -errno;
2121     }
2122     return ret;
2123 }
2124 
2125 int kvm_device_ioctl(int fd, int type, ...)
2126 {
2127     int ret;
2128     void *arg;
2129     va_list ap;
2130 
2131     va_start(ap, type);
2132     arg = va_arg(ap, void *);
2133     va_end(ap);
2134 
2135     trace_kvm_device_ioctl(fd, type, arg);
2136     ret = ioctl(fd, type, arg);
2137     if (ret == -1) {
2138         ret = -errno;
2139     }
2140     return ret;
2141 }
2142 
2143 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
2144 {
2145     int ret;
2146     struct kvm_device_attr attribute = {
2147         .group = group,
2148         .attr = attr,
2149     };
2150 
2151     if (!kvm_vm_attributes_allowed) {
2152         return 0;
2153     }
2154 
2155     ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
2156     /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2157     return ret ? 0 : 1;
2158 }
2159 
2160 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
2161 {
2162     struct kvm_device_attr attribute = {
2163         .group = group,
2164         .attr = attr,
2165         .flags = 0,
2166     };
2167 
2168     return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
2169 }
2170 
2171 int kvm_device_access(int fd, int group, uint64_t attr,
2172                       void *val, bool write, Error **errp)
2173 {
2174     struct kvm_device_attr kvmattr;
2175     int err;
2176 
2177     kvmattr.flags = 0;
2178     kvmattr.group = group;
2179     kvmattr.attr = attr;
2180     kvmattr.addr = (uintptr_t)val;
2181 
2182     err = kvm_device_ioctl(fd,
2183                            write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
2184                            &kvmattr);
2185     if (err < 0) {
2186         error_setg_errno(errp, -err,
2187                          "KVM_%s_DEVICE_ATTR failed: Group %d "
2188                          "attr 0x%016" PRIx64,
2189                          write ? "SET" : "GET", group, attr);
2190     }
2191     return err;
2192 }
2193 
2194 /* Return 1 on success, 0 on failure */
2195 int kvm_has_sync_mmu(void)
2196 {
2197     return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2198 }
2199 
2200 int kvm_has_vcpu_events(void)
2201 {
2202     return kvm_state->vcpu_events;
2203 }
2204 
2205 int kvm_has_robust_singlestep(void)
2206 {
2207     return kvm_state->robust_singlestep;
2208 }
2209 
2210 int kvm_has_debugregs(void)
2211 {
2212     return kvm_state->debugregs;
2213 }
2214 
2215 int kvm_has_many_ioeventfds(void)
2216 {
2217     if (!kvm_enabled()) {
2218         return 0;
2219     }
2220     return kvm_state->many_ioeventfds;
2221 }
2222 
2223 int kvm_has_gsi_routing(void)
2224 {
2225 #ifdef KVM_CAP_IRQ_ROUTING
2226     return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
2227 #else
2228     return false;
2229 #endif
2230 }
2231 
2232 int kvm_has_intx_set_mask(void)
2233 {
2234     return kvm_state->intx_set_mask;
2235 }
2236 
2237 bool kvm_arm_supports_user_irq(void)
2238 {
2239     return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
2240 }
2241 
2242 #ifdef KVM_CAP_SET_GUEST_DEBUG
2243 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
2244                                                  target_ulong pc)
2245 {
2246     struct kvm_sw_breakpoint *bp;
2247 
2248     QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
2249         if (bp->pc == pc) {
2250             return bp;
2251         }
2252     }
2253     return NULL;
2254 }
2255 
2256 int kvm_sw_breakpoints_active(CPUState *cpu)
2257 {
2258     return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
2259 }
2260 
2261 struct kvm_set_guest_debug_data {
2262     struct kvm_guest_debug dbg;
2263     int err;
2264 };
2265 
2266 static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
2267 {
2268     struct kvm_set_guest_debug_data *dbg_data =
2269         (struct kvm_set_guest_debug_data *) data.host_ptr;
2270 
2271     dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
2272                                    &dbg_data->dbg);
2273 }
2274 
2275 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2276 {
2277     struct kvm_set_guest_debug_data data;
2278 
2279     data.dbg.control = reinject_trap;
2280 
2281     if (cpu->singlestep_enabled) {
2282         data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2283     }
2284     kvm_arch_update_guest_debug(cpu, &data.dbg);
2285 
2286     run_on_cpu(cpu, kvm_invoke_set_guest_debug,
2287                RUN_ON_CPU_HOST_PTR(&data));
2288     return data.err;
2289 }
2290 
2291 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2292                           target_ulong len, int type)
2293 {
2294     struct kvm_sw_breakpoint *bp;
2295     int err;
2296 
2297     if (type == GDB_BREAKPOINT_SW) {
2298         bp = kvm_find_sw_breakpoint(cpu, addr);
2299         if (bp) {
2300             bp->use_count++;
2301             return 0;
2302         }
2303 
2304         bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2305         bp->pc = addr;
2306         bp->use_count = 1;
2307         err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2308         if (err) {
2309             g_free(bp);
2310             return err;
2311         }
2312 
2313         QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2314     } else {
2315         err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2316         if (err) {
2317             return err;
2318         }
2319     }
2320 
2321     CPU_FOREACH(cpu) {
2322         err = kvm_update_guest_debug(cpu, 0);
2323         if (err) {
2324             return err;
2325         }
2326     }
2327     return 0;
2328 }
2329 
2330 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2331                           target_ulong len, int type)
2332 {
2333     struct kvm_sw_breakpoint *bp;
2334     int err;
2335 
2336     if (type == GDB_BREAKPOINT_SW) {
2337         bp = kvm_find_sw_breakpoint(cpu, addr);
2338         if (!bp) {
2339             return -ENOENT;
2340         }
2341 
2342         if (bp->use_count > 1) {
2343             bp->use_count--;
2344             return 0;
2345         }
2346 
2347         err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2348         if (err) {
2349             return err;
2350         }
2351 
2352         QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2353         g_free(bp);
2354     } else {
2355         err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2356         if (err) {
2357             return err;
2358         }
2359     }
2360 
2361     CPU_FOREACH(cpu) {
2362         err = kvm_update_guest_debug(cpu, 0);
2363         if (err) {
2364             return err;
2365         }
2366     }
2367     return 0;
2368 }
2369 
2370 void kvm_remove_all_breakpoints(CPUState *cpu)
2371 {
2372     struct kvm_sw_breakpoint *bp, *next;
2373     KVMState *s = cpu->kvm_state;
2374     CPUState *tmpcpu;
2375 
2376     QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2377         if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2378             /* Try harder to find a CPU that currently sees the breakpoint. */
2379             CPU_FOREACH(tmpcpu) {
2380                 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2381                     break;
2382                 }
2383             }
2384         }
2385         QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2386         g_free(bp);
2387     }
2388     kvm_arch_remove_all_hw_breakpoints();
2389 
2390     CPU_FOREACH(cpu) {
2391         kvm_update_guest_debug(cpu, 0);
2392     }
2393 }
2394 
2395 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2396 
2397 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2398 {
2399     return -EINVAL;
2400 }
2401 
2402 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2403                           target_ulong len, int type)
2404 {
2405     return -EINVAL;
2406 }
2407 
2408 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2409                           target_ulong len, int type)
2410 {
2411     return -EINVAL;
2412 }
2413 
2414 void kvm_remove_all_breakpoints(CPUState *cpu)
2415 {
2416 }
2417 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2418 
2419 static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2420 {
2421     KVMState *s = kvm_state;
2422     struct kvm_signal_mask *sigmask;
2423     int r;
2424 
2425     sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2426 
2427     sigmask->len = s->sigmask_len;
2428     memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2429     r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2430     g_free(sigmask);
2431 
2432     return r;
2433 }
2434 
2435 static void kvm_ipi_signal(int sig)
2436 {
2437     if (current_cpu) {
2438         assert(kvm_immediate_exit);
2439         kvm_cpu_kick(current_cpu);
2440     }
2441 }
2442 
2443 void kvm_init_cpu_signals(CPUState *cpu)
2444 {
2445     int r;
2446     sigset_t set;
2447     struct sigaction sigact;
2448 
2449     memset(&sigact, 0, sizeof(sigact));
2450     sigact.sa_handler = kvm_ipi_signal;
2451     sigaction(SIG_IPI, &sigact, NULL);
2452 
2453     pthread_sigmask(SIG_BLOCK, NULL, &set);
2454 #if defined KVM_HAVE_MCE_INJECTION
2455     sigdelset(&set, SIGBUS);
2456     pthread_sigmask(SIG_SETMASK, &set, NULL);
2457 #endif
2458     sigdelset(&set, SIG_IPI);
2459     if (kvm_immediate_exit) {
2460         r = pthread_sigmask(SIG_SETMASK, &set, NULL);
2461     } else {
2462         r = kvm_set_signal_mask(cpu, &set);
2463     }
2464     if (r) {
2465         fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
2466         exit(1);
2467     }
2468 }
2469 
2470 /* Called asynchronously in VCPU thread.  */
2471 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2472 {
2473 #ifdef KVM_HAVE_MCE_INJECTION
2474     if (have_sigbus_pending) {
2475         return 1;
2476     }
2477     have_sigbus_pending = true;
2478     pending_sigbus_addr = addr;
2479     pending_sigbus_code = code;
2480     atomic_set(&cpu->exit_request, 1);
2481     return 0;
2482 #else
2483     return 1;
2484 #endif
2485 }
2486 
2487 /* Called synchronously (via signalfd) in main thread.  */
2488 int kvm_on_sigbus(int code, void *addr)
2489 {
2490 #ifdef KVM_HAVE_MCE_INJECTION
2491     /* Action required MCE kills the process if SIGBUS is blocked.  Because
2492      * that's what happens in the I/O thread, where we handle MCE via signalfd,
2493      * we can only get action optional here.
2494      */
2495     assert(code != BUS_MCEERR_AR);
2496     kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
2497     return 0;
2498 #else
2499     return 1;
2500 #endif
2501 }
2502 
2503 int kvm_create_device(KVMState *s, uint64_t type, bool test)
2504 {
2505     int ret;
2506     struct kvm_create_device create_dev;
2507 
2508     create_dev.type = type;
2509     create_dev.fd = -1;
2510     create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2511 
2512     if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2513         return -ENOTSUP;
2514     }
2515 
2516     ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2517     if (ret) {
2518         return ret;
2519     }
2520 
2521     return test ? 0 : create_dev.fd;
2522 }
2523 
2524 bool kvm_device_supported(int vmfd, uint64_t type)
2525 {
2526     struct kvm_create_device create_dev = {
2527         .type = type,
2528         .fd = -1,
2529         .flags = KVM_CREATE_DEVICE_TEST,
2530     };
2531 
2532     if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
2533         return false;
2534     }
2535 
2536     return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
2537 }
2538 
2539 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2540 {
2541     struct kvm_one_reg reg;
2542     int r;
2543 
2544     reg.id = id;
2545     reg.addr = (uintptr_t) source;
2546     r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
2547     if (r) {
2548         trace_kvm_failed_reg_set(id, strerror(-r));
2549     }
2550     return r;
2551 }
2552 
2553 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2554 {
2555     struct kvm_one_reg reg;
2556     int r;
2557 
2558     reg.id = id;
2559     reg.addr = (uintptr_t) target;
2560     r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
2561     if (r) {
2562         trace_kvm_failed_reg_get(id, strerror(-r));
2563     }
2564     return r;
2565 }
2566 
2567 static void kvm_accel_class_init(ObjectClass *oc, void *data)
2568 {
2569     AccelClass *ac = ACCEL_CLASS(oc);
2570     ac->name = "KVM";
2571     ac->init_machine = kvm_init;
2572     ac->allowed = &kvm_allowed;
2573 }
2574 
2575 static const TypeInfo kvm_accel_type = {
2576     .name = TYPE_KVM_ACCEL,
2577     .parent = TYPE_ACCEL,
2578     .class_init = kvm_accel_class_init,
2579     .instance_size = sizeof(KVMState),
2580 };
2581 
2582 static void kvm_type_init(void)
2583 {
2584     type_register_static(&kvm_accel_type);
2585 }
2586 
2587 type_init(kvm_type_init);
2588