]> Git Repo - qemu.git/blob - kvm-all.c
qxl: use uint64_t for vram size
[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 static int kvm_max_vcpu_id(KVMState *s)
1523 {
1524     int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
1525     return (ret) ? ret : kvm_max_vcpus(s);
1526 }
1527
1528 bool kvm_vcpu_id_is_valid(int vcpu_id)
1529 {
1530     KVMState *s = KVM_STATE(current_machine->accelerator);
1531     return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
1532 }
1533
1534 static int kvm_init(MachineState *ms)
1535 {
1536     MachineClass *mc = MACHINE_GET_CLASS(ms);
1537     static const char upgrade_note[] =
1538         "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1539         "(see http://sourceforge.net/projects/kvm).\n";
1540     struct {
1541         const char *name;
1542         int num;
1543     } num_cpus[] = {
1544         { "SMP",          smp_cpus },
1545         { "hotpluggable", max_cpus },
1546         { NULL, }
1547     }, *nc = num_cpus;
1548     int soft_vcpus_limit, hard_vcpus_limit;
1549     KVMState *s;
1550     const KVMCapabilityInfo *missing_cap;
1551     int ret;
1552     int type = 0;
1553     const char *kvm_type;
1554
1555     s = KVM_STATE(ms->accelerator);
1556
1557     /*
1558      * On systems where the kernel can support different base page
1559      * sizes, host page size may be different from TARGET_PAGE_SIZE,
1560      * even with KVM.  TARGET_PAGE_SIZE is assumed to be the minimum
1561      * page size for the system though.
1562      */
1563     assert(TARGET_PAGE_SIZE <= getpagesize());
1564
1565     s->sigmask_len = 8;
1566
1567 #ifdef KVM_CAP_SET_GUEST_DEBUG
1568     QTAILQ_INIT(&s->kvm_sw_breakpoints);
1569 #endif
1570     QLIST_INIT(&s->kvm_parked_vcpus);
1571     s->vmfd = -1;
1572     s->fd = qemu_open("/dev/kvm", O_RDWR);
1573     if (s->fd == -1) {
1574         fprintf(stderr, "Could not access KVM kernel module: %m\n");
1575         ret = -errno;
1576         goto err;
1577     }
1578
1579     ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1580     if (ret < KVM_API_VERSION) {
1581         if (ret >= 0) {
1582             ret = -EINVAL;
1583         }
1584         fprintf(stderr, "kvm version too old\n");
1585         goto err;
1586     }
1587
1588     if (ret > KVM_API_VERSION) {
1589         ret = -EINVAL;
1590         fprintf(stderr, "kvm version not supported\n");
1591         goto err;
1592     }
1593
1594     s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
1595
1596     /* If unspecified, use the default value */
1597     if (!s->nr_slots) {
1598         s->nr_slots = 32;
1599     }
1600
1601     /* check the vcpu limits */
1602     soft_vcpus_limit = kvm_recommended_vcpus(s);
1603     hard_vcpus_limit = kvm_max_vcpus(s);
1604
1605     while (nc->name) {
1606         if (nc->num > soft_vcpus_limit) {
1607             fprintf(stderr,
1608                     "Warning: Number of %s cpus requested (%d) exceeds "
1609                     "the recommended cpus supported by KVM (%d)\n",
1610                     nc->name, nc->num, soft_vcpus_limit);
1611
1612             if (nc->num > hard_vcpus_limit) {
1613                 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
1614                         "the maximum cpus supported by KVM (%d)\n",
1615                         nc->name, nc->num, hard_vcpus_limit);
1616                 exit(1);
1617             }
1618         }
1619         nc++;
1620     }
1621
1622     kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1623     if (mc->kvm_type) {
1624         type = mc->kvm_type(kvm_type);
1625     } else if (kvm_type) {
1626         ret = -EINVAL;
1627         fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1628         goto err;
1629     }
1630
1631     do {
1632         ret = kvm_ioctl(s, KVM_CREATE_VM, type);
1633     } while (ret == -EINTR);
1634
1635     if (ret < 0) {
1636         fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
1637                 strerror(-ret));
1638
1639 #ifdef TARGET_S390X
1640         if (ret == -EINVAL) {
1641             fprintf(stderr,
1642                     "Host kernel setup problem detected. Please verify:\n");
1643             fprintf(stderr, "- for kernels supporting the switch_amode or"
1644                     " user_mode parameters, whether\n");
1645             fprintf(stderr,
1646                     "  user space is running in primary address space\n");
1647             fprintf(stderr,
1648                     "- for kernels supporting the vm.allocate_pgste sysctl, "
1649                     "whether it is enabled\n");
1650         }
1651 #endif
1652         goto err;
1653     }
1654
1655     s->vmfd = ret;
1656     missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1657     if (!missing_cap) {
1658         missing_cap =
1659             kvm_check_extension_list(s, kvm_arch_required_capabilities);
1660     }
1661     if (missing_cap) {
1662         ret = -EINVAL;
1663         fprintf(stderr, "kvm does not support %s\n%s",
1664                 missing_cap->name, upgrade_note);
1665         goto err;
1666     }
1667
1668     s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1669
1670     s->broken_set_mem_region = 1;
1671     ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
1672     if (ret > 0) {
1673         s->broken_set_mem_region = 0;
1674     }
1675
1676 #ifdef KVM_CAP_VCPU_EVENTS
1677     s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1678 #endif
1679
1680     s->robust_singlestep =
1681         kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1682
1683 #ifdef KVM_CAP_DEBUGREGS
1684     s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1685 #endif
1686
1687 #ifdef KVM_CAP_IRQ_ROUTING
1688     kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1689 #endif
1690
1691     s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1692
1693     s->irq_set_ioctl = KVM_IRQ_LINE;
1694     if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1695         s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1696     }
1697
1698 #ifdef KVM_CAP_READONLY_MEM
1699     kvm_readonly_mem_allowed =
1700         (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1701 #endif
1702
1703     kvm_eventfds_allowed =
1704         (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
1705
1706     kvm_irqfds_allowed =
1707         (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
1708
1709     kvm_resamplefds_allowed =
1710         (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
1711
1712     kvm_vm_attributes_allowed =
1713         (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
1714
1715     kvm_ioeventfd_any_length_allowed =
1716         (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
1717
1718     ret = kvm_arch_init(ms, s);
1719     if (ret < 0) {
1720         goto err;
1721     }
1722
1723     if (machine_kernel_irqchip_allowed(ms)) {
1724         kvm_irqchip_create(ms, s);
1725     }
1726
1727     kvm_state = s;
1728
1729     if (kvm_eventfds_allowed) {
1730         s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
1731         s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
1732     }
1733     s->memory_listener.listener.coalesced_mmio_add = kvm_coalesce_mmio_region;
1734     s->memory_listener.listener.coalesced_mmio_del = kvm_uncoalesce_mmio_region;
1735
1736     kvm_memory_listener_register(s, &s->memory_listener,
1737                                  &address_space_memory, 0);
1738     memory_listener_register(&kvm_io_listener,
1739                              &address_space_io);
1740
1741     s->many_ioeventfds = kvm_check_many_ioeventfds();
1742
1743     cpu_interrupt_handler = kvm_handle_interrupt;
1744
1745     return 0;
1746
1747 err:
1748     assert(ret < 0);
1749     if (s->vmfd >= 0) {
1750         close(s->vmfd);
1751     }
1752     if (s->fd != -1) {
1753         close(s->fd);
1754     }
1755     g_free(s->memory_listener.slots);
1756
1757     return ret;
1758 }
1759
1760 void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
1761 {
1762     s->sigmask_len = sigmask_len;
1763 }
1764
1765 static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
1766                           int size, uint32_t count)
1767 {
1768     int i;
1769     uint8_t *ptr = data;
1770
1771     for (i = 0; i < count; i++) {
1772         address_space_rw(&address_space_io, port, attrs,
1773                          ptr, size,
1774                          direction == KVM_EXIT_IO_OUT);
1775         ptr += size;
1776     }
1777 }
1778
1779 static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
1780 {
1781     fprintf(stderr, "KVM internal error. Suberror: %d\n",
1782             run->internal.suberror);
1783
1784     if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1785         int i;
1786
1787         for (i = 0; i < run->internal.ndata; ++i) {
1788             fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1789                     i, (uint64_t)run->internal.data[i]);
1790         }
1791     }
1792     if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1793         fprintf(stderr, "emulation failure\n");
1794         if (!kvm_arch_stop_on_emulation_error(cpu)) {
1795             cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1796             return EXCP_INTERRUPT;
1797         }
1798     }
1799     /* FIXME: Should trigger a qmp message to let management know
1800      * something went wrong.
1801      */
1802     return -1;
1803 }
1804
1805 void kvm_flush_coalesced_mmio_buffer(void)
1806 {
1807     KVMState *s = kvm_state;
1808
1809     if (s->coalesced_flush_in_progress) {
1810         return;
1811     }
1812
1813     s->coalesced_flush_in_progress = true;
1814
1815     if (s->coalesced_mmio_ring) {
1816         struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1817         while (ring->first != ring->last) {
1818             struct kvm_coalesced_mmio *ent;
1819
1820             ent = &ring->coalesced_mmio[ring->first];
1821
1822             cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1823             smp_wmb();
1824             ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1825         }
1826     }
1827
1828     s->coalesced_flush_in_progress = false;
1829 }
1830
1831 static void do_kvm_cpu_synchronize_state(void *arg)
1832 {
1833     CPUState *cpu = arg;
1834
1835     if (!cpu->kvm_vcpu_dirty) {
1836         kvm_arch_get_registers(cpu);
1837         cpu->kvm_vcpu_dirty = true;
1838     }
1839 }
1840
1841 void kvm_cpu_synchronize_state(CPUState *cpu)
1842 {
1843     if (!cpu->kvm_vcpu_dirty) {
1844         run_on_cpu(cpu, do_kvm_cpu_synchronize_state, cpu);
1845     }
1846 }
1847
1848 static void do_kvm_cpu_synchronize_post_reset(void *arg)
1849 {
1850     CPUState *cpu = arg;
1851
1852     kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1853     cpu->kvm_vcpu_dirty = false;
1854 }
1855
1856 void kvm_cpu_synchronize_post_reset(CPUState *cpu)
1857 {
1858     run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, cpu);
1859 }
1860
1861 static void do_kvm_cpu_synchronize_post_init(void *arg)
1862 {
1863     CPUState *cpu = arg;
1864
1865     kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1866     cpu->kvm_vcpu_dirty = false;
1867 }
1868
1869 void kvm_cpu_synchronize_post_init(CPUState *cpu)
1870 {
1871     run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, cpu);
1872 }
1873
1874 int kvm_cpu_exec(CPUState *cpu)
1875 {
1876     struct kvm_run *run = cpu->kvm_run;
1877     int ret, run_ret;
1878
1879     DPRINTF("kvm_cpu_exec()\n");
1880
1881     if (kvm_arch_process_async_events(cpu)) {
1882         cpu->exit_request = 0;
1883         return EXCP_HLT;
1884     }
1885
1886     qemu_mutex_unlock_iothread();
1887
1888     do {
1889         MemTxAttrs attrs;
1890
1891         if (cpu->kvm_vcpu_dirty) {
1892             kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1893             cpu->kvm_vcpu_dirty = false;
1894         }
1895
1896         kvm_arch_pre_run(cpu, run);
1897         if (cpu->exit_request) {
1898             DPRINTF("interrupt exit requested\n");
1899             /*
1900              * KVM requires us to reenter the kernel after IO exits to complete
1901              * instruction emulation. This self-signal will ensure that we
1902              * leave ASAP again.
1903              */
1904             qemu_cpu_kick_self();
1905         }
1906
1907         run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
1908
1909         attrs = kvm_arch_post_run(cpu, run);
1910
1911         if (run_ret < 0) {
1912             if (run_ret == -EINTR || run_ret == -EAGAIN) {
1913                 DPRINTF("io window exit\n");
1914                 ret = EXCP_INTERRUPT;
1915                 break;
1916             }
1917             fprintf(stderr, "error: kvm run failed %s\n",
1918                     strerror(-run_ret));
1919 #ifdef TARGET_PPC
1920             if (run_ret == -EBUSY) {
1921                 fprintf(stderr,
1922                         "This is probably because your SMT is enabled.\n"
1923                         "VCPU can only run on primary threads with all "
1924                         "secondary threads offline.\n");
1925             }
1926 #endif
1927             ret = -1;
1928             break;
1929         }
1930
1931         trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
1932         switch (run->exit_reason) {
1933         case KVM_EXIT_IO:
1934             DPRINTF("handle_io\n");
1935             /* Called outside BQL */
1936             kvm_handle_io(run->io.port, attrs,
1937                           (uint8_t *)run + run->io.data_offset,
1938                           run->io.direction,
1939                           run->io.size,
1940                           run->io.count);
1941             ret = 0;
1942             break;
1943         case KVM_EXIT_MMIO:
1944             DPRINTF("handle_mmio\n");
1945             /* Called outside BQL */
1946             address_space_rw(&address_space_memory,
1947                              run->mmio.phys_addr, attrs,
1948                              run->mmio.data,
1949                              run->mmio.len,
1950                              run->mmio.is_write);
1951             ret = 0;
1952             break;
1953         case KVM_EXIT_IRQ_WINDOW_OPEN:
1954             DPRINTF("irq_window_open\n");
1955             ret = EXCP_INTERRUPT;
1956             break;
1957         case KVM_EXIT_SHUTDOWN:
1958             DPRINTF("shutdown\n");
1959             qemu_system_reset_request();
1960             ret = EXCP_INTERRUPT;
1961             break;
1962         case KVM_EXIT_UNKNOWN:
1963             fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1964                     (uint64_t)run->hw.hardware_exit_reason);
1965             ret = -1;
1966             break;
1967         case KVM_EXIT_INTERNAL_ERROR:
1968             ret = kvm_handle_internal_error(cpu, run);
1969             break;
1970         case KVM_EXIT_SYSTEM_EVENT:
1971             switch (run->system_event.type) {
1972             case KVM_SYSTEM_EVENT_SHUTDOWN:
1973                 qemu_system_shutdown_request();
1974                 ret = EXCP_INTERRUPT;
1975                 break;
1976             case KVM_SYSTEM_EVENT_RESET:
1977                 qemu_system_reset_request();
1978                 ret = EXCP_INTERRUPT;
1979                 break;
1980             case KVM_SYSTEM_EVENT_CRASH:
1981                 qemu_mutex_lock_iothread();
1982                 qemu_system_guest_panicked();
1983                 qemu_mutex_unlock_iothread();
1984                 ret = 0;
1985                 break;
1986             default:
1987                 DPRINTF("kvm_arch_handle_exit\n");
1988                 ret = kvm_arch_handle_exit(cpu, run);
1989                 break;
1990             }
1991             break;
1992         default:
1993             DPRINTF("kvm_arch_handle_exit\n");
1994             ret = kvm_arch_handle_exit(cpu, run);
1995             break;
1996         }
1997     } while (ret == 0);
1998
1999     qemu_mutex_lock_iothread();
2000
2001     if (ret < 0) {
2002         cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
2003         vm_stop(RUN_STATE_INTERNAL_ERROR);
2004     }
2005
2006     cpu->exit_request = 0;
2007     return ret;
2008 }
2009
2010 int kvm_ioctl(KVMState *s, int type, ...)
2011 {
2012     int ret;
2013     void *arg;
2014     va_list ap;
2015
2016     va_start(ap, type);
2017     arg = va_arg(ap, void *);
2018     va_end(ap);
2019
2020     trace_kvm_ioctl(type, arg);
2021     ret = ioctl(s->fd, type, arg);
2022     if (ret == -1) {
2023         ret = -errno;
2024     }
2025     return ret;
2026 }
2027
2028 int kvm_vm_ioctl(KVMState *s, int type, ...)
2029 {
2030     int ret;
2031     void *arg;
2032     va_list ap;
2033
2034     va_start(ap, type);
2035     arg = va_arg(ap, void *);
2036     va_end(ap);
2037
2038     trace_kvm_vm_ioctl(type, arg);
2039     ret = ioctl(s->vmfd, type, arg);
2040     if (ret == -1) {
2041         ret = -errno;
2042     }
2043     return ret;
2044 }
2045
2046 int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
2047 {
2048     int ret;
2049     void *arg;
2050     va_list ap;
2051
2052     va_start(ap, type);
2053     arg = va_arg(ap, void *);
2054     va_end(ap);
2055
2056     trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
2057     ret = ioctl(cpu->kvm_fd, type, arg);
2058     if (ret == -1) {
2059         ret = -errno;
2060     }
2061     return ret;
2062 }
2063
2064 int kvm_device_ioctl(int fd, int type, ...)
2065 {
2066     int ret;
2067     void *arg;
2068     va_list ap;
2069
2070     va_start(ap, type);
2071     arg = va_arg(ap, void *);
2072     va_end(ap);
2073
2074     trace_kvm_device_ioctl(fd, type, arg);
2075     ret = ioctl(fd, type, arg);
2076     if (ret == -1) {
2077         ret = -errno;
2078     }
2079     return ret;
2080 }
2081
2082 int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
2083 {
2084     int ret;
2085     struct kvm_device_attr attribute = {
2086         .group = group,
2087         .attr = attr,
2088     };
2089
2090     if (!kvm_vm_attributes_allowed) {
2091         return 0;
2092     }
2093
2094     ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
2095     /* kvm returns 0 on success for HAS_DEVICE_ATTR */
2096     return ret ? 0 : 1;
2097 }
2098
2099 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
2100 {
2101     struct kvm_device_attr attribute = {
2102         .group = group,
2103         .attr = attr,
2104         .flags = 0,
2105     };
2106
2107     return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
2108 }
2109
2110 void kvm_device_access(int fd, int group, uint64_t attr,
2111                        void *val, bool write)
2112 {
2113     struct kvm_device_attr kvmattr;
2114     int err;
2115
2116     kvmattr.flags = 0;
2117     kvmattr.group = group;
2118     kvmattr.attr = attr;
2119     kvmattr.addr = (uintptr_t)val;
2120
2121     err = kvm_device_ioctl(fd,
2122                            write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
2123                            &kvmattr);
2124     if (err < 0) {
2125         error_report("KVM_%s_DEVICE_ATTR failed: %s",
2126                      write ? "SET" : "GET", strerror(-err));
2127         error_printf("Group %d attr 0x%016" PRIx64, group, attr);
2128         abort();
2129     }
2130 }
2131
2132 int kvm_has_sync_mmu(void)
2133 {
2134     return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
2135 }
2136
2137 int kvm_has_vcpu_events(void)
2138 {
2139     return kvm_state->vcpu_events;
2140 }
2141
2142 int kvm_has_robust_singlestep(void)
2143 {
2144     return kvm_state->robust_singlestep;
2145 }
2146
2147 int kvm_has_debugregs(void)
2148 {
2149     return kvm_state->debugregs;
2150 }
2151
2152 int kvm_has_many_ioeventfds(void)
2153 {
2154     if (!kvm_enabled()) {
2155         return 0;
2156     }
2157     return kvm_state->many_ioeventfds;
2158 }
2159
2160 int kvm_has_gsi_routing(void)
2161 {
2162 #ifdef KVM_CAP_IRQ_ROUTING
2163     return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
2164 #else
2165     return false;
2166 #endif
2167 }
2168
2169 int kvm_has_intx_set_mask(void)
2170 {
2171     return kvm_state->intx_set_mask;
2172 }
2173
2174 void kvm_setup_guest_memory(void *start, size_t size)
2175 {
2176     if (!kvm_has_sync_mmu()) {
2177         int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
2178
2179         if (ret) {
2180             perror("qemu_madvise");
2181             fprintf(stderr,
2182                     "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
2183             exit(1);
2184         }
2185     }
2186 }
2187
2188 #ifdef KVM_CAP_SET_GUEST_DEBUG
2189 struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
2190                                                  target_ulong pc)
2191 {
2192     struct kvm_sw_breakpoint *bp;
2193
2194     QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
2195         if (bp->pc == pc) {
2196             return bp;
2197         }
2198     }
2199     return NULL;
2200 }
2201
2202 int kvm_sw_breakpoints_active(CPUState *cpu)
2203 {
2204     return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
2205 }
2206
2207 struct kvm_set_guest_debug_data {
2208     struct kvm_guest_debug dbg;
2209     CPUState *cpu;
2210     int err;
2211 };
2212
2213 static void kvm_invoke_set_guest_debug(void *data)
2214 {
2215     struct kvm_set_guest_debug_data *dbg_data = data;
2216
2217     dbg_data->err = kvm_vcpu_ioctl(dbg_data->cpu, KVM_SET_GUEST_DEBUG,
2218                                    &dbg_data->dbg);
2219 }
2220
2221 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2222 {
2223     struct kvm_set_guest_debug_data data;
2224
2225     data.dbg.control = reinject_trap;
2226
2227     if (cpu->singlestep_enabled) {
2228         data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2229     }
2230     kvm_arch_update_guest_debug(cpu, &data.dbg);
2231     data.cpu = cpu;
2232
2233     run_on_cpu(cpu, kvm_invoke_set_guest_debug, &data);
2234     return data.err;
2235 }
2236
2237 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2238                           target_ulong len, int type)
2239 {
2240     struct kvm_sw_breakpoint *bp;
2241     int err;
2242
2243     if (type == GDB_BREAKPOINT_SW) {
2244         bp = kvm_find_sw_breakpoint(cpu, addr);
2245         if (bp) {
2246             bp->use_count++;
2247             return 0;
2248         }
2249
2250         bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2251         bp->pc = addr;
2252         bp->use_count = 1;
2253         err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2254         if (err) {
2255             g_free(bp);
2256             return err;
2257         }
2258
2259         QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2260     } else {
2261         err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2262         if (err) {
2263             return err;
2264         }
2265     }
2266
2267     CPU_FOREACH(cpu) {
2268         err = kvm_update_guest_debug(cpu, 0);
2269         if (err) {
2270             return err;
2271         }
2272     }
2273     return 0;
2274 }
2275
2276 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2277                           target_ulong len, int type)
2278 {
2279     struct kvm_sw_breakpoint *bp;
2280     int err;
2281
2282     if (type == GDB_BREAKPOINT_SW) {
2283         bp = kvm_find_sw_breakpoint(cpu, addr);
2284         if (!bp) {
2285             return -ENOENT;
2286         }
2287
2288         if (bp->use_count > 1) {
2289             bp->use_count--;
2290             return 0;
2291         }
2292
2293         err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2294         if (err) {
2295             return err;
2296         }
2297
2298         QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2299         g_free(bp);
2300     } else {
2301         err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2302         if (err) {
2303             return err;
2304         }
2305     }
2306
2307     CPU_FOREACH(cpu) {
2308         err = kvm_update_guest_debug(cpu, 0);
2309         if (err) {
2310             return err;
2311         }
2312     }
2313     return 0;
2314 }
2315
2316 void kvm_remove_all_breakpoints(CPUState *cpu)
2317 {
2318     struct kvm_sw_breakpoint *bp, *next;
2319     KVMState *s = cpu->kvm_state;
2320     CPUState *tmpcpu;
2321
2322     QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2323         if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2324             /* Try harder to find a CPU that currently sees the breakpoint. */
2325             CPU_FOREACH(tmpcpu) {
2326                 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2327                     break;
2328                 }
2329             }
2330         }
2331         QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2332         g_free(bp);
2333     }
2334     kvm_arch_remove_all_hw_breakpoints();
2335
2336     CPU_FOREACH(cpu) {
2337         kvm_update_guest_debug(cpu, 0);
2338     }
2339 }
2340
2341 #else /* !KVM_CAP_SET_GUEST_DEBUG */
2342
2343 int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2344 {
2345     return -EINVAL;
2346 }
2347
2348 int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2349                           target_ulong len, int type)
2350 {
2351     return -EINVAL;
2352 }
2353
2354 int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2355                           target_ulong len, int type)
2356 {
2357     return -EINVAL;
2358 }
2359
2360 void kvm_remove_all_breakpoints(CPUState *cpu)
2361 {
2362 }
2363 #endif /* !KVM_CAP_SET_GUEST_DEBUG */
2364
2365 int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2366 {
2367     KVMState *s = kvm_state;
2368     struct kvm_signal_mask *sigmask;
2369     int r;
2370
2371     if (!sigset) {
2372         return kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, NULL);
2373     }
2374
2375     sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2376
2377     sigmask->len = s->sigmask_len;
2378     memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2379     r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2380     g_free(sigmask);
2381
2382     return r;
2383 }
2384 int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2385 {
2386     return kvm_arch_on_sigbus_vcpu(cpu, code, addr);
2387 }
2388
2389 int kvm_on_sigbus(int code, void *addr)
2390 {
2391     return kvm_arch_on_sigbus(code, addr);
2392 }
2393
2394 int kvm_create_device(KVMState *s, uint64_t type, bool test)
2395 {
2396     int ret;
2397     struct kvm_create_device create_dev;
2398
2399     create_dev.type = type;
2400     create_dev.fd = -1;
2401     create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2402
2403     if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2404         return -ENOTSUP;
2405     }
2406
2407     ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2408     if (ret) {
2409         return ret;
2410     }
2411
2412     return test ? 0 : create_dev.fd;
2413 }
2414
2415 bool kvm_device_supported(int vmfd, uint64_t type)
2416 {
2417     struct kvm_create_device create_dev = {
2418         .type = type,
2419         .fd = -1,
2420         .flags = KVM_CREATE_DEVICE_TEST,
2421     };
2422
2423     if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
2424         return false;
2425     }
2426
2427     return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
2428 }
2429
2430 int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2431 {
2432     struct kvm_one_reg reg;
2433     int r;
2434
2435     reg.id = id;
2436     reg.addr = (uintptr_t) source;
2437     r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
2438     if (r) {
2439         trace_kvm_failed_reg_set(id, strerror(-r));
2440     }
2441     return r;
2442 }
2443
2444 int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2445 {
2446     struct kvm_one_reg reg;
2447     int r;
2448
2449     reg.id = id;
2450     reg.addr = (uintptr_t) target;
2451     r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
2452     if (r) {
2453         trace_kvm_failed_reg_get(id, strerror(-r));
2454     }
2455     return r;
2456 }
2457
2458 static void kvm_accel_class_init(ObjectClass *oc, void *data)
2459 {
2460     AccelClass *ac = ACCEL_CLASS(oc);
2461     ac->name = "KVM";
2462     ac->init_machine = kvm_init;
2463     ac->allowed = &kvm_allowed;
2464 }
2465
2466 static const TypeInfo kvm_accel_type = {
2467     .name = TYPE_KVM_ACCEL,
2468     .parent = TYPE_ACCEL,
2469     .class_init = kvm_accel_class_init,
2470     .instance_size = sizeof(KVMState),
2471 };
2472
2473 static void kvm_type_init(void)
2474 {
2475     type_register_static(&kvm_accel_type);
2476 }
2477
2478 type_init(kvm_type_init);
This page took 0.149976 seconds and 4 git commands to generate.