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