1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (C) 2020-2023 Loongson Technology Corporation Limited
4 */
5
6 #include <linux/highmem.h>
7 #include <linux/hugetlb.h>
8 #include <linux/kvm_host.h>
9 #include <linux/page-flags.h>
10 #include <linux/uaccess.h>
11 #include <asm/mmu_context.h>
12 #include <asm/pgalloc.h>
13 #include <asm/tlb.h>
14 #include <asm/kvm_mmu.h>
15
kvm_hugepage_capable(struct kvm_memory_slot * slot)16 static inline bool kvm_hugepage_capable(struct kvm_memory_slot *slot)
17 {
18 return slot->arch.flags & KVM_MEM_HUGEPAGE_CAPABLE;
19 }
20
kvm_hugepage_incapable(struct kvm_memory_slot * slot)21 static inline bool kvm_hugepage_incapable(struct kvm_memory_slot *slot)
22 {
23 return slot->arch.flags & KVM_MEM_HUGEPAGE_INCAPABLE;
24 }
25
kvm_ptw_prepare(struct kvm * kvm,kvm_ptw_ctx * ctx)26 static inline void kvm_ptw_prepare(struct kvm *kvm, kvm_ptw_ctx *ctx)
27 {
28 ctx->level = kvm->arch.root_level;
29 /* pte table */
30 ctx->invalid_ptes = kvm->arch.invalid_ptes;
31 ctx->pte_shifts = kvm->arch.pte_shifts;
32 ctx->pgtable_shift = ctx->pte_shifts[ctx->level];
33 ctx->invalid_entry = ctx->invalid_ptes[ctx->level];
34 ctx->opaque = kvm;
35 }
36
37 /*
38 * Mark a range of guest physical address space old (all accesses fault) in the
39 * VM's GPA page table to allow detection of commonly used pages.
40 */
kvm_mkold_pte(kvm_pte_t * pte,phys_addr_t addr,kvm_ptw_ctx * ctx)41 static int kvm_mkold_pte(kvm_pte_t *pte, phys_addr_t addr, kvm_ptw_ctx *ctx)
42 {
43 if (kvm_pte_young(*pte)) {
44 *pte = kvm_pte_mkold(*pte);
45 return 1;
46 }
47
48 return 0;
49 }
50
51 /*
52 * Mark a range of guest physical address space clean (writes fault) in the VM's
53 * GPA page table to allow dirty page tracking.
54 */
kvm_mkclean_pte(kvm_pte_t * pte,phys_addr_t addr,kvm_ptw_ctx * ctx)55 static int kvm_mkclean_pte(kvm_pte_t *pte, phys_addr_t addr, kvm_ptw_ctx *ctx)
56 {
57 gfn_t offset;
58 kvm_pte_t val;
59
60 val = *pte;
61 /*
62 * For kvm_arch_mmu_enable_log_dirty_pt_masked with mask, start and end
63 * may cross hugepage, for first huge page parameter addr is equal to
64 * start, however for the second huge page addr is base address of
65 * this huge page, rather than start or end address
66 */
67 if ((ctx->flag & _KVM_HAS_PGMASK) && !kvm_pte_huge(val)) {
68 offset = (addr >> PAGE_SHIFT) - ctx->gfn;
69 if (!(BIT(offset) & ctx->mask))
70 return 0;
71 }
72
73 /*
74 * Need not split huge page now, just set write-proect pte bit
75 * Split huge page until next write fault
76 */
77 if (kvm_pte_dirty(val)) {
78 *pte = kvm_pte_mkclean(val);
79 return 1;
80 }
81
82 return 0;
83 }
84
85 /*
86 * Clear pte entry
87 */
kvm_flush_pte(kvm_pte_t * pte,phys_addr_t addr,kvm_ptw_ctx * ctx)88 static int kvm_flush_pte(kvm_pte_t *pte, phys_addr_t addr, kvm_ptw_ctx *ctx)
89 {
90 struct kvm *kvm;
91
92 kvm = ctx->opaque;
93 if (ctx->level)
94 kvm->stat.hugepages--;
95 else
96 kvm->stat.pages--;
97
98 kvm_set_pte(pte, ctx->invalid_entry);
99
100 return 1;
101 }
102
103 /*
104 * kvm_pgd_alloc() - Allocate and initialise a KVM GPA page directory.
105 *
106 * Allocate a blank KVM GPA page directory (PGD) for representing guest physical
107 * to host physical page mappings.
108 *
109 * Returns: Pointer to new KVM GPA page directory.
110 * NULL on allocation failure.
111 */
kvm_pgd_alloc(void)112 kvm_pte_t *kvm_pgd_alloc(void)
113 {
114 kvm_pte_t *pgd;
115
116 pgd = (kvm_pte_t *)__get_free_pages(GFP_KERNEL, 0);
117 if (pgd)
118 pgd_init((void *)pgd);
119
120 return pgd;
121 }
122
_kvm_pte_init(void * addr,unsigned long val)123 static void _kvm_pte_init(void *addr, unsigned long val)
124 {
125 unsigned long *p, *end;
126
127 p = (unsigned long *)addr;
128 end = p + PTRS_PER_PTE;
129 do {
130 p[0] = val;
131 p[1] = val;
132 p[2] = val;
133 p[3] = val;
134 p[4] = val;
135 p += 8;
136 p[-3] = val;
137 p[-2] = val;
138 p[-1] = val;
139 } while (p != end);
140 }
141
142 /*
143 * Caller must hold kvm->mm_lock
144 *
145 * Walk the page tables of kvm to find the PTE corresponding to the
146 * address @addr. If page tables don't exist for @addr, they will be created
147 * from the MMU cache if @cache is not NULL.
148 */
kvm_populate_gpa(struct kvm * kvm,struct kvm_mmu_memory_cache * cache,unsigned long addr,int level)149 static kvm_pte_t *kvm_populate_gpa(struct kvm *kvm,
150 struct kvm_mmu_memory_cache *cache,
151 unsigned long addr, int level)
152 {
153 kvm_ptw_ctx ctx;
154 kvm_pte_t *entry, *child;
155
156 kvm_ptw_prepare(kvm, &ctx);
157 child = kvm->arch.pgd;
158 while (ctx.level > level) {
159 entry = kvm_pgtable_offset(&ctx, child, addr);
160 if (kvm_pte_none(&ctx, entry)) {
161 if (!cache)
162 return NULL;
163
164 child = kvm_mmu_memory_cache_alloc(cache);
165 _kvm_pte_init(child, ctx.invalid_ptes[ctx.level - 1]);
166 smp_wmb(); /* Make pte visible before pmd */
167 kvm_set_pte(entry, __pa(child));
168 } else if (kvm_pte_huge(*entry)) {
169 return entry;
170 } else
171 child = (kvm_pte_t *)__va(PHYSADDR(*entry));
172 kvm_ptw_enter(&ctx);
173 }
174
175 entry = kvm_pgtable_offset(&ctx, child, addr);
176
177 return entry;
178 }
179
180 /*
181 * Page walker for VM shadow mmu at last level
182 * The last level is small pte page or huge pmd page
183 */
kvm_ptw_leaf(kvm_pte_t * dir,phys_addr_t addr,phys_addr_t end,kvm_ptw_ctx * ctx)184 static int kvm_ptw_leaf(kvm_pte_t *dir, phys_addr_t addr, phys_addr_t end, kvm_ptw_ctx *ctx)
185 {
186 int ret;
187 phys_addr_t next, start, size;
188 struct list_head *list;
189 kvm_pte_t *entry, *child;
190
191 ret = 0;
192 start = addr;
193 child = (kvm_pte_t *)__va(PHYSADDR(*dir));
194 entry = kvm_pgtable_offset(ctx, child, addr);
195 do {
196 next = addr + (0x1UL << ctx->pgtable_shift);
197 if (!kvm_pte_present(ctx, entry))
198 continue;
199
200 ret |= ctx->ops(entry, addr, ctx);
201 } while (entry++, addr = next, addr < end);
202
203 if (kvm_need_flush(ctx)) {
204 size = 0x1UL << (ctx->pgtable_shift + PAGE_SHIFT - 3);
205 if (start + size == end) {
206 list = (struct list_head *)child;
207 list_add_tail(list, &ctx->list);
208 *dir = ctx->invalid_ptes[ctx->level + 1];
209 }
210 }
211
212 return ret;
213 }
214
215 /*
216 * Page walker for VM shadow mmu at page table dir level
217 */
kvm_ptw_dir(kvm_pte_t * dir,phys_addr_t addr,phys_addr_t end,kvm_ptw_ctx * ctx)218 static int kvm_ptw_dir(kvm_pte_t *dir, phys_addr_t addr, phys_addr_t end, kvm_ptw_ctx *ctx)
219 {
220 int ret;
221 phys_addr_t next, start, size;
222 struct list_head *list;
223 kvm_pte_t *entry, *child;
224
225 ret = 0;
226 start = addr;
227 child = (kvm_pte_t *)__va(PHYSADDR(*dir));
228 entry = kvm_pgtable_offset(ctx, child, addr);
229 do {
230 next = kvm_pgtable_addr_end(ctx, addr, end);
231 if (!kvm_pte_present(ctx, entry))
232 continue;
233
234 if (kvm_pte_huge(*entry)) {
235 ret |= ctx->ops(entry, addr, ctx);
236 continue;
237 }
238
239 kvm_ptw_enter(ctx);
240 if (ctx->level == 0)
241 ret |= kvm_ptw_leaf(entry, addr, next, ctx);
242 else
243 ret |= kvm_ptw_dir(entry, addr, next, ctx);
244 kvm_ptw_exit(ctx);
245 } while (entry++, addr = next, addr < end);
246
247 if (kvm_need_flush(ctx)) {
248 size = 0x1UL << (ctx->pgtable_shift + PAGE_SHIFT - 3);
249 if (start + size == end) {
250 list = (struct list_head *)child;
251 list_add_tail(list, &ctx->list);
252 *dir = ctx->invalid_ptes[ctx->level + 1];
253 }
254 }
255
256 return ret;
257 }
258
259 /*
260 * Page walker for VM shadow mmu at page root table
261 */
kvm_ptw_top(kvm_pte_t * dir,phys_addr_t addr,phys_addr_t end,kvm_ptw_ctx * ctx)262 static int kvm_ptw_top(kvm_pte_t *dir, phys_addr_t addr, phys_addr_t end, kvm_ptw_ctx *ctx)
263 {
264 int ret;
265 phys_addr_t next;
266 kvm_pte_t *entry;
267
268 ret = 0;
269 entry = kvm_pgtable_offset(ctx, dir, addr);
270 do {
271 next = kvm_pgtable_addr_end(ctx, addr, end);
272 if (!kvm_pte_present(ctx, entry))
273 continue;
274
275 kvm_ptw_enter(ctx);
276 ret |= kvm_ptw_dir(entry, addr, next, ctx);
277 kvm_ptw_exit(ctx);
278 } while (entry++, addr = next, addr < end);
279
280 return ret;
281 }
282
283 /*
284 * kvm_flush_range() - Flush a range of guest physical addresses.
285 * @kvm: KVM pointer.
286 * @start_gfn: Guest frame number of first page in GPA range to flush.
287 * @end_gfn: Guest frame number of last page in GPA range to flush.
288 * @lock: Whether to hold mmu_lock or not
289 *
290 * Flushes a range of GPA mappings from the GPA page tables.
291 */
kvm_flush_range(struct kvm * kvm,gfn_t start_gfn,gfn_t end_gfn,int lock)292 static void kvm_flush_range(struct kvm *kvm, gfn_t start_gfn, gfn_t end_gfn, int lock)
293 {
294 int ret;
295 kvm_ptw_ctx ctx;
296 struct list_head *pos, *temp;
297
298 ctx.ops = kvm_flush_pte;
299 ctx.flag = _KVM_FLUSH_PGTABLE;
300 kvm_ptw_prepare(kvm, &ctx);
301 INIT_LIST_HEAD(&ctx.list);
302
303 if (lock) {
304 spin_lock(&kvm->mmu_lock);
305 ret = kvm_ptw_top(kvm->arch.pgd, start_gfn << PAGE_SHIFT,
306 end_gfn << PAGE_SHIFT, &ctx);
307 spin_unlock(&kvm->mmu_lock);
308 } else
309 ret = kvm_ptw_top(kvm->arch.pgd, start_gfn << PAGE_SHIFT,
310 end_gfn << PAGE_SHIFT, &ctx);
311
312 /* Flush vpid for each vCPU individually */
313 if (ret)
314 kvm_flush_remote_tlbs(kvm);
315
316 /*
317 * free pte table page after mmu_lock
318 * the pte table page is linked together with ctx.list
319 */
320 list_for_each_safe(pos, temp, &ctx.list) {
321 list_del(pos);
322 free_page((unsigned long)pos);
323 }
324 }
325
326 /*
327 * kvm_mkclean_gpa_pt() - Make a range of guest physical addresses clean.
328 * @kvm: KVM pointer.
329 * @start_gfn: Guest frame number of first page in GPA range to flush.
330 * @end_gfn: Guest frame number of last page in GPA range to flush.
331 *
332 * Make a range of GPA mappings clean so that guest writes will fault and
333 * trigger dirty page logging.
334 *
335 * The caller must hold the @kvm->mmu_lock spinlock.
336 *
337 * Returns: Whether any GPA mappings were modified, which would require
338 * derived mappings (GVA page tables & TLB enties) to be
339 * invalidated.
340 */
kvm_mkclean_gpa_pt(struct kvm * kvm,gfn_t start_gfn,gfn_t end_gfn)341 static int kvm_mkclean_gpa_pt(struct kvm *kvm, gfn_t start_gfn, gfn_t end_gfn)
342 {
343 kvm_ptw_ctx ctx;
344
345 ctx.ops = kvm_mkclean_pte;
346 ctx.flag = 0;
347 kvm_ptw_prepare(kvm, &ctx);
348 return kvm_ptw_top(kvm->arch.pgd, start_gfn << PAGE_SHIFT, end_gfn << PAGE_SHIFT, &ctx);
349 }
350
351 /*
352 * kvm_arch_mmu_enable_log_dirty_pt_masked() - write protect dirty pages
353 * @kvm: The KVM pointer
354 * @slot: The memory slot associated with mask
355 * @gfn_offset: The gfn offset in memory slot
356 * @mask: The mask of dirty pages at offset 'gfn_offset' in this memory
357 * slot to be write protected
358 *
359 * Walks bits set in mask write protects the associated pte's. Caller must
360 * acquire @kvm->mmu_lock.
361 */
kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn_offset,unsigned long mask)362 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
363 struct kvm_memory_slot *slot, gfn_t gfn_offset, unsigned long mask)
364 {
365 kvm_ptw_ctx ctx;
366 gfn_t base_gfn = slot->base_gfn + gfn_offset;
367 gfn_t start = base_gfn + __ffs(mask);
368 gfn_t end = base_gfn + __fls(mask) + 1;
369
370 ctx.ops = kvm_mkclean_pte;
371 ctx.flag = _KVM_HAS_PGMASK;
372 ctx.mask = mask;
373 ctx.gfn = base_gfn;
374 kvm_ptw_prepare(kvm, &ctx);
375
376 kvm_ptw_top(kvm->arch.pgd, start << PAGE_SHIFT, end << PAGE_SHIFT, &ctx);
377 }
378
kvm_arch_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)379 int kvm_arch_prepare_memory_region(struct kvm *kvm, const struct kvm_memory_slot *old,
380 struct kvm_memory_slot *new, enum kvm_mr_change change)
381 {
382 gpa_t gpa_start;
383 hva_t hva_start;
384 size_t size, gpa_offset, hva_offset;
385
386 /*
387 * The generic code allocates a fresh, zeroed memslot for every change,
388 * so the arch flags computed below must be carried over when only the
389 * userspace flags change, e.g. when dirty logging is toggled.
390 */
391 if (change == KVM_MR_FLAGS_ONLY) {
392 new->arch = old->arch;
393 return 0;
394 }
395
396 if ((change != KVM_MR_MOVE) && (change != KVM_MR_CREATE))
397 return 0;
398 /*
399 * Prevent userspace from creating a memory region outside of the
400 * VM GPA address space
401 */
402 if ((new->base_gfn + new->npages) > (kvm->arch.gpa_size >> PAGE_SHIFT))
403 return -ENOMEM;
404
405 new->arch.flags = 0;
406 size = new->npages * PAGE_SIZE;
407 gpa_start = new->base_gfn << PAGE_SHIFT;
408 hva_start = new->userspace_addr;
409 if (IS_ALIGNED(size, PMD_SIZE) && IS_ALIGNED(gpa_start, PMD_SIZE)
410 && IS_ALIGNED(hva_start, PMD_SIZE))
411 new->arch.flags |= KVM_MEM_HUGEPAGE_CAPABLE;
412 else {
413 /*
414 * Pages belonging to memslots that don't have the same
415 * alignment within a PMD for userspace and GPA cannot be
416 * mapped with PMD entries, because we'll end up mapping
417 * the wrong pages.
418 *
419 * Consider a layout like the following:
420 *
421 * memslot->userspace_addr:
422 * +-----+--------------------+--------------------+---+
423 * |abcde|fgh Stage-1 block | Stage-1 block tv|xyz|
424 * +-----+--------------------+--------------------+---+
425 *
426 * memslot->base_gfn << PAGE_SIZE:
427 * +---+--------------------+--------------------+-----+
428 * |abc|def Stage-2 block | Stage-2 block |tvxyz|
429 * +---+--------------------+--------------------+-----+
430 *
431 * If we create those stage-2 blocks, we'll end up with this
432 * incorrect mapping:
433 * d -> f
434 * e -> g
435 * f -> h
436 */
437 gpa_offset = gpa_start & (PMD_SIZE - 1);
438 hva_offset = hva_start & (PMD_SIZE - 1);
439 if (gpa_offset != hva_offset) {
440 new->arch.flags |= KVM_MEM_HUGEPAGE_INCAPABLE;
441 } else {
442 if (gpa_offset == 0)
443 gpa_offset = PMD_SIZE;
444 if ((size + gpa_offset) < (PMD_SIZE * 2))
445 new->arch.flags |= KVM_MEM_HUGEPAGE_INCAPABLE;
446 }
447 }
448
449 return 0;
450 }
451
kvm_arch_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)452 void kvm_arch_commit_memory_region(struct kvm *kvm,
453 struct kvm_memory_slot *old,
454 const struct kvm_memory_slot *new,
455 enum kvm_mr_change change)
456 {
457 int needs_flush;
458 u32 old_flags = old ? old->flags : 0;
459 u32 new_flags = new ? new->flags : 0;
460 bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
461
462 /* Only track memslot flags changed */
463 if (change != KVM_MR_FLAGS_ONLY)
464 return;
465
466 /* Discard dirty page tracking on readonly memslot */
467 if ((old_flags & new_flags) & KVM_MEM_READONLY)
468 return;
469
470 /*
471 * If dirty page logging is enabled, write protect all pages in the slot
472 * ready for dirty logging.
473 *
474 * There is no need to do this in any of the following cases:
475 * CREATE: No dirty mappings will already exist.
476 * MOVE/DELETE: The old mappings will already have been cleaned up by
477 * kvm_arch_flush_shadow_memslot()
478 */
479 if (!(old_flags & KVM_MEM_LOG_DIRTY_PAGES) && log_dirty_pages) {
480 /*
481 * Initially-all-set does not require write protecting any page
482 * because they're all assumed to be dirty.
483 */
484 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
485 return;
486
487 spin_lock(&kvm->mmu_lock);
488 /* Write protect GPA page table entries */
489 needs_flush = kvm_mkclean_gpa_pt(kvm, new->base_gfn,
490 new->base_gfn + new->npages);
491 spin_unlock(&kvm->mmu_lock);
492 if (needs_flush)
493 kvm_flush_remote_tlbs(kvm);
494 }
495 }
496
kvm_arch_flush_shadow_all(struct kvm * kvm)497 void kvm_arch_flush_shadow_all(struct kvm *kvm)
498 {
499 kvm_flush_range(kvm, 0, kvm->arch.gpa_size >> PAGE_SHIFT, 0);
500 }
501
kvm_arch_flush_shadow_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)502 void kvm_arch_flush_shadow_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
503 {
504 /*
505 * The slot has been made invalid (ready for moving or deletion), so we
506 * need to ensure that it can no longer be accessed by any guest vCPUs.
507 */
508 kvm_flush_range(kvm, slot->base_gfn, slot->base_gfn + slot->npages, 1);
509 }
510
kvm_unmap_gfn_range(struct kvm * kvm,struct kvm_gfn_range * range)511 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
512 {
513 kvm_ptw_ctx ctx;
514
515 ctx.flag = 0;
516 ctx.ops = kvm_flush_pte;
517 kvm_ptw_prepare(kvm, &ctx);
518 INIT_LIST_HEAD(&ctx.list);
519
520 return kvm_ptw_top(kvm->arch.pgd, range->start << PAGE_SHIFT,
521 range->end << PAGE_SHIFT, &ctx);
522 }
523
kvm_age_gfn(struct kvm * kvm,struct kvm_gfn_range * range)524 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
525 {
526 kvm_ptw_ctx ctx;
527
528 ctx.flag = 0;
529 ctx.ops = kvm_mkold_pte;
530 kvm_ptw_prepare(kvm, &ctx);
531
532 return kvm_ptw_top(kvm->arch.pgd, range->start << PAGE_SHIFT,
533 range->end << PAGE_SHIFT, &ctx);
534 }
535
kvm_test_age_gfn(struct kvm * kvm,struct kvm_gfn_range * range)536 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
537 {
538 gpa_t gpa = range->start << PAGE_SHIFT;
539 kvm_pte_t *ptep = kvm_populate_gpa(kvm, NULL, gpa, 0);
540
541 if (ptep && kvm_pte_present(NULL, ptep) && kvm_pte_young(*ptep))
542 return true;
543
544 return false;
545 }
546
547 /*
548 * kvm_map_page_fast() - Fast path GPA fault handler.
549 * @vcpu: vCPU pointer.
550 * @gpa: Guest physical address of fault.
551 * @write: Whether the fault was due to a write.
552 *
553 * Perform fast path GPA fault handling, doing all that can be done without
554 * calling into KVM. This handles marking old pages young (for idle page
555 * tracking), and dirtying of clean pages (for dirty page logging).
556 *
557 * Returns: 0 on success, in which case we can update derived mappings and
558 * resume guest execution.
559 * -EFAULT on failure due to absent GPA mapping or write to
560 * read-only page, in which case KVM must be consulted.
561 */
kvm_map_page_fast(struct kvm_vcpu * vcpu,unsigned long gpa,bool write)562 static int kvm_map_page_fast(struct kvm_vcpu *vcpu, unsigned long gpa, bool write)
563 {
564 int ret = 0;
565 kvm_pte_t *ptep, changed, new;
566 gfn_t gfn = gpa >> PAGE_SHIFT;
567 struct kvm *kvm = vcpu->kvm;
568 struct kvm_memory_slot *slot;
569
570 spin_lock(&kvm->mmu_lock);
571
572 /* Fast path - just check GPA page table for an existing entry */
573 ptep = kvm_populate_gpa(kvm, NULL, gpa, 0);
574 if (!ptep || !kvm_pte_present(NULL, ptep)) {
575 ret = -EFAULT;
576 goto out;
577 }
578
579 /* Track access to pages marked old */
580 new = kvm_pte_mkyoung(*ptep);
581 if (write && !kvm_pte_dirty(new)) {
582 if (!kvm_pte_writeable(new)) {
583 ret = -EFAULT;
584 goto out;
585 }
586
587 if (kvm_pte_huge(new)) {
588 /*
589 * Do not set write permission when dirty logging is
590 * enabled for HugePages
591 */
592 slot = gfn_to_memslot(kvm, gfn);
593 if (kvm_slot_dirty_track_enabled(slot)) {
594 ret = -EFAULT;
595 goto out;
596 }
597 }
598
599 /* Track dirtying of writeable pages */
600 new = kvm_pte_mkdirty(new);
601 }
602
603 changed = new ^ (*ptep);
604 if (changed)
605 kvm_set_pte(ptep, new);
606
607 spin_unlock(&kvm->mmu_lock);
608
609 if (kvm_pte_dirty(changed))
610 mark_page_dirty(kvm, gfn);
611
612 return ret;
613 out:
614 spin_unlock(&kvm->mmu_lock);
615 return ret;
616 }
617
fault_supports_huge_mapping(struct kvm_memory_slot * memslot,unsigned long hva,bool write)618 static bool fault_supports_huge_mapping(struct kvm_memory_slot *memslot,
619 unsigned long hva, bool write)
620 {
621 hva_t start, end;
622
623 /* Disable dirty logging on HugePages */
624 if (kvm_slot_dirty_track_enabled(memslot) && write)
625 return false;
626
627 if (kvm_hugepage_capable(memslot))
628 return true;
629
630 if (kvm_hugepage_incapable(memslot))
631 return false;
632
633 start = memslot->userspace_addr;
634 end = start + memslot->npages * PAGE_SIZE;
635
636 /*
637 * Next, let's make sure we're not trying to map anything not covered
638 * by the memslot. This means we have to prohibit block size mappings
639 * for the beginning and end of a non-block aligned and non-block sized
640 * memory slot (illustrated by the head and tail parts of the
641 * userspace view above containing pages 'abcde' and 'xyz',
642 * respectively).
643 *
644 * Note that it doesn't matter if we do the check using the
645 * userspace_addr or the base_gfn, as both are equally aligned (per
646 * the check above) and equally sized.
647 */
648 return (hva >= ALIGN(start, PMD_SIZE)) && (hva < ALIGN_DOWN(end, PMD_SIZE));
649 }
650
651 /*
652 * Lookup the mapping level for @gfn in the current mm.
653 *
654 * WARNING! Use of host_pfn_mapping_level() requires the caller and the end
655 * consumer to be tied into KVM's handlers for MMU notifier events!
656 *
657 * There are several ways to safely use this helper:
658 *
659 * - Check mmu_invalidate_retry_gfn() after grabbing the mapping level, before
660 * consuming it. In this case, mmu_lock doesn't need to be held during the
661 * lookup, but it does need to be held while checking the MMU notifier.
662 *
663 * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
664 * event for the hva. This can be done by explicit checking the MMU notifier
665 * or by ensuring that KVM already has a valid mapping that covers the hva.
666 *
667 * - Do not use the result to install new mappings, e.g. use the host mapping
668 * level only to decide whether or not to zap an entry. In this case, it's
669 * not required to hold mmu_lock (though it's highly likely the caller will
670 * want to hold mmu_lock anyways, e.g. to modify SPTEs).
671 *
672 * Note! The lookup can still race with modifications to host page tables, but
673 * the above "rules" ensure KVM will not _consume_ the result of the walk if a
674 * race with the primary MMU occurs.
675 */
host_pfn_mapping_level(struct kvm * kvm,gfn_t gfn,const struct kvm_memory_slot * slot)676 static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
677 const struct kvm_memory_slot *slot)
678 {
679 int level = 0;
680 unsigned long hva;
681 unsigned long flags;
682 pgd_t pgd;
683 p4d_t p4d;
684 pud_t pud;
685 pmd_t pmd;
686
687 /*
688 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
689 * is not solely for performance, it's also necessary to avoid the
690 * "writable" check in __gfn_to_hva_many(), which will always fail on
691 * read-only memslots due to gfn_to_hva() assuming writes. Earlier
692 * page fault steps have already verified the guest isn't writing a
693 * read-only memslot.
694 */
695 hva = __gfn_to_hva_memslot(slot, gfn);
696
697 /*
698 * Disable IRQs to prevent concurrent tear down of host page tables,
699 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
700 * the original page table.
701 */
702 local_irq_save(flags);
703
704 /*
705 * Read each entry once. As above, a non-leaf entry can be promoted to
706 * a huge page _during_ this walk. Re-reading the entry could send the
707 * walk into the weeks, e.g. p*d_leaf() returns false (sees the old
708 * value) and then p*d_offset() walks into the target huge page instead
709 * of the old page table (sees the new value).
710 */
711 pgd = pgdp_get(pgd_offset(kvm->mm, hva));
712 if (pgd_none(pgd))
713 goto out;
714
715 p4d = p4dp_get(p4d_offset(&pgd, hva));
716 if (p4d_none(p4d) || !p4d_present(p4d))
717 goto out;
718
719 pud = pudp_get(pud_offset(&p4d, hva));
720 if (pud_none(pud) || !pud_present(pud))
721 goto out;
722
723 pmd = pmdp_get(pmd_offset(&pud, hva));
724 if (pmd_none(pmd) || !pmd_present(pmd))
725 goto out;
726
727 if (kvm_pte_huge(pmd_val(pmd)))
728 level = 1;
729
730 out:
731 local_irq_restore(flags);
732 return level;
733 }
734
735 /*
736 * Split huge page
737 */
kvm_split_huge(struct kvm_vcpu * vcpu,kvm_pte_t * ptep,gfn_t gfn)738 static kvm_pte_t *kvm_split_huge(struct kvm_vcpu *vcpu, kvm_pte_t *ptep, gfn_t gfn)
739 {
740 int i;
741 kvm_pte_t val, *child;
742 struct kvm *kvm = vcpu->kvm;
743 struct kvm_mmu_memory_cache *memcache;
744
745 memcache = &vcpu->arch.mmu_page_cache;
746 child = kvm_mmu_memory_cache_alloc(memcache);
747 val = kvm_pte_mksmall(*ptep);
748 for (i = 0; i < PTRS_PER_PTE; i++) {
749 kvm_set_pte(child + i, val);
750 val += PAGE_SIZE;
751 }
752
753 smp_wmb(); /* Make pte visible before pmd */
754 /* The later kvm_flush_tlb_gpa() will flush hugepage tlb */
755 kvm_set_pte(ptep, __pa(child));
756
757 kvm->stat.hugepages--;
758 kvm->stat.pages += PTRS_PER_PTE;
759
760 return child + (gfn & (PTRS_PER_PTE - 1));
761 }
762
763 /*
764 * kvm_map_page() - Map a guest physical page.
765 * @vcpu: vCPU pointer.
766 * @gpa: Guest physical address of fault.
767 * @write: Whether the fault was due to a write.
768 *
769 * Handle GPA faults by creating a new GPA mapping (or updating an existing
770 * one).
771 *
772 * This takes care of marking pages young or dirty (idle/dirty page tracking),
773 * asking KVM for the corresponding PFN, and creating a mapping in the GPA page
774 * tables. Derived mappings (GVA page tables and TLBs) must be handled by the
775 * caller.
776 *
777 * Returns: 0 on success
778 * -EFAULT if there is no memory region at @gpa or a write was
779 * attempted to a read-only memory region. This is usually handled
780 * as an MMIO access.
781 */
kvm_map_page(struct kvm_vcpu * vcpu,unsigned long gpa,bool write)782 static int kvm_map_page(struct kvm_vcpu *vcpu, unsigned long gpa, bool write)
783 {
784 bool writeable;
785 int srcu_idx, err, retry_no = 0, level;
786 unsigned long hva, mmu_seq, prot_bits;
787 kvm_pfn_t pfn;
788 kvm_pte_t *ptep, new_pte;
789 gfn_t gfn = gpa >> PAGE_SHIFT;
790 struct kvm *kvm = vcpu->kvm;
791 struct kvm_memory_slot *memslot;
792 struct kvm_mmu_memory_cache *memcache = &vcpu->arch.mmu_page_cache;
793 struct page *page;
794
795 /* Try the fast path to handle old / clean pages */
796 srcu_idx = srcu_read_lock(&kvm->srcu);
797 err = kvm_map_page_fast(vcpu, gpa, write);
798 if (!err)
799 goto out;
800
801 memslot = gfn_to_memslot(kvm, gfn);
802 hva = gfn_to_hva_memslot_prot(memslot, gfn, &writeable);
803 if (kvm_is_error_hva(hva) || (write && !writeable)) {
804 err = -EFAULT;
805 goto out;
806 }
807
808 /* We need a minimum of cached pages ready for page table creation */
809 err = kvm_mmu_topup_memory_cache(memcache, KVM_MMU_CACHE_MIN_PAGES);
810 if (err)
811 goto out;
812
813 retry:
814 /*
815 * Used to check for invalidations in progress, of the pfn that is
816 * returned by pfn_to_pfn_prot below.
817 */
818 mmu_seq = kvm->mmu_invalidate_seq;
819 /*
820 * Ensure the read of mmu_invalidate_seq isn't reordered with PTE reads in
821 * kvm_faultin_pfn() (which calls get_user_pages()), so that we don't
822 * risk the page we get a reference to getting unmapped before we have a
823 * chance to grab the mmu_lock without mmu_invalidate_retry() noticing.
824 *
825 * This smp_rmb() pairs with the effective smp_wmb() of the combination
826 * of the pte_unmap_unlock() after the PTE is zapped, and the
827 * spin_lock() in kvm_mmu_invalidate_invalidate_<page|range_end>() before
828 * mmu_invalidate_seq is incremented.
829 */
830 smp_rmb();
831
832 /* Slow path - ask KVM core whether we can access this GPA */
833 pfn = kvm_faultin_pfn(vcpu, gfn, write, &writeable, &page);
834 if (is_error_noslot_pfn(pfn)) {
835 err = -EFAULT;
836 goto out;
837 }
838
839 /* Check if an invalidation has taken place since we got pfn */
840 spin_lock(&kvm->mmu_lock);
841 if (mmu_invalidate_retry_gfn(kvm, mmu_seq, gfn)) {
842 /*
843 * This can happen when mappings are changed asynchronously, but
844 * also synchronously if a COW is triggered by
845 * kvm_faultin_pfn().
846 */
847 spin_unlock(&kvm->mmu_lock);
848 kvm_release_page_unused(page);
849 if (retry_no > 100) {
850 retry_no = 0;
851 schedule();
852 }
853 retry_no++;
854 goto retry;
855 }
856
857 /*
858 * For emulated devices such virtio device, actual cache attribute is
859 * determined by physical machine.
860 * For pass through physical device, it should be uncachable
861 */
862 prot_bits = _PAGE_PRESENT | __READABLE;
863 if (pfn_valid(pfn))
864 prot_bits |= _CACHE_CC;
865 else
866 prot_bits |= _CACHE_SUC;
867
868 if (writeable) {
869 prot_bits = kvm_pte_mkwriteable(prot_bits);
870 if (write || !kvm_slot_dirty_track_enabled(memslot))
871 prot_bits = kvm_pte_mkdirty(prot_bits);
872 }
873
874 /* Disable dirty logging on HugePages */
875 level = 0;
876 if (fault_supports_huge_mapping(memslot, hva, write)) {
877 /* Check page level about host mmu*/
878 level = host_pfn_mapping_level(kvm, gfn, memslot);
879 if (level == 1) {
880 /*
881 * Check page level about secondary mmu
882 * Disable hugepage if it is normal page on
883 * secondary mmu already
884 */
885 ptep = kvm_populate_gpa(kvm, NULL, gpa, 0);
886 if (ptep && !kvm_pte_huge(*ptep))
887 level = 0;
888 }
889
890 if (level == 1) {
891 gfn = gfn & ~(PTRS_PER_PTE - 1);
892 pfn = pfn & ~(PTRS_PER_PTE - 1);
893 }
894 }
895
896 /* Ensure page tables are allocated */
897 ptep = kvm_populate_gpa(kvm, memcache, gpa, level);
898 new_pte = kvm_pfn_pte(pfn, __pgprot(prot_bits));
899 if (level == 1) {
900 new_pte = kvm_pte_mkhuge(new_pte);
901 /*
902 * previous pmd entry is invalid_pte_table
903 * there is invalid tlb with small page
904 * need flush these invalid tlbs for current vcpu
905 */
906 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
907 ++kvm->stat.hugepages;
908 } else if (kvm_pte_huge(*ptep) && write)
909 ptep = kvm_split_huge(vcpu, ptep, gfn);
910 else
911 ++kvm->stat.pages;
912 kvm_set_pte(ptep, new_pte);
913
914 kvm_release_faultin_page(kvm, page, false, writeable);
915 spin_unlock(&kvm->mmu_lock);
916
917 if (kvm_pte_dirty(prot_bits))
918 mark_page_dirty_in_slot(kvm, memslot, gfn);
919
920 out:
921 srcu_read_unlock(&kvm->srcu, srcu_idx);
922 return err;
923 }
924
kvm_handle_mm_fault(struct kvm_vcpu * vcpu,unsigned long gpa,bool write,int ecode)925 int kvm_handle_mm_fault(struct kvm_vcpu *vcpu, unsigned long gpa, bool write, int ecode)
926 {
927 int ret;
928
929 ret = kvm_map_page(vcpu, gpa, write);
930 if (ret)
931 return ret;
932
933 /* Invalidate this entry in the TLB */
934 if (!cpu_has_ptw || (ecode == EXCCODE_TLBM)) {
935 /*
936 * With HW PTW, invalid TLB is not added when page fault. But
937 * for EXCCODE_TLBM exception, stale TLB may exist because of
938 * the last read access.
939 *
940 * With SW PTW, invalid TLB is added in TLB refill exception.
941 */
942 vcpu->arch.flush_gpa = gpa;
943 kvm_make_request(KVM_REQ_TLB_FLUSH_GPA, vcpu);
944 }
945
946 return 0;
947 }
948
kvm_arch_sync_dirty_log(struct kvm * kvm,struct kvm_memory_slot * memslot)949 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
950 {
951 }
952