Statistics
| Branch: | Revision:

root / kvm-all.c @ 8c0d577e

History | View | Annotate | Download (29.7 kB)

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-barrier.h"
25
#include "sysemu.h"
26
#include "hw/hw.h"
27
#include "gdbstub.h"
28
#include "kvm.h"
29

    
30
/* KVM uses PAGE_SIZE in it's definition of COALESCED_MMIO_MAX */
31
#define PAGE_SIZE TARGET_PAGE_SIZE
32

    
33
//#define DEBUG_KVM
34

    
35
#ifdef DEBUG_KVM
36
#define DPRINTF(fmt, ...) \
37
    do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
38
#else
39
#define DPRINTF(fmt, ...) \
40
    do { } while (0)
41
#endif
42

    
43
typedef struct KVMSlot
44
{
45
    target_phys_addr_t start_addr;
46
    ram_addr_t memory_size;
47
    ram_addr_t phys_offset;
48
    int slot;
49
    int flags;
50
} KVMSlot;
51

    
52
typedef struct kvm_dirty_log KVMDirtyLog;
53

    
54
struct KVMState
55
{
56
    KVMSlot slots[32];
57
    int fd;
58
    int vmfd;
59
    int coalesced_mmio;
60
#ifdef KVM_CAP_COALESCED_MMIO
61
    struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
62
#endif
63
    int broken_set_mem_region;
64
    int migration_log;
65
    int vcpu_events;
66
    int robust_singlestep;
67
#ifdef KVM_CAP_SET_GUEST_DEBUG
68
    struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
69
#endif
70
    int irqchip_in_kernel;
71
    int pit_in_kernel;
72
};
73

    
74
static KVMState *kvm_state;
75

    
76
static KVMSlot *kvm_alloc_slot(KVMState *s)
77
{
78
    int i;
79

    
80
    for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
81
        /* KVM private memory slots */
82
        if (i >= 8 && i < 12)
83
            continue;
84
        if (s->slots[i].memory_size == 0)
85
            return &s->slots[i];
86
    }
87

    
88
    fprintf(stderr, "%s: no free slot available\n", __func__);
89
    abort();
90
}
91

    
92
static KVMSlot *kvm_lookup_matching_slot(KVMState *s,
93
                                         target_phys_addr_t start_addr,
94
                                         target_phys_addr_t end_addr)
95
{
96
    int i;
97

    
98
    for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
99
        KVMSlot *mem = &s->slots[i];
100

    
101
        if (start_addr == mem->start_addr &&
102
            end_addr == mem->start_addr + mem->memory_size) {
103
            return mem;
104
        }
105
    }
106

    
107
    return NULL;
108
}
109

    
110
/*
111
 * Find overlapping slot with lowest start address
112
 */
113
static KVMSlot *kvm_lookup_overlapping_slot(KVMState *s,
114
                                            target_phys_addr_t start_addr,
115
                                            target_phys_addr_t end_addr)
116
{
117
    KVMSlot *found = NULL;
118
    int i;
119

    
120
    for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
121
        KVMSlot *mem = &s->slots[i];
122

    
123
        if (mem->memory_size == 0 ||
124
            (found && found->start_addr < mem->start_addr)) {
125
            continue;
126
        }
127

    
128
        if (end_addr > mem->start_addr &&
129
            start_addr < mem->start_addr + mem->memory_size) {
130
            found = mem;
131
        }
132
    }
133

    
134
    return found;
135
}
136

    
137
static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)
138
{
139
    struct kvm_userspace_memory_region mem;
140

    
141
    mem.slot = slot->slot;
142
    mem.guest_phys_addr = slot->start_addr;
143
    mem.memory_size = slot->memory_size;
144
    mem.userspace_addr = (unsigned long)qemu_get_ram_ptr(slot->phys_offset);
145
    mem.flags = slot->flags;
146
    if (s->migration_log) {
147
        mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;
148
    }
149
    return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
150
}
151

    
152
static void kvm_reset_vcpu(void *opaque)
153
{
154
    CPUState *env = opaque;
155

    
156
    kvm_arch_reset_vcpu(env);
157
}
158

    
159
int kvm_irqchip_in_kernel(void)
160
{
161
    return kvm_state->irqchip_in_kernel;
162
}
163

    
164
int kvm_pit_in_kernel(void)
165
{
166
    return kvm_state->pit_in_kernel;
167
}
168

    
169

    
170
int kvm_init_vcpu(CPUState *env)
171
{
172
    KVMState *s = kvm_state;
173
    long mmap_size;
174
    int ret;
175

    
176
    DPRINTF("kvm_init_vcpu\n");
177

    
178
    ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, env->cpu_index);
179
    if (ret < 0) {
180
        DPRINTF("kvm_create_vcpu failed\n");
181
        goto err;
182
    }
183

    
184
    env->kvm_fd = ret;
185
    env->kvm_state = s;
186

    
187
    mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
188
    if (mmap_size < 0) {
189
        DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
190
        goto err;
191
    }
192

    
193
    env->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
194
                        env->kvm_fd, 0);
195
    if (env->kvm_run == MAP_FAILED) {
196
        ret = -errno;
197
        DPRINTF("mmap'ing vcpu state failed\n");
198
        goto err;
199
    }
200

    
201
#ifdef KVM_CAP_COALESCED_MMIO
202
    if (s->coalesced_mmio && !s->coalesced_mmio_ring)
203
        s->coalesced_mmio_ring = (void *) env->kvm_run +
204
                s->coalesced_mmio * PAGE_SIZE;
205
#endif
206

    
207
    ret = kvm_arch_init_vcpu(env);
208
    if (ret == 0) {
209
        qemu_register_reset(kvm_reset_vcpu, env);
210
        kvm_arch_reset_vcpu(env);
211
    }
212
err:
213
    return ret;
214
}
215

    
216
/*
217
 * dirty pages logging control
218
 */
219
static int kvm_dirty_pages_log_change(target_phys_addr_t phys_addr,
220
                                      ram_addr_t size, int flags, int mask)
221
{
222
    KVMState *s = kvm_state;
223
    KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
224
    int old_flags;
225

    
226
    if (mem == NULL)  {
227
            fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
228
                    TARGET_FMT_plx "\n", __func__, phys_addr,
229
                    (target_phys_addr_t)(phys_addr + size - 1));
230
            return -EINVAL;
231
    }
232

    
233
    old_flags = mem->flags;
234

    
235
    flags = (mem->flags & ~mask) | flags;
236
    mem->flags = flags;
237

    
238
    /* If nothing changed effectively, no need to issue ioctl */
239
    if (s->migration_log) {
240
        flags |= KVM_MEM_LOG_DIRTY_PAGES;
241
    }
242
    if (flags == old_flags) {
243
            return 0;
244
    }
245

    
246
    return kvm_set_user_memory_region(s, mem);
247
}
248

    
249
int kvm_log_start(target_phys_addr_t phys_addr, ram_addr_t size)
250
{
251
        return kvm_dirty_pages_log_change(phys_addr, size,
252
                                          KVM_MEM_LOG_DIRTY_PAGES,
253
                                          KVM_MEM_LOG_DIRTY_PAGES);
254
}
255

    
256
int kvm_log_stop(target_phys_addr_t phys_addr, ram_addr_t size)
257
{
258
        return kvm_dirty_pages_log_change(phys_addr, size,
259
                                          0,
260
                                          KVM_MEM_LOG_DIRTY_PAGES);
261
}
262

    
263
static int kvm_set_migration_log(int enable)
264
{
265
    KVMState *s = kvm_state;
266
    KVMSlot *mem;
267
    int i, err;
268

    
269
    s->migration_log = enable;
270

    
271
    for (i = 0; i < ARRAY_SIZE(s->slots); i++) {
272
        mem = &s->slots[i];
273

    
274
        if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
275
            continue;
276
        }
277
        err = kvm_set_user_memory_region(s, mem);
278
        if (err) {
279
            return err;
280
        }
281
    }
282
    return 0;
283
}
284

    
285
static int test_le_bit(unsigned long nr, unsigned char *addr)
286
{
287
    return (addr[nr >> 3] >> (nr & 7)) & 1;
288
}
289

    
290
/**
291
 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
292
 * This function updates qemu's dirty bitmap using cpu_physical_memory_set_dirty().
293
 * This means all bits are set to dirty.
294
 *
295
 * @start_add: start of logged region.
296
 * @end_addr: end of logged region.
297
 */
298
static int kvm_physical_sync_dirty_bitmap(target_phys_addr_t start_addr,
299
                                          target_phys_addr_t end_addr)
300
{
301
    KVMState *s = kvm_state;
302
    unsigned long size, allocated_size = 0;
303
    target_phys_addr_t phys_addr;
304
    ram_addr_t addr;
305
    KVMDirtyLog d;
306
    KVMSlot *mem;
307
    int ret = 0;
308

    
309
    d.dirty_bitmap = NULL;
310
    while (start_addr < end_addr) {
311
        mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
312
        if (mem == NULL) {
313
            break;
314
        }
315

    
316
        size = ((mem->memory_size >> TARGET_PAGE_BITS) + 7) / 8;
317
        if (!d.dirty_bitmap) {
318
            d.dirty_bitmap = qemu_malloc(size);
319
        } else if (size > allocated_size) {
320
            d.dirty_bitmap = qemu_realloc(d.dirty_bitmap, size);
321
        }
322
        allocated_size = size;
323
        memset(d.dirty_bitmap, 0, allocated_size);
324

    
325
        d.slot = mem->slot;
326

    
327
        if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
328
            DPRINTF("ioctl failed %d\n", errno);
329
            ret = -1;
330
            break;
331
        }
332

    
333
        for (phys_addr = mem->start_addr, addr = mem->phys_offset;
334
             phys_addr < mem->start_addr + mem->memory_size;
335
             phys_addr += TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
336
            unsigned char *bitmap = (unsigned char *)d.dirty_bitmap;
337
            unsigned nr = (phys_addr - mem->start_addr) >> TARGET_PAGE_BITS;
338

    
339
            if (test_le_bit(nr, bitmap)) {
340
                cpu_physical_memory_set_dirty(addr);
341
            }
342
        }
343
        start_addr = phys_addr;
344
    }
345
    qemu_free(d.dirty_bitmap);
346

    
347
    return ret;
348
}
349

    
350
int kvm_coalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
351
{
352
    int ret = -ENOSYS;
353
#ifdef KVM_CAP_COALESCED_MMIO
354
    KVMState *s = kvm_state;
355

    
356
    if (s->coalesced_mmio) {
357
        struct kvm_coalesced_mmio_zone zone;
358

    
359
        zone.addr = start;
360
        zone.size = size;
361

    
362
        ret = kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
363
    }
364
#endif
365

    
366
    return ret;
367
}
368

    
369
int kvm_uncoalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)
370
{
371
    int ret = -ENOSYS;
372
#ifdef KVM_CAP_COALESCED_MMIO
373
    KVMState *s = kvm_state;
374

    
375
    if (s->coalesced_mmio) {
376
        struct kvm_coalesced_mmio_zone zone;
377

    
378
        zone.addr = start;
379
        zone.size = size;
380

    
381
        ret = kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
382
    }
383
#endif
384

    
385
    return ret;
386
}
387

    
388
int kvm_check_extension(KVMState *s, unsigned int extension)
389
{
390
    int ret;
391

    
392
    ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
393
    if (ret < 0) {
394
        ret = 0;
395
    }
396

    
397
    return ret;
398
}
399

    
400
static void kvm_set_phys_mem(target_phys_addr_t start_addr,
401
                             ram_addr_t size,
402
                             ram_addr_t phys_offset)
403
{
404
    KVMState *s = kvm_state;
405
    ram_addr_t flags = phys_offset & ~TARGET_PAGE_MASK;
406
    KVMSlot *mem, old;
407
    int err;
408

    
409
    if (start_addr & ~TARGET_PAGE_MASK) {
410
        if (flags >= IO_MEM_UNASSIGNED) {
411
            if (!kvm_lookup_overlapping_slot(s, start_addr,
412
                                             start_addr + size)) {
413
                return;
414
            }
415
            fprintf(stderr, "Unaligned split of a KVM memory slot\n");
416
        } else {
417
            fprintf(stderr, "Only page-aligned memory slots supported\n");
418
        }
419
        abort();
420
    }
421

    
422
    /* KVM does not support read-only slots */
423
    phys_offset &= ~IO_MEM_ROM;
424

    
425
    while (1) {
426
        mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
427
        if (!mem) {
428
            break;
429
        }
430

    
431
        if (flags < IO_MEM_UNASSIGNED && start_addr >= mem->start_addr &&
432
            (start_addr + size <= mem->start_addr + mem->memory_size) &&
433
            (phys_offset - start_addr == mem->phys_offset - mem->start_addr)) {
434
            /* The new slot fits into the existing one and comes with
435
             * identical parameters - nothing to be done. */
436
            return;
437
        }
438

    
439
        old = *mem;
440

    
441
        /* unregister the overlapping slot */
442
        mem->memory_size = 0;
443
        err = kvm_set_user_memory_region(s, mem);
444
        if (err) {
445
            fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
446
                    __func__, strerror(-err));
447
            abort();
448
        }
449

    
450
        /* Workaround for older KVM versions: we can't join slots, even not by
451
         * unregistering the previous ones and then registering the larger
452
         * slot. We have to maintain the existing fragmentation. Sigh.
453
         *
454
         * This workaround assumes that the new slot starts at the same
455
         * address as the first existing one. If not or if some overlapping
456
         * slot comes around later, we will fail (not seen in practice so far)
457
         * - and actually require a recent KVM version. */
458
        if (s->broken_set_mem_region &&
459
            old.start_addr == start_addr && old.memory_size < size &&
460
            flags < IO_MEM_UNASSIGNED) {
461
            mem = kvm_alloc_slot(s);
462
            mem->memory_size = old.memory_size;
463
            mem->start_addr = old.start_addr;
464
            mem->phys_offset = old.phys_offset;
465
            mem->flags = 0;
466

    
467
            err = kvm_set_user_memory_region(s, mem);
468
            if (err) {
469
                fprintf(stderr, "%s: error updating slot: %s\n", __func__,
470
                        strerror(-err));
471
                abort();
472
            }
473

    
474
            start_addr += old.memory_size;
475
            phys_offset += old.memory_size;
476
            size -= old.memory_size;
477
            continue;
478
        }
479

    
480
        /* register prefix slot */
481
        if (old.start_addr < start_addr) {
482
            mem = kvm_alloc_slot(s);
483
            mem->memory_size = start_addr - old.start_addr;
484
            mem->start_addr = old.start_addr;
485
            mem->phys_offset = old.phys_offset;
486
            mem->flags = 0;
487

    
488
            err = kvm_set_user_memory_region(s, mem);
489
            if (err) {
490
                fprintf(stderr, "%s: error registering prefix slot: %s\n",
491
                        __func__, strerror(-err));
492
                abort();
493
            }
494
        }
495

    
496
        /* register suffix slot */
497
        if (old.start_addr + old.memory_size > start_addr + size) {
498
            ram_addr_t size_delta;
499

    
500
            mem = kvm_alloc_slot(s);
501
            mem->start_addr = start_addr + size;
502
            size_delta = mem->start_addr - old.start_addr;
503
            mem->memory_size = old.memory_size - size_delta;
504
            mem->phys_offset = old.phys_offset + size_delta;
505
            mem->flags = 0;
506

    
507
            err = kvm_set_user_memory_region(s, mem);
508
            if (err) {
509
                fprintf(stderr, "%s: error registering suffix slot: %s\n",
510
                        __func__, strerror(-err));
511
                abort();
512
            }
513
        }
514
    }
515

    
516
    /* in case the KVM bug workaround already "consumed" the new slot */
517
    if (!size)
518
        return;
519

    
520
    /* KVM does not need to know about this memory */
521
    if (flags >= IO_MEM_UNASSIGNED)
522
        return;
523

    
524
    mem = kvm_alloc_slot(s);
525
    mem->memory_size = size;
526
    mem->start_addr = start_addr;
527
    mem->phys_offset = phys_offset;
528
    mem->flags = 0;
529

    
530
    err = kvm_set_user_memory_region(s, mem);
531
    if (err) {
532
        fprintf(stderr, "%s: error registering slot: %s\n", __func__,
533
                strerror(-err));
534
        abort();
535
    }
536
}
537

    
538
static void kvm_client_set_memory(struct CPUPhysMemoryClient *client,
539
                                  target_phys_addr_t start_addr,
540
                                  ram_addr_t size,
541
                                  ram_addr_t phys_offset)
542
{
543
        kvm_set_phys_mem(start_addr, size, phys_offset);
544
}
545

    
546
static int kvm_client_sync_dirty_bitmap(struct CPUPhysMemoryClient *client,
547
                                        target_phys_addr_t start_addr,
548
                                        target_phys_addr_t end_addr)
549
{
550
        return kvm_physical_sync_dirty_bitmap(start_addr, end_addr);
551
}
552

    
553
static int kvm_client_migration_log(struct CPUPhysMemoryClient *client,
554
                                    int enable)
555
{
556
        return kvm_set_migration_log(enable);
557
}
558

    
559
static CPUPhysMemoryClient kvm_cpu_phys_memory_client = {
560
        .set_memory = kvm_client_set_memory,
561
        .sync_dirty_bitmap = kvm_client_sync_dirty_bitmap,
562
        .migration_log = kvm_client_migration_log,
563
};
564

    
565
int kvm_init(int smp_cpus)
566
{
567
    static const char upgrade_note[] =
568
        "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
569
        "(see http://sourceforge.net/projects/kvm).\n";
570
    KVMState *s;
571
    int ret;
572
    int i;
573

    
574
    if (smp_cpus > 1) {
575
        fprintf(stderr, "No SMP KVM support, use '-smp 1'\n");
576
        return -EINVAL;
577
    }
578

    
579
    s = qemu_mallocz(sizeof(KVMState));
580

    
581
#ifdef KVM_CAP_SET_GUEST_DEBUG
582
    QTAILQ_INIT(&s->kvm_sw_breakpoints);
583
#endif
584
    for (i = 0; i < ARRAY_SIZE(s->slots); i++)
585
        s->slots[i].slot = i;
586

    
587
    s->vmfd = -1;
588
    s->fd = qemu_open("/dev/kvm", O_RDWR);
589
    if (s->fd == -1) {
590
        fprintf(stderr, "Could not access KVM kernel module: %m\n");
591
        ret = -errno;
592
        goto err;
593
    }
594

    
595
    ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
596
    if (ret < KVM_API_VERSION) {
597
        if (ret > 0)
598
            ret = -EINVAL;
599
        fprintf(stderr, "kvm version too old\n");
600
        goto err;
601
    }
602

    
603
    if (ret > KVM_API_VERSION) {
604
        ret = -EINVAL;
605
        fprintf(stderr, "kvm version not supported\n");
606
        goto err;
607
    }
608

    
609
    s->vmfd = kvm_ioctl(s, KVM_CREATE_VM, 0);
610
    if (s->vmfd < 0) {
611
#ifdef TARGET_S390X
612
        fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
613
                        "your host kernel command line\n");
614
#endif
615
        goto err;
616
    }
617

    
618
    /* initially, KVM allocated its own memory and we had to jump through
619
     * hooks to make phys_ram_base point to this.  Modern versions of KVM
620
     * just use a user allocated buffer so we can use regular pages
621
     * unmodified.  Make sure we have a sufficiently modern version of KVM.
622
     */
623
    if (!kvm_check_extension(s, KVM_CAP_USER_MEMORY)) {
624
        ret = -EINVAL;
625
        fprintf(stderr, "kvm does not support KVM_CAP_USER_MEMORY\n%s",
626
                upgrade_note);
627
        goto err;
628
    }
629

    
630
    /* There was a nasty bug in < kvm-80 that prevents memory slots from being
631
     * destroyed properly.  Since we rely on this capability, refuse to work
632
     * with any kernel without this capability. */
633
    if (!kvm_check_extension(s, KVM_CAP_DESTROY_MEMORY_REGION_WORKS)) {
634
        ret = -EINVAL;
635

    
636
        fprintf(stderr,
637
                "KVM kernel module broken (DESTROY_MEMORY_REGION).\n%s",
638
                upgrade_note);
639
        goto err;
640
    }
641

    
642
    s->coalesced_mmio = 0;
643
#ifdef KVM_CAP_COALESCED_MMIO
644
    s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
645
    s->coalesced_mmio_ring = NULL;
646
#endif
647

    
648
    s->broken_set_mem_region = 1;
649
#ifdef KVM_CAP_JOIN_MEMORY_REGIONS_WORKS
650
    ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
651
    if (ret > 0) {
652
        s->broken_set_mem_region = 0;
653
    }
654
#endif
655

    
656
    s->vcpu_events = 0;
657
#ifdef KVM_CAP_VCPU_EVENTS
658
    s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
659
#endif
660

    
661
    s->robust_singlestep = 0;
662
#ifdef KVM_CAP_X86_ROBUST_SINGLESTEP
663
    s->robust_singlestep =
664
        kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
665
#endif
666

    
667
    ret = kvm_arch_init(s, smp_cpus);
668
    if (ret < 0)
669
        goto err;
670

    
671
    kvm_state = s;
672
    cpu_register_phys_memory_client(&kvm_cpu_phys_memory_client);
673

    
674
    return 0;
675

    
676
err:
677
    if (s) {
678
        if (s->vmfd != -1)
679
            close(s->vmfd);
680
        if (s->fd != -1)
681
            close(s->fd);
682
    }
683
    qemu_free(s);
684

    
685
    return ret;
686
}
687

    
688
static int kvm_handle_io(uint16_t port, void *data, int direction, int size,
689
                         uint32_t count)
690
{
691
    int i;
692
    uint8_t *ptr = data;
693

    
694
    for (i = 0; i < count; i++) {
695
        if (direction == KVM_EXIT_IO_IN) {
696
            switch (size) {
697
            case 1:
698
                stb_p(ptr, cpu_inb(port));
699
                break;
700
            case 2:
701
                stw_p(ptr, cpu_inw(port));
702
                break;
703
            case 4:
704
                stl_p(ptr, cpu_inl(port));
705
                break;
706
            }
707
        } else {
708
            switch (size) {
709
            case 1:
710
                cpu_outb(port, ldub_p(ptr));
711
                break;
712
            case 2:
713
                cpu_outw(port, lduw_p(ptr));
714
                break;
715
            case 4:
716
                cpu_outl(port, ldl_p(ptr));
717
                break;
718
            }
719
        }
720

    
721
        ptr += size;
722
    }
723

    
724
    return 1;
725
}
726

    
727
void kvm_flush_coalesced_mmio_buffer(void)
728
{
729
#ifdef KVM_CAP_COALESCED_MMIO
730
    KVMState *s = kvm_state;
731
    if (s->coalesced_mmio_ring) {
732
        struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
733
        while (ring->first != ring->last) {
734
            struct kvm_coalesced_mmio *ent;
735

    
736
            ent = &ring->coalesced_mmio[ring->first];
737

    
738
            cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
739
            smp_wmb();
740
            ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
741
        }
742
    }
743
#endif
744
}
745

    
746
void kvm_cpu_synchronize_state(CPUState *env)
747
{
748
    if (!env->kvm_vcpu_dirty) {
749
        kvm_arch_get_registers(env);
750
        env->kvm_vcpu_dirty = 1;
751
    }
752
}
753

    
754
void kvm_cpu_synchronize_post_reset(CPUState *env)
755
{
756
    kvm_arch_put_registers(env, KVM_PUT_RESET_STATE);
757
    env->kvm_vcpu_dirty = 0;
758
}
759

    
760
void kvm_cpu_synchronize_post_init(CPUState *env)
761
{
762
    kvm_arch_put_registers(env, KVM_PUT_FULL_STATE);
763
    env->kvm_vcpu_dirty = 0;
764
}
765

    
766
int kvm_cpu_exec(CPUState *env)
767
{
768
    struct kvm_run *run = env->kvm_run;
769
    int ret;
770

    
771
    DPRINTF("kvm_cpu_exec()\n");
772

    
773
    do {
774
#ifndef CONFIG_IOTHREAD
775
        if (env->exit_request) {
776
            DPRINTF("interrupt exit requested\n");
777
            ret = 0;
778
            break;
779
        }
780
#endif
781

    
782
        if (env->kvm_vcpu_dirty) {
783
            kvm_arch_put_registers(env, KVM_PUT_RUNTIME_STATE);
784
            env->kvm_vcpu_dirty = 0;
785
        }
786

    
787
        kvm_arch_pre_run(env, run);
788
        qemu_mutex_unlock_iothread();
789
        ret = kvm_vcpu_ioctl(env, KVM_RUN, 0);
790
        qemu_mutex_lock_iothread();
791
        kvm_arch_post_run(env, run);
792

    
793
        if (ret == -EINTR || ret == -EAGAIN) {
794
            cpu_exit(env);
795
            DPRINTF("io window exit\n");
796
            ret = 0;
797
            break;
798
        }
799

    
800
        if (ret < 0) {
801
            DPRINTF("kvm run failed %s\n", strerror(-ret));
802
            abort();
803
        }
804

    
805
        kvm_flush_coalesced_mmio_buffer();
806

    
807
        ret = 0; /* exit loop */
808
        switch (run->exit_reason) {
809
        case KVM_EXIT_IO:
810
            DPRINTF("handle_io\n");
811
            ret = kvm_handle_io(run->io.port,
812
                                (uint8_t *)run + run->io.data_offset,
813
                                run->io.direction,
814
                                run->io.size,
815
                                run->io.count);
816
            break;
817
        case KVM_EXIT_MMIO:
818
            DPRINTF("handle_mmio\n");
819
            cpu_physical_memory_rw(run->mmio.phys_addr,
820
                                   run->mmio.data,
821
                                   run->mmio.len,
822
                                   run->mmio.is_write);
823
            ret = 1;
824
            break;
825
        case KVM_EXIT_IRQ_WINDOW_OPEN:
826
            DPRINTF("irq_window_open\n");
827
            break;
828
        case KVM_EXIT_SHUTDOWN:
829
            DPRINTF("shutdown\n");
830
            qemu_system_reset_request();
831
            ret = 1;
832
            break;
833
        case KVM_EXIT_UNKNOWN:
834
            DPRINTF("kvm_exit_unknown\n");
835
            break;
836
        case KVM_EXIT_FAIL_ENTRY:
837
            DPRINTF("kvm_exit_fail_entry\n");
838
            break;
839
        case KVM_EXIT_EXCEPTION:
840
            DPRINTF("kvm_exit_exception\n");
841
            break;
842
        case KVM_EXIT_DEBUG:
843
            DPRINTF("kvm_exit_debug\n");
844
#ifdef KVM_CAP_SET_GUEST_DEBUG
845
            if (kvm_arch_debug(&run->debug.arch)) {
846
                gdb_set_stop_cpu(env);
847
                vm_stop(EXCP_DEBUG);
848
                env->exception_index = EXCP_DEBUG;
849
                return 0;
850
            }
851
            /* re-enter, this exception was guest-internal */
852
            ret = 1;
853
#endif /* KVM_CAP_SET_GUEST_DEBUG */
854
            break;
855
        default:
856
            DPRINTF("kvm_arch_handle_exit\n");
857
            ret = kvm_arch_handle_exit(env, run);
858
            break;
859
        }
860
    } while (ret > 0);
861

    
862
    if (env->exit_request) {
863
        env->exit_request = 0;
864
        env->exception_index = EXCP_INTERRUPT;
865
    }
866

    
867
    return ret;
868
}
869

    
870
int kvm_ioctl(KVMState *s, int type, ...)
871
{
872
    int ret;
873
    void *arg;
874
    va_list ap;
875

    
876
    va_start(ap, type);
877
    arg = va_arg(ap, void *);
878
    va_end(ap);
879

    
880
    ret = ioctl(s->fd, type, arg);
881
    if (ret == -1)
882
        ret = -errno;
883

    
884
    return ret;
885
}
886

    
887
int kvm_vm_ioctl(KVMState *s, int type, ...)
888
{
889
    int ret;
890
    void *arg;
891
    va_list ap;
892

    
893
    va_start(ap, type);
894
    arg = va_arg(ap, void *);
895
    va_end(ap);
896

    
897
    ret = ioctl(s->vmfd, type, arg);
898
    if (ret == -1)
899
        ret = -errno;
900

    
901
    return ret;
902
}
903

    
904
int kvm_vcpu_ioctl(CPUState *env, int type, ...)
905
{
906
    int ret;
907
    void *arg;
908
    va_list ap;
909

    
910
    va_start(ap, type);
911
    arg = va_arg(ap, void *);
912
    va_end(ap);
913

    
914
    ret = ioctl(env->kvm_fd, type, arg);
915
    if (ret == -1)
916
        ret = -errno;
917

    
918
    return ret;
919
}
920

    
921
int kvm_has_sync_mmu(void)
922
{
923
#ifdef KVM_CAP_SYNC_MMU
924
    KVMState *s = kvm_state;
925

    
926
    return kvm_check_extension(s, KVM_CAP_SYNC_MMU);
927
#else
928
    return 0;
929
#endif
930
}
931

    
932
int kvm_has_vcpu_events(void)
933
{
934
    return kvm_state->vcpu_events;
935
}
936

    
937
int kvm_has_robust_singlestep(void)
938
{
939
    return kvm_state->robust_singlestep;
940
}
941

    
942
void kvm_setup_guest_memory(void *start, size_t size)
943
{
944
    if (!kvm_has_sync_mmu()) {
945
#ifdef MADV_DONTFORK
946
        int ret = madvise(start, size, MADV_DONTFORK);
947

    
948
        if (ret) {
949
            perror("madvice");
950
            exit(1);
951
        }
952
#else
953
        fprintf(stderr,
954
                "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
955
        exit(1);
956
#endif
957
    }
958
}
959

    
960
#ifdef KVM_CAP_SET_GUEST_DEBUG
961
static void on_vcpu(CPUState *env, void (*func)(void *data), void *data)
962
{
963
#ifdef CONFIG_IOTHREAD
964
    if (env != cpu_single_env) {
965
        abort();
966
    }
967
#endif
968
    func(data);
969
}
970

    
971
struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *env,
972
                                                 target_ulong pc)
973
{
974
    struct kvm_sw_breakpoint *bp;
975

    
976
    QTAILQ_FOREACH(bp, &env->kvm_state->kvm_sw_breakpoints, entry) {
977
        if (bp->pc == pc)
978
            return bp;
979
    }
980
    return NULL;
981
}
982

    
983
int kvm_sw_breakpoints_active(CPUState *env)
984
{
985
    return !QTAILQ_EMPTY(&env->kvm_state->kvm_sw_breakpoints);
986
}
987

    
988
struct kvm_set_guest_debug_data {
989
    struct kvm_guest_debug dbg;
990
    CPUState *env;
991
    int err;
992
};
993

    
994
static void kvm_invoke_set_guest_debug(void *data)
995
{
996
    struct kvm_set_guest_debug_data *dbg_data = data;
997
    CPUState *env = dbg_data->env;
998

    
999
    dbg_data->err = kvm_vcpu_ioctl(env, KVM_SET_GUEST_DEBUG, &dbg_data->dbg);
1000
}
1001

    
1002
int kvm_update_guest_debug(CPUState *env, unsigned long reinject_trap)
1003
{
1004
    struct kvm_set_guest_debug_data data;
1005

    
1006
    data.dbg.control = reinject_trap;
1007

    
1008
    if (env->singlestep_enabled) {
1009
        data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
1010
    }
1011
    kvm_arch_update_guest_debug(env, &data.dbg);
1012
    data.env = env;
1013

    
1014
    on_vcpu(env, kvm_invoke_set_guest_debug, &data);
1015
    return data.err;
1016
}
1017

    
1018
int kvm_insert_breakpoint(CPUState *current_env, target_ulong addr,
1019
                          target_ulong len, int type)
1020
{
1021
    struct kvm_sw_breakpoint *bp;
1022
    CPUState *env;
1023
    int err;
1024

    
1025
    if (type == GDB_BREAKPOINT_SW) {
1026
        bp = kvm_find_sw_breakpoint(current_env, addr);
1027
        if (bp) {
1028
            bp->use_count++;
1029
            return 0;
1030
        }
1031

    
1032
        bp = qemu_malloc(sizeof(struct kvm_sw_breakpoint));
1033
        if (!bp)
1034
            return -ENOMEM;
1035

    
1036
        bp->pc = addr;
1037
        bp->use_count = 1;
1038
        err = kvm_arch_insert_sw_breakpoint(current_env, bp);
1039
        if (err) {
1040
            free(bp);
1041
            return err;
1042
        }
1043

    
1044
        QTAILQ_INSERT_HEAD(&current_env->kvm_state->kvm_sw_breakpoints,
1045
                          bp, entry);
1046
    } else {
1047
        err = kvm_arch_insert_hw_breakpoint(addr, len, type);
1048
        if (err)
1049
            return err;
1050
    }
1051

    
1052
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
1053
        err = kvm_update_guest_debug(env, 0);
1054
        if (err)
1055
            return err;
1056
    }
1057
    return 0;
1058
}
1059

    
1060
int kvm_remove_breakpoint(CPUState *current_env, target_ulong addr,
1061
                          target_ulong len, int type)
1062
{
1063
    struct kvm_sw_breakpoint *bp;
1064
    CPUState *env;
1065
    int err;
1066

    
1067
    if (type == GDB_BREAKPOINT_SW) {
1068
        bp = kvm_find_sw_breakpoint(current_env, addr);
1069
        if (!bp)
1070
            return -ENOENT;
1071

    
1072
        if (bp->use_count > 1) {
1073
            bp->use_count--;
1074
            return 0;
1075
        }
1076

    
1077
        err = kvm_arch_remove_sw_breakpoint(current_env, bp);
1078
        if (err)
1079
            return err;
1080

    
1081
        QTAILQ_REMOVE(&current_env->kvm_state->kvm_sw_breakpoints, bp, entry);
1082
        qemu_free(bp);
1083
    } else {
1084
        err = kvm_arch_remove_hw_breakpoint(addr, len, type);
1085
        if (err)
1086
            return err;
1087
    }
1088

    
1089
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
1090
        err = kvm_update_guest_debug(env, 0);
1091
        if (err)
1092
            return err;
1093
    }
1094
    return 0;
1095
}
1096

    
1097
void kvm_remove_all_breakpoints(CPUState *current_env)
1098
{
1099
    struct kvm_sw_breakpoint *bp, *next;
1100
    KVMState *s = current_env->kvm_state;
1101
    CPUState *env;
1102

    
1103
    QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
1104
        if (kvm_arch_remove_sw_breakpoint(current_env, bp) != 0) {
1105
            /* Try harder to find a CPU that currently sees the breakpoint. */
1106
            for (env = first_cpu; env != NULL; env = env->next_cpu) {
1107
                if (kvm_arch_remove_sw_breakpoint(env, bp) == 0)
1108
                    break;
1109
            }
1110
        }
1111
    }
1112
    kvm_arch_remove_all_hw_breakpoints();
1113

    
1114
    for (env = first_cpu; env != NULL; env = env->next_cpu)
1115
        kvm_update_guest_debug(env, 0);
1116
}
1117

    
1118
#else /* !KVM_CAP_SET_GUEST_DEBUG */
1119

    
1120
int kvm_update_guest_debug(CPUState *env, unsigned long reinject_trap)
1121
{
1122
    return -EINVAL;
1123
}
1124

    
1125
int kvm_insert_breakpoint(CPUState *current_env, target_ulong addr,
1126
                          target_ulong len, int type)
1127
{
1128
    return -EINVAL;
1129
}
1130

    
1131
int kvm_remove_breakpoint(CPUState *current_env, target_ulong addr,
1132
                          target_ulong len, int type)
1133
{
1134
    return -EINVAL;
1135
}
1136

    
1137
void kvm_remove_all_breakpoints(CPUState *current_env)
1138
{
1139
}
1140
#endif /* !KVM_CAP_SET_GUEST_DEBUG */
1141

    
1142
int kvm_set_signal_mask(CPUState *env, const sigset_t *sigset)
1143
{
1144
    struct kvm_signal_mask *sigmask;
1145
    int r;
1146

    
1147
    if (!sigset)
1148
        return kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, NULL);
1149

    
1150
    sigmask = qemu_malloc(sizeof(*sigmask) + sizeof(*sigset));
1151

    
1152
    sigmask->len = 8;
1153
    memcpy(sigmask->sigset, sigset, sizeof(*sigset));
1154
    r = kvm_vcpu_ioctl(env, KVM_SET_SIGNAL_MASK, sigmask);
1155
    free(sigmask);
1156

    
1157
    return r;
1158
}
1159

    
1160
#ifdef KVM_IOEVENTFD
1161
int kvm_set_ioeventfd_pio_word(int fd, uint16_t addr, uint16_t val, bool assign)
1162
{
1163
    struct kvm_ioeventfd kick = {
1164
        .datamatch = val,
1165
        .addr = addr,
1166
        .len = 2,
1167
        .flags = KVM_IOEVENTFD_FLAG_DATAMATCH | KVM_IOEVENTFD_FLAG_PIO,
1168
        .fd = fd,
1169
    };
1170
    int r;
1171
    if (!kvm_enabled())
1172
        return -ENOSYS;
1173
    if (!assign)
1174
        kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1175
    r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
1176
    if (r < 0)
1177
        return r;
1178
    return 0;
1179
}
1180
#endif