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