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