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