]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blob - arch/x86/kvm/mmu/mmu.c
KVM: mmu: extract spte.h and spte.c
[mirror_ubuntu-jammy-kernel.git] / arch / x86 / kvm / mmu / mmu.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Kernel-based Virtual Machine driver for Linux
4 *
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
7 *
8 * MMU support
9 *
10 * Copyright (C) 2006 Qumranet, Inc.
11 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 *
13 * Authors:
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Avi Kivity <avi@qumranet.com>
16 */
17
18 #include "irq.h"
19 #include "ioapic.h"
20 #include "mmu.h"
21 #include "mmu_internal.h"
22 #include "x86.h"
23 #include "kvm_cache_regs.h"
24 #include "kvm_emulate.h"
25 #include "cpuid.h"
26 #include "spte.h"
27
28 #include <linux/kvm_host.h>
29 #include <linux/types.h>
30 #include <linux/string.h>
31 #include <linux/mm.h>
32 #include <linux/highmem.h>
33 #include <linux/moduleparam.h>
34 #include <linux/export.h>
35 #include <linux/swap.h>
36 #include <linux/hugetlb.h>
37 #include <linux/compiler.h>
38 #include <linux/srcu.h>
39 #include <linux/slab.h>
40 #include <linux/sched/signal.h>
41 #include <linux/uaccess.h>
42 #include <linux/hash.h>
43 #include <linux/kern_levels.h>
44 #include <linux/kthread.h>
45
46 #include <asm/page.h>
47 #include <asm/memtype.h>
48 #include <asm/cmpxchg.h>
49 #include <asm/io.h>
50 #include <asm/vmx.h>
51 #include <asm/kvm_page_track.h>
52 #include "trace.h"
53
54 extern bool itlb_multihit_kvm_mitigation;
55
56 static int __read_mostly nx_huge_pages = -1;
57 #ifdef CONFIG_PREEMPT_RT
58 /* Recovery can cause latency spikes, disable it for PREEMPT_RT. */
59 static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
60 #else
61 static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
62 #endif
63
64 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
65 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp);
66
67 static const struct kernel_param_ops nx_huge_pages_ops = {
68 .set = set_nx_huge_pages,
69 .get = param_get_bool,
70 };
71
72 static const struct kernel_param_ops nx_huge_pages_recovery_ratio_ops = {
73 .set = set_nx_huge_pages_recovery_ratio,
74 .get = param_get_uint,
75 };
76
77 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
78 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
79 module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_ratio_ops,
80 &nx_huge_pages_recovery_ratio, 0644);
81 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
82
83 static bool __read_mostly force_flush_and_sync_on_reuse;
84 module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
85
86 /*
87 * When setting this variable to true it enables Two-Dimensional-Paging
88 * where the hardware walks 2 page tables:
89 * 1. the guest-virtual to guest-physical
90 * 2. while doing 1. it walks guest-physical to host-physical
91 * If the hardware supports that we don't need to do shadow paging.
92 */
93 bool tdp_enabled = false;
94
95 static int max_huge_page_level __read_mostly;
96 static int max_tdp_level __read_mostly;
97
98 enum {
99 AUDIT_PRE_PAGE_FAULT,
100 AUDIT_POST_PAGE_FAULT,
101 AUDIT_PRE_PTE_WRITE,
102 AUDIT_POST_PTE_WRITE,
103 AUDIT_PRE_SYNC,
104 AUDIT_POST_SYNC
105 };
106
107 #ifdef MMU_DEBUG
108 bool dbg = 0;
109 module_param(dbg, bool, 0644);
110 #endif
111
112 #define PTE_PREFETCH_NUM 8
113
114 #define PT32_LEVEL_BITS 10
115
116 #define PT32_LEVEL_SHIFT(level) \
117 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
118
119 #define PT32_LVL_OFFSET_MASK(level) \
120 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
121 * PT32_LEVEL_BITS))) - 1))
122
123 #define PT32_INDEX(address, level)\
124 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
125
126
127 #define PT32_BASE_ADDR_MASK PAGE_MASK
128 #define PT32_DIR_BASE_ADDR_MASK \
129 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
130 #define PT32_LVL_ADDR_MASK(level) \
131 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
132 * PT32_LEVEL_BITS))) - 1))
133
134 #include <trace/events/kvm.h>
135
136 /* make pte_list_desc fit well in cache line */
137 #define PTE_LIST_EXT 3
138
139 /*
140 * Return values of handle_mmio_page_fault, mmu.page_fault, and fast_page_fault().
141 *
142 * RET_PF_RETRY: let CPU fault again on the address.
143 * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
144 * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
145 * RET_PF_FIXED: The faulting entry has been fixed.
146 * RET_PF_SPURIOUS: The faulting entry was already fixed, e.g. by another vCPU.
147 */
148 enum {
149 RET_PF_RETRY = 0,
150 RET_PF_EMULATE,
151 RET_PF_INVALID,
152 RET_PF_FIXED,
153 RET_PF_SPURIOUS,
154 };
155
156 struct pte_list_desc {
157 u64 *sptes[PTE_LIST_EXT];
158 struct pte_list_desc *more;
159 };
160
161 struct kvm_shadow_walk_iterator {
162 u64 addr;
163 hpa_t shadow_addr;
164 u64 *sptep;
165 int level;
166 unsigned index;
167 };
168
169 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
170 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
171 (_root), (_addr)); \
172 shadow_walk_okay(&(_walker)); \
173 shadow_walk_next(&(_walker)))
174
175 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
176 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
177 shadow_walk_okay(&(_walker)); \
178 shadow_walk_next(&(_walker)))
179
180 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
181 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
182 shadow_walk_okay(&(_walker)) && \
183 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
184 __shadow_walk_next(&(_walker), spte))
185
186 static struct kmem_cache *pte_list_desc_cache;
187 static struct kmem_cache *mmu_page_header_cache;
188 static struct percpu_counter kvm_total_used_mmu_pages;
189
190 static void mmu_spte_set(u64 *sptep, u64 spte);
191 static union kvm_mmu_page_role
192 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
193
194 #define CREATE_TRACE_POINTS
195 #include "mmutrace.h"
196
197
198 static inline bool kvm_available_flush_tlb_with_range(void)
199 {
200 return kvm_x86_ops.tlb_remote_flush_with_range;
201 }
202
203 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
204 struct kvm_tlb_range *range)
205 {
206 int ret = -ENOTSUPP;
207
208 if (range && kvm_x86_ops.tlb_remote_flush_with_range)
209 ret = kvm_x86_ops.tlb_remote_flush_with_range(kvm, range);
210
211 if (ret)
212 kvm_flush_remote_tlbs(kvm);
213 }
214
215 static void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
216 u64 start_gfn, u64 pages)
217 {
218 struct kvm_tlb_range range;
219
220 range.start_gfn = start_gfn;
221 range.pages = pages;
222
223 kvm_flush_remote_tlbs_with_range(kvm, &range);
224 }
225
226 bool is_nx_huge_page_enabled(void)
227 {
228 return READ_ONCE(nx_huge_pages);
229 }
230
231 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
232 unsigned int access)
233 {
234 u64 mask = make_mmio_spte(vcpu, gfn, access);
235 unsigned int gen = get_mmio_spte_generation(mask);
236
237 access = mask & ACC_ALL;
238
239 trace_mark_mmio_spte(sptep, gfn, access, gen);
240 mmu_spte_set(sptep, mask);
241 }
242
243 static gfn_t get_mmio_spte_gfn(u64 spte)
244 {
245 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
246
247 gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
248 & shadow_nonpresent_or_rsvd_mask;
249
250 return gpa >> PAGE_SHIFT;
251 }
252
253 static unsigned get_mmio_spte_access(u64 spte)
254 {
255 return spte & shadow_mmio_access_mask;
256 }
257
258 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
259 kvm_pfn_t pfn, unsigned int access)
260 {
261 if (unlikely(is_noslot_pfn(pfn))) {
262 mark_mmio_spte(vcpu, sptep, gfn, access);
263 return true;
264 }
265
266 return false;
267 }
268
269 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
270 {
271 u64 kvm_gen, spte_gen, gen;
272
273 gen = kvm_vcpu_memslots(vcpu)->generation;
274 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
275 return false;
276
277 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
278 spte_gen = get_mmio_spte_generation(spte);
279
280 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
281 return likely(kvm_gen == spte_gen);
282 }
283
284 static gpa_t translate_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
285 struct x86_exception *exception)
286 {
287 /* Check if guest physical address doesn't exceed guest maximum */
288 if (kvm_vcpu_is_illegal_gpa(vcpu, gpa)) {
289 exception->error_code |= PFERR_RSVD_MASK;
290 return UNMAPPED_GVA;
291 }
292
293 return gpa;
294 }
295
296 static int is_cpuid_PSE36(void)
297 {
298 return 1;
299 }
300
301 static int is_nx(struct kvm_vcpu *vcpu)
302 {
303 return vcpu->arch.efer & EFER_NX;
304 }
305
306 static gfn_t pse36_gfn_delta(u32 gpte)
307 {
308 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
309
310 return (gpte & PT32_DIR_PSE36_MASK) << shift;
311 }
312
313 #ifdef CONFIG_X86_64
314 static void __set_spte(u64 *sptep, u64 spte)
315 {
316 WRITE_ONCE(*sptep, spte);
317 }
318
319 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
320 {
321 WRITE_ONCE(*sptep, spte);
322 }
323
324 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
325 {
326 return xchg(sptep, spte);
327 }
328
329 static u64 __get_spte_lockless(u64 *sptep)
330 {
331 return READ_ONCE(*sptep);
332 }
333 #else
334 union split_spte {
335 struct {
336 u32 spte_low;
337 u32 spte_high;
338 };
339 u64 spte;
340 };
341
342 static void count_spte_clear(u64 *sptep, u64 spte)
343 {
344 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
345
346 if (is_shadow_present_pte(spte))
347 return;
348
349 /* Ensure the spte is completely set before we increase the count */
350 smp_wmb();
351 sp->clear_spte_count++;
352 }
353
354 static void __set_spte(u64 *sptep, u64 spte)
355 {
356 union split_spte *ssptep, sspte;
357
358 ssptep = (union split_spte *)sptep;
359 sspte = (union split_spte)spte;
360
361 ssptep->spte_high = sspte.spte_high;
362
363 /*
364 * If we map the spte from nonpresent to present, We should store
365 * the high bits firstly, then set present bit, so cpu can not
366 * fetch this spte while we are setting the spte.
367 */
368 smp_wmb();
369
370 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
371 }
372
373 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
374 {
375 union split_spte *ssptep, sspte;
376
377 ssptep = (union split_spte *)sptep;
378 sspte = (union split_spte)spte;
379
380 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
381
382 /*
383 * If we map the spte from present to nonpresent, we should clear
384 * present bit firstly to avoid vcpu fetch the old high bits.
385 */
386 smp_wmb();
387
388 ssptep->spte_high = sspte.spte_high;
389 count_spte_clear(sptep, spte);
390 }
391
392 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
393 {
394 union split_spte *ssptep, sspte, orig;
395
396 ssptep = (union split_spte *)sptep;
397 sspte = (union split_spte)spte;
398
399 /* xchg acts as a barrier before the setting of the high bits */
400 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
401 orig.spte_high = ssptep->spte_high;
402 ssptep->spte_high = sspte.spte_high;
403 count_spte_clear(sptep, spte);
404
405 return orig.spte;
406 }
407
408 /*
409 * The idea using the light way get the spte on x86_32 guest is from
410 * gup_get_pte (mm/gup.c).
411 *
412 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
413 * coalesces them and we are running out of the MMU lock. Therefore
414 * we need to protect against in-progress updates of the spte.
415 *
416 * Reading the spte while an update is in progress may get the old value
417 * for the high part of the spte. The race is fine for a present->non-present
418 * change (because the high part of the spte is ignored for non-present spte),
419 * but for a present->present change we must reread the spte.
420 *
421 * All such changes are done in two steps (present->non-present and
422 * non-present->present), hence it is enough to count the number of
423 * present->non-present updates: if it changed while reading the spte,
424 * we might have hit the race. This is done using clear_spte_count.
425 */
426 static u64 __get_spte_lockless(u64 *sptep)
427 {
428 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
429 union split_spte spte, *orig = (union split_spte *)sptep;
430 int count;
431
432 retry:
433 count = sp->clear_spte_count;
434 smp_rmb();
435
436 spte.spte_low = orig->spte_low;
437 smp_rmb();
438
439 spte.spte_high = orig->spte_high;
440 smp_rmb();
441
442 if (unlikely(spte.spte_low != orig->spte_low ||
443 count != sp->clear_spte_count))
444 goto retry;
445
446 return spte.spte;
447 }
448 #endif
449
450 static bool spte_has_volatile_bits(u64 spte)
451 {
452 if (!is_shadow_present_pte(spte))
453 return false;
454
455 /*
456 * Always atomically update spte if it can be updated
457 * out of mmu-lock, it can ensure dirty bit is not lost,
458 * also, it can help us to get a stable is_writable_pte()
459 * to ensure tlb flush is not missed.
460 */
461 if (spte_can_locklessly_be_made_writable(spte) ||
462 is_access_track_spte(spte))
463 return true;
464
465 if (spte_ad_enabled(spte)) {
466 if ((spte & shadow_accessed_mask) == 0 ||
467 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
468 return true;
469 }
470
471 return false;
472 }
473
474 /* Rules for using mmu_spte_set:
475 * Set the sptep from nonpresent to present.
476 * Note: the sptep being assigned *must* be either not present
477 * or in a state where the hardware will not attempt to update
478 * the spte.
479 */
480 static void mmu_spte_set(u64 *sptep, u64 new_spte)
481 {
482 WARN_ON(is_shadow_present_pte(*sptep));
483 __set_spte(sptep, new_spte);
484 }
485
486 /*
487 * Update the SPTE (excluding the PFN), but do not track changes in its
488 * accessed/dirty status.
489 */
490 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
491 {
492 u64 old_spte = *sptep;
493
494 WARN_ON(!is_shadow_present_pte(new_spte));
495
496 if (!is_shadow_present_pte(old_spte)) {
497 mmu_spte_set(sptep, new_spte);
498 return old_spte;
499 }
500
501 if (!spte_has_volatile_bits(old_spte))
502 __update_clear_spte_fast(sptep, new_spte);
503 else
504 old_spte = __update_clear_spte_slow(sptep, new_spte);
505
506 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
507
508 return old_spte;
509 }
510
511 /* Rules for using mmu_spte_update:
512 * Update the state bits, it means the mapped pfn is not changed.
513 *
514 * Whenever we overwrite a writable spte with a read-only one we
515 * should flush remote TLBs. Otherwise rmap_write_protect
516 * will find a read-only spte, even though the writable spte
517 * might be cached on a CPU's TLB, the return value indicates this
518 * case.
519 *
520 * Returns true if the TLB needs to be flushed
521 */
522 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
523 {
524 bool flush = false;
525 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
526
527 if (!is_shadow_present_pte(old_spte))
528 return false;
529
530 /*
531 * For the spte updated out of mmu-lock is safe, since
532 * we always atomically update it, see the comments in
533 * spte_has_volatile_bits().
534 */
535 if (spte_can_locklessly_be_made_writable(old_spte) &&
536 !is_writable_pte(new_spte))
537 flush = true;
538
539 /*
540 * Flush TLB when accessed/dirty states are changed in the page tables,
541 * to guarantee consistency between TLB and page tables.
542 */
543
544 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
545 flush = true;
546 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
547 }
548
549 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
550 flush = true;
551 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
552 }
553
554 return flush;
555 }
556
557 /*
558 * Rules for using mmu_spte_clear_track_bits:
559 * It sets the sptep from present to nonpresent, and track the
560 * state bits, it is used to clear the last level sptep.
561 * Returns non-zero if the PTE was previously valid.
562 */
563 static int mmu_spte_clear_track_bits(u64 *sptep)
564 {
565 kvm_pfn_t pfn;
566 u64 old_spte = *sptep;
567
568 if (!spte_has_volatile_bits(old_spte))
569 __update_clear_spte_fast(sptep, 0ull);
570 else
571 old_spte = __update_clear_spte_slow(sptep, 0ull);
572
573 if (!is_shadow_present_pte(old_spte))
574 return 0;
575
576 pfn = spte_to_pfn(old_spte);
577
578 /*
579 * KVM does not hold the refcount of the page used by
580 * kvm mmu, before reclaiming the page, we should
581 * unmap it from mmu first.
582 */
583 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
584
585 if (is_accessed_spte(old_spte))
586 kvm_set_pfn_accessed(pfn);
587
588 if (is_dirty_spte(old_spte))
589 kvm_set_pfn_dirty(pfn);
590
591 return 1;
592 }
593
594 /*
595 * Rules for using mmu_spte_clear_no_track:
596 * Directly clear spte without caring the state bits of sptep,
597 * it is used to set the upper level spte.
598 */
599 static void mmu_spte_clear_no_track(u64 *sptep)
600 {
601 __update_clear_spte_fast(sptep, 0ull);
602 }
603
604 static u64 mmu_spte_get_lockless(u64 *sptep)
605 {
606 return __get_spte_lockless(sptep);
607 }
608
609 /* Restore an acc-track PTE back to a regular PTE */
610 static u64 restore_acc_track_spte(u64 spte)
611 {
612 u64 new_spte = spte;
613 u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
614 & shadow_acc_track_saved_bits_mask;
615
616 WARN_ON_ONCE(spte_ad_enabled(spte));
617 WARN_ON_ONCE(!is_access_track_spte(spte));
618
619 new_spte &= ~shadow_acc_track_mask;
620 new_spte &= ~(shadow_acc_track_saved_bits_mask <<
621 shadow_acc_track_saved_bits_shift);
622 new_spte |= saved_bits;
623
624 return new_spte;
625 }
626
627 /* Returns the Accessed status of the PTE and resets it at the same time. */
628 static bool mmu_spte_age(u64 *sptep)
629 {
630 u64 spte = mmu_spte_get_lockless(sptep);
631
632 if (!is_accessed_spte(spte))
633 return false;
634
635 if (spte_ad_enabled(spte)) {
636 clear_bit((ffs(shadow_accessed_mask) - 1),
637 (unsigned long *)sptep);
638 } else {
639 /*
640 * Capture the dirty status of the page, so that it doesn't get
641 * lost when the SPTE is marked for access tracking.
642 */
643 if (is_writable_pte(spte))
644 kvm_set_pfn_dirty(spte_to_pfn(spte));
645
646 spte = mark_spte_for_access_track(spte);
647 mmu_spte_update_no_track(sptep, spte);
648 }
649
650 return true;
651 }
652
653 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
654 {
655 /*
656 * Prevent page table teardown by making any free-er wait during
657 * kvm_flush_remote_tlbs() IPI to all active vcpus.
658 */
659 local_irq_disable();
660
661 /*
662 * Make sure a following spte read is not reordered ahead of the write
663 * to vcpu->mode.
664 */
665 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
666 }
667
668 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
669 {
670 /*
671 * Make sure the write to vcpu->mode is not reordered in front of
672 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
673 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
674 */
675 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
676 local_irq_enable();
677 }
678
679 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
680 {
681 int r;
682
683 /* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
684 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
685 1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
686 if (r)
687 return r;
688 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
689 PT64_ROOT_MAX_LEVEL);
690 if (r)
691 return r;
692 if (maybe_indirect) {
693 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_gfn_array_cache,
694 PT64_ROOT_MAX_LEVEL);
695 if (r)
696 return r;
697 }
698 return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
699 PT64_ROOT_MAX_LEVEL);
700 }
701
702 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
703 {
704 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
705 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
706 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_gfn_array_cache);
707 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
708 }
709
710 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
711 {
712 return kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
713 }
714
715 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
716 {
717 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
718 }
719
720 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
721 {
722 if (!sp->role.direct)
723 return sp->gfns[index];
724
725 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
726 }
727
728 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
729 {
730 if (!sp->role.direct) {
731 sp->gfns[index] = gfn;
732 return;
733 }
734
735 if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
736 pr_err_ratelimited("gfn mismatch under direct page %llx "
737 "(expected %llx, got %llx)\n",
738 sp->gfn,
739 kvm_mmu_page_get_gfn(sp, index), gfn);
740 }
741
742 /*
743 * Return the pointer to the large page information for a given gfn,
744 * handling slots that are not large page aligned.
745 */
746 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
747 struct kvm_memory_slot *slot,
748 int level)
749 {
750 unsigned long idx;
751
752 idx = gfn_to_index(gfn, slot->base_gfn, level);
753 return &slot->arch.lpage_info[level - 2][idx];
754 }
755
756 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
757 gfn_t gfn, int count)
758 {
759 struct kvm_lpage_info *linfo;
760 int i;
761
762 for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
763 linfo = lpage_info_slot(gfn, slot, i);
764 linfo->disallow_lpage += count;
765 WARN_ON(linfo->disallow_lpage < 0);
766 }
767 }
768
769 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
770 {
771 update_gfn_disallow_lpage_count(slot, gfn, 1);
772 }
773
774 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
775 {
776 update_gfn_disallow_lpage_count(slot, gfn, -1);
777 }
778
779 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
780 {
781 struct kvm_memslots *slots;
782 struct kvm_memory_slot *slot;
783 gfn_t gfn;
784
785 kvm->arch.indirect_shadow_pages++;
786 gfn = sp->gfn;
787 slots = kvm_memslots_for_spte_role(kvm, sp->role);
788 slot = __gfn_to_memslot(slots, gfn);
789
790 /* the non-leaf shadow pages are keeping readonly. */
791 if (sp->role.level > PG_LEVEL_4K)
792 return kvm_slot_page_track_add_page(kvm, slot, gfn,
793 KVM_PAGE_TRACK_WRITE);
794
795 kvm_mmu_gfn_disallow_lpage(slot, gfn);
796 }
797
798 static void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
799 {
800 if (sp->lpage_disallowed)
801 return;
802
803 ++kvm->stat.nx_lpage_splits;
804 list_add_tail(&sp->lpage_disallowed_link,
805 &kvm->arch.lpage_disallowed_mmu_pages);
806 sp->lpage_disallowed = true;
807 }
808
809 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
810 {
811 struct kvm_memslots *slots;
812 struct kvm_memory_slot *slot;
813 gfn_t gfn;
814
815 kvm->arch.indirect_shadow_pages--;
816 gfn = sp->gfn;
817 slots = kvm_memslots_for_spte_role(kvm, sp->role);
818 slot = __gfn_to_memslot(slots, gfn);
819 if (sp->role.level > PG_LEVEL_4K)
820 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
821 KVM_PAGE_TRACK_WRITE);
822
823 kvm_mmu_gfn_allow_lpage(slot, gfn);
824 }
825
826 static void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
827 {
828 --kvm->stat.nx_lpage_splits;
829 sp->lpage_disallowed = false;
830 list_del(&sp->lpage_disallowed_link);
831 }
832
833 static struct kvm_memory_slot *
834 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
835 bool no_dirty_log)
836 {
837 struct kvm_memory_slot *slot;
838
839 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
840 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
841 return NULL;
842 if (no_dirty_log && slot->dirty_bitmap)
843 return NULL;
844
845 return slot;
846 }
847
848 /*
849 * About rmap_head encoding:
850 *
851 * If the bit zero of rmap_head->val is clear, then it points to the only spte
852 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
853 * pte_list_desc containing more mappings.
854 */
855
856 /*
857 * Returns the number of pointers in the rmap chain, not counting the new one.
858 */
859 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
860 struct kvm_rmap_head *rmap_head)
861 {
862 struct pte_list_desc *desc;
863 int i, count = 0;
864
865 if (!rmap_head->val) {
866 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
867 rmap_head->val = (unsigned long)spte;
868 } else if (!(rmap_head->val & 1)) {
869 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
870 desc = mmu_alloc_pte_list_desc(vcpu);
871 desc->sptes[0] = (u64 *)rmap_head->val;
872 desc->sptes[1] = spte;
873 rmap_head->val = (unsigned long)desc | 1;
874 ++count;
875 } else {
876 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
877 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
878 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
879 desc = desc->more;
880 count += PTE_LIST_EXT;
881 }
882 if (desc->sptes[PTE_LIST_EXT-1]) {
883 desc->more = mmu_alloc_pte_list_desc(vcpu);
884 desc = desc->more;
885 }
886 for (i = 0; desc->sptes[i]; ++i)
887 ++count;
888 desc->sptes[i] = spte;
889 }
890 return count;
891 }
892
893 static void
894 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
895 struct pte_list_desc *desc, int i,
896 struct pte_list_desc *prev_desc)
897 {
898 int j;
899
900 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
901 ;
902 desc->sptes[i] = desc->sptes[j];
903 desc->sptes[j] = NULL;
904 if (j != 0)
905 return;
906 if (!prev_desc && !desc->more)
907 rmap_head->val = 0;
908 else
909 if (prev_desc)
910 prev_desc->more = desc->more;
911 else
912 rmap_head->val = (unsigned long)desc->more | 1;
913 mmu_free_pte_list_desc(desc);
914 }
915
916 static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
917 {
918 struct pte_list_desc *desc;
919 struct pte_list_desc *prev_desc;
920 int i;
921
922 if (!rmap_head->val) {
923 pr_err("%s: %p 0->BUG\n", __func__, spte);
924 BUG();
925 } else if (!(rmap_head->val & 1)) {
926 rmap_printk("%s: %p 1->0\n", __func__, spte);
927 if ((u64 *)rmap_head->val != spte) {
928 pr_err("%s: %p 1->BUG\n", __func__, spte);
929 BUG();
930 }
931 rmap_head->val = 0;
932 } else {
933 rmap_printk("%s: %p many->many\n", __func__, spte);
934 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
935 prev_desc = NULL;
936 while (desc) {
937 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
938 if (desc->sptes[i] == spte) {
939 pte_list_desc_remove_entry(rmap_head,
940 desc, i, prev_desc);
941 return;
942 }
943 }
944 prev_desc = desc;
945 desc = desc->more;
946 }
947 pr_err("%s: %p many->many\n", __func__, spte);
948 BUG();
949 }
950 }
951
952 static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
953 {
954 mmu_spte_clear_track_bits(sptep);
955 __pte_list_remove(sptep, rmap_head);
956 }
957
958 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
959 struct kvm_memory_slot *slot)
960 {
961 unsigned long idx;
962
963 idx = gfn_to_index(gfn, slot->base_gfn, level);
964 return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
965 }
966
967 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
968 struct kvm_mmu_page *sp)
969 {
970 struct kvm_memslots *slots;
971 struct kvm_memory_slot *slot;
972
973 slots = kvm_memslots_for_spte_role(kvm, sp->role);
974 slot = __gfn_to_memslot(slots, gfn);
975 return __gfn_to_rmap(gfn, sp->role.level, slot);
976 }
977
978 static bool rmap_can_add(struct kvm_vcpu *vcpu)
979 {
980 struct kvm_mmu_memory_cache *mc;
981
982 mc = &vcpu->arch.mmu_pte_list_desc_cache;
983 return kvm_mmu_memory_cache_nr_free_objects(mc);
984 }
985
986 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
987 {
988 struct kvm_mmu_page *sp;
989 struct kvm_rmap_head *rmap_head;
990
991 sp = sptep_to_sp(spte);
992 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
993 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
994 return pte_list_add(vcpu, spte, rmap_head);
995 }
996
997 static void rmap_remove(struct kvm *kvm, u64 *spte)
998 {
999 struct kvm_mmu_page *sp;
1000 gfn_t gfn;
1001 struct kvm_rmap_head *rmap_head;
1002
1003 sp = sptep_to_sp(spte);
1004 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1005 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1006 __pte_list_remove(spte, rmap_head);
1007 }
1008
1009 /*
1010 * Used by the following functions to iterate through the sptes linked by a
1011 * rmap. All fields are private and not assumed to be used outside.
1012 */
1013 struct rmap_iterator {
1014 /* private fields */
1015 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1016 int pos; /* index of the sptep */
1017 };
1018
1019 /*
1020 * Iteration must be started by this function. This should also be used after
1021 * removing/dropping sptes from the rmap link because in such cases the
1022 * information in the iterator may not be valid.
1023 *
1024 * Returns sptep if found, NULL otherwise.
1025 */
1026 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1027 struct rmap_iterator *iter)
1028 {
1029 u64 *sptep;
1030
1031 if (!rmap_head->val)
1032 return NULL;
1033
1034 if (!(rmap_head->val & 1)) {
1035 iter->desc = NULL;
1036 sptep = (u64 *)rmap_head->val;
1037 goto out;
1038 }
1039
1040 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1041 iter->pos = 0;
1042 sptep = iter->desc->sptes[iter->pos];
1043 out:
1044 BUG_ON(!is_shadow_present_pte(*sptep));
1045 return sptep;
1046 }
1047
1048 /*
1049 * Must be used with a valid iterator: e.g. after rmap_get_first().
1050 *
1051 * Returns sptep if found, NULL otherwise.
1052 */
1053 static u64 *rmap_get_next(struct rmap_iterator *iter)
1054 {
1055 u64 *sptep;
1056
1057 if (iter->desc) {
1058 if (iter->pos < PTE_LIST_EXT - 1) {
1059 ++iter->pos;
1060 sptep = iter->desc->sptes[iter->pos];
1061 if (sptep)
1062 goto out;
1063 }
1064
1065 iter->desc = iter->desc->more;
1066
1067 if (iter->desc) {
1068 iter->pos = 0;
1069 /* desc->sptes[0] cannot be NULL */
1070 sptep = iter->desc->sptes[iter->pos];
1071 goto out;
1072 }
1073 }
1074
1075 return NULL;
1076 out:
1077 BUG_ON(!is_shadow_present_pte(*sptep));
1078 return sptep;
1079 }
1080
1081 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1082 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1083 _spte_; _spte_ = rmap_get_next(_iter_))
1084
1085 static void drop_spte(struct kvm *kvm, u64 *sptep)
1086 {
1087 if (mmu_spte_clear_track_bits(sptep))
1088 rmap_remove(kvm, sptep);
1089 }
1090
1091
1092 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1093 {
1094 if (is_large_pte(*sptep)) {
1095 WARN_ON(sptep_to_sp(sptep)->role.level == PG_LEVEL_4K);
1096 drop_spte(kvm, sptep);
1097 --kvm->stat.lpages;
1098 return true;
1099 }
1100
1101 return false;
1102 }
1103
1104 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1105 {
1106 if (__drop_large_spte(vcpu->kvm, sptep)) {
1107 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
1108
1109 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1110 KVM_PAGES_PER_HPAGE(sp->role.level));
1111 }
1112 }
1113
1114 /*
1115 * Write-protect on the specified @sptep, @pt_protect indicates whether
1116 * spte write-protection is caused by protecting shadow page table.
1117 *
1118 * Note: write protection is difference between dirty logging and spte
1119 * protection:
1120 * - for dirty logging, the spte can be set to writable at anytime if
1121 * its dirty bitmap is properly set.
1122 * - for spte protection, the spte can be writable only after unsync-ing
1123 * shadow page.
1124 *
1125 * Return true if tlb need be flushed.
1126 */
1127 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1128 {
1129 u64 spte = *sptep;
1130
1131 if (!is_writable_pte(spte) &&
1132 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1133 return false;
1134
1135 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1136
1137 if (pt_protect)
1138 spte &= ~SPTE_MMU_WRITEABLE;
1139 spte = spte & ~PT_WRITABLE_MASK;
1140
1141 return mmu_spte_update(sptep, spte);
1142 }
1143
1144 static bool __rmap_write_protect(struct kvm *kvm,
1145 struct kvm_rmap_head *rmap_head,
1146 bool pt_protect)
1147 {
1148 u64 *sptep;
1149 struct rmap_iterator iter;
1150 bool flush = false;
1151
1152 for_each_rmap_spte(rmap_head, &iter, sptep)
1153 flush |= spte_write_protect(sptep, pt_protect);
1154
1155 return flush;
1156 }
1157
1158 static bool spte_clear_dirty(u64 *sptep)
1159 {
1160 u64 spte = *sptep;
1161
1162 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1163
1164 MMU_WARN_ON(!spte_ad_enabled(spte));
1165 spte &= ~shadow_dirty_mask;
1166 return mmu_spte_update(sptep, spte);
1167 }
1168
1169 static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1170 {
1171 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1172 (unsigned long *)sptep);
1173 if (was_writable && !spte_ad_enabled(*sptep))
1174 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1175
1176 return was_writable;
1177 }
1178
1179 /*
1180 * Gets the GFN ready for another round of dirty logging by clearing the
1181 * - D bit on ad-enabled SPTEs, and
1182 * - W bit on ad-disabled SPTEs.
1183 * Returns true iff any D or W bits were cleared.
1184 */
1185 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1186 {
1187 u64 *sptep;
1188 struct rmap_iterator iter;
1189 bool flush = false;
1190
1191 for_each_rmap_spte(rmap_head, &iter, sptep)
1192 if (spte_ad_need_write_protect(*sptep))
1193 flush |= spte_wrprot_for_clear_dirty(sptep);
1194 else
1195 flush |= spte_clear_dirty(sptep);
1196
1197 return flush;
1198 }
1199
1200 static bool spte_set_dirty(u64 *sptep)
1201 {
1202 u64 spte = *sptep;
1203
1204 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1205
1206 /*
1207 * Similar to the !kvm_x86_ops.slot_disable_log_dirty case,
1208 * do not bother adding back write access to pages marked
1209 * SPTE_AD_WRPROT_ONLY_MASK.
1210 */
1211 spte |= shadow_dirty_mask;
1212
1213 return mmu_spte_update(sptep, spte);
1214 }
1215
1216 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1217 {
1218 u64 *sptep;
1219 struct rmap_iterator iter;
1220 bool flush = false;
1221
1222 for_each_rmap_spte(rmap_head, &iter, sptep)
1223 if (spte_ad_enabled(*sptep))
1224 flush |= spte_set_dirty(sptep);
1225
1226 return flush;
1227 }
1228
1229 /**
1230 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1231 * @kvm: kvm instance
1232 * @slot: slot to protect
1233 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1234 * @mask: indicates which pages we should protect
1235 *
1236 * Used when we do not need to care about huge page mappings: e.g. during dirty
1237 * logging we do not have any such mappings.
1238 */
1239 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1240 struct kvm_memory_slot *slot,
1241 gfn_t gfn_offset, unsigned long mask)
1242 {
1243 struct kvm_rmap_head *rmap_head;
1244
1245 while (mask) {
1246 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1247 PG_LEVEL_4K, slot);
1248 __rmap_write_protect(kvm, rmap_head, false);
1249
1250 /* clear the first set bit */
1251 mask &= mask - 1;
1252 }
1253 }
1254
1255 /**
1256 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1257 * protect the page if the D-bit isn't supported.
1258 * @kvm: kvm instance
1259 * @slot: slot to clear D-bit
1260 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1261 * @mask: indicates which pages we should clear D-bit
1262 *
1263 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1264 */
1265 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1266 struct kvm_memory_slot *slot,
1267 gfn_t gfn_offset, unsigned long mask)
1268 {
1269 struct kvm_rmap_head *rmap_head;
1270
1271 while (mask) {
1272 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1273 PG_LEVEL_4K, slot);
1274 __rmap_clear_dirty(kvm, rmap_head);
1275
1276 /* clear the first set bit */
1277 mask &= mask - 1;
1278 }
1279 }
1280 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1281
1282 /**
1283 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1284 * PT level pages.
1285 *
1286 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1287 * enable dirty logging for them.
1288 *
1289 * Used when we do not need to care about huge page mappings: e.g. during dirty
1290 * logging we do not have any such mappings.
1291 */
1292 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1293 struct kvm_memory_slot *slot,
1294 gfn_t gfn_offset, unsigned long mask)
1295 {
1296 if (kvm_x86_ops.enable_log_dirty_pt_masked)
1297 kvm_x86_ops.enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1298 mask);
1299 else
1300 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1301 }
1302
1303 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1304 struct kvm_memory_slot *slot, u64 gfn)
1305 {
1306 struct kvm_rmap_head *rmap_head;
1307 int i;
1308 bool write_protected = false;
1309
1310 for (i = PG_LEVEL_4K; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
1311 rmap_head = __gfn_to_rmap(gfn, i, slot);
1312 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1313 }
1314
1315 return write_protected;
1316 }
1317
1318 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1319 {
1320 struct kvm_memory_slot *slot;
1321
1322 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1323 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1324 }
1325
1326 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1327 {
1328 u64 *sptep;
1329 struct rmap_iterator iter;
1330 bool flush = false;
1331
1332 while ((sptep = rmap_get_first(rmap_head, &iter))) {
1333 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1334
1335 pte_list_remove(rmap_head, sptep);
1336 flush = true;
1337 }
1338
1339 return flush;
1340 }
1341
1342 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1343 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1344 unsigned long data)
1345 {
1346 return kvm_zap_rmapp(kvm, rmap_head);
1347 }
1348
1349 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1350 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1351 unsigned long data)
1352 {
1353 u64 *sptep;
1354 struct rmap_iterator iter;
1355 int need_flush = 0;
1356 u64 new_spte;
1357 pte_t *ptep = (pte_t *)data;
1358 kvm_pfn_t new_pfn;
1359
1360 WARN_ON(pte_huge(*ptep));
1361 new_pfn = pte_pfn(*ptep);
1362
1363 restart:
1364 for_each_rmap_spte(rmap_head, &iter, sptep) {
1365 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1366 sptep, *sptep, gfn, level);
1367
1368 need_flush = 1;
1369
1370 if (pte_write(*ptep)) {
1371 pte_list_remove(rmap_head, sptep);
1372 goto restart;
1373 } else {
1374 new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1375 *sptep, new_pfn);
1376
1377 mmu_spte_clear_track_bits(sptep);
1378 mmu_spte_set(sptep, new_spte);
1379 }
1380 }
1381
1382 if (need_flush && kvm_available_flush_tlb_with_range()) {
1383 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1384 return 0;
1385 }
1386
1387 return need_flush;
1388 }
1389
1390 struct slot_rmap_walk_iterator {
1391 /* input fields. */
1392 struct kvm_memory_slot *slot;
1393 gfn_t start_gfn;
1394 gfn_t end_gfn;
1395 int start_level;
1396 int end_level;
1397
1398 /* output fields. */
1399 gfn_t gfn;
1400 struct kvm_rmap_head *rmap;
1401 int level;
1402
1403 /* private field. */
1404 struct kvm_rmap_head *end_rmap;
1405 };
1406
1407 static void
1408 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1409 {
1410 iterator->level = level;
1411 iterator->gfn = iterator->start_gfn;
1412 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1413 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1414 iterator->slot);
1415 }
1416
1417 static void
1418 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1419 struct kvm_memory_slot *slot, int start_level,
1420 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1421 {
1422 iterator->slot = slot;
1423 iterator->start_level = start_level;
1424 iterator->end_level = end_level;
1425 iterator->start_gfn = start_gfn;
1426 iterator->end_gfn = end_gfn;
1427
1428 rmap_walk_init_level(iterator, iterator->start_level);
1429 }
1430
1431 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1432 {
1433 return !!iterator->rmap;
1434 }
1435
1436 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1437 {
1438 if (++iterator->rmap <= iterator->end_rmap) {
1439 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1440 return;
1441 }
1442
1443 if (++iterator->level > iterator->end_level) {
1444 iterator->rmap = NULL;
1445 return;
1446 }
1447
1448 rmap_walk_init_level(iterator, iterator->level);
1449 }
1450
1451 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1452 _start_gfn, _end_gfn, _iter_) \
1453 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1454 _end_level_, _start_gfn, _end_gfn); \
1455 slot_rmap_walk_okay(_iter_); \
1456 slot_rmap_walk_next(_iter_))
1457
1458 static int kvm_handle_hva_range(struct kvm *kvm,
1459 unsigned long start,
1460 unsigned long end,
1461 unsigned long data,
1462 int (*handler)(struct kvm *kvm,
1463 struct kvm_rmap_head *rmap_head,
1464 struct kvm_memory_slot *slot,
1465 gfn_t gfn,
1466 int level,
1467 unsigned long data))
1468 {
1469 struct kvm_memslots *slots;
1470 struct kvm_memory_slot *memslot;
1471 struct slot_rmap_walk_iterator iterator;
1472 int ret = 0;
1473 int i;
1474
1475 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1476 slots = __kvm_memslots(kvm, i);
1477 kvm_for_each_memslot(memslot, slots) {
1478 unsigned long hva_start, hva_end;
1479 gfn_t gfn_start, gfn_end;
1480
1481 hva_start = max(start, memslot->userspace_addr);
1482 hva_end = min(end, memslot->userspace_addr +
1483 (memslot->npages << PAGE_SHIFT));
1484 if (hva_start >= hva_end)
1485 continue;
1486 /*
1487 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1488 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1489 */
1490 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1491 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1492
1493 for_each_slot_rmap_range(memslot, PG_LEVEL_4K,
1494 KVM_MAX_HUGEPAGE_LEVEL,
1495 gfn_start, gfn_end - 1,
1496 &iterator)
1497 ret |= handler(kvm, iterator.rmap, memslot,
1498 iterator.gfn, iterator.level, data);
1499 }
1500 }
1501
1502 return ret;
1503 }
1504
1505 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1506 unsigned long data,
1507 int (*handler)(struct kvm *kvm,
1508 struct kvm_rmap_head *rmap_head,
1509 struct kvm_memory_slot *slot,
1510 gfn_t gfn, int level,
1511 unsigned long data))
1512 {
1513 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1514 }
1515
1516 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end,
1517 unsigned flags)
1518 {
1519 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1520 }
1521
1522 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1523 {
1524 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1525 }
1526
1527 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1528 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1529 unsigned long data)
1530 {
1531 u64 *sptep;
1532 struct rmap_iterator iter;
1533 int young = 0;
1534
1535 for_each_rmap_spte(rmap_head, &iter, sptep)
1536 young |= mmu_spte_age(sptep);
1537
1538 trace_kvm_age_page(gfn, level, slot, young);
1539 return young;
1540 }
1541
1542 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1543 struct kvm_memory_slot *slot, gfn_t gfn,
1544 int level, unsigned long data)
1545 {
1546 u64 *sptep;
1547 struct rmap_iterator iter;
1548
1549 for_each_rmap_spte(rmap_head, &iter, sptep)
1550 if (is_accessed_spte(*sptep))
1551 return 1;
1552 return 0;
1553 }
1554
1555 #define RMAP_RECYCLE_THRESHOLD 1000
1556
1557 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1558 {
1559 struct kvm_rmap_head *rmap_head;
1560 struct kvm_mmu_page *sp;
1561
1562 sp = sptep_to_sp(spte);
1563
1564 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1565
1566 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
1567 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1568 KVM_PAGES_PER_HPAGE(sp->role.level));
1569 }
1570
1571 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
1572 {
1573 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
1574 }
1575
1576 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1577 {
1578 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
1579 }
1580
1581 #ifdef MMU_DEBUG
1582 static int is_empty_shadow_page(u64 *spt)
1583 {
1584 u64 *pos;
1585 u64 *end;
1586
1587 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1588 if (is_shadow_present_pte(*pos)) {
1589 printk(KERN_ERR "%s: %p %llx\n", __func__,
1590 pos, *pos);
1591 return 0;
1592 }
1593 return 1;
1594 }
1595 #endif
1596
1597 /*
1598 * This value is the sum of all of the kvm instances's
1599 * kvm->arch.n_used_mmu_pages values. We need a global,
1600 * aggregate version in order to make the slab shrinker
1601 * faster
1602 */
1603 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
1604 {
1605 kvm->arch.n_used_mmu_pages += nr;
1606 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1607 }
1608
1609 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
1610 {
1611 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
1612 hlist_del(&sp->hash_link);
1613 list_del(&sp->link);
1614 free_page((unsigned long)sp->spt);
1615 if (!sp->role.direct)
1616 free_page((unsigned long)sp->gfns);
1617 kmem_cache_free(mmu_page_header_cache, sp);
1618 }
1619
1620 static unsigned kvm_page_table_hashfn(gfn_t gfn)
1621 {
1622 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1623 }
1624
1625 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
1626 struct kvm_mmu_page *sp, u64 *parent_pte)
1627 {
1628 if (!parent_pte)
1629 return;
1630
1631 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
1632 }
1633
1634 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1635 u64 *parent_pte)
1636 {
1637 __pte_list_remove(parent_pte, &sp->parent_ptes);
1638 }
1639
1640 static void drop_parent_pte(struct kvm_mmu_page *sp,
1641 u64 *parent_pte)
1642 {
1643 mmu_page_remove_parent_pte(sp, parent_pte);
1644 mmu_spte_clear_no_track(parent_pte);
1645 }
1646
1647 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
1648 {
1649 struct kvm_mmu_page *sp;
1650
1651 sp = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
1652 sp->spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_shadow_page_cache);
1653 if (!direct)
1654 sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
1655 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
1656
1657 /*
1658 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
1659 * depends on valid pages being added to the head of the list. See
1660 * comments in kvm_zap_obsolete_pages().
1661 */
1662 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
1663 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
1664 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
1665 return sp;
1666 }
1667
1668 static void mark_unsync(u64 *spte);
1669 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1670 {
1671 u64 *sptep;
1672 struct rmap_iterator iter;
1673
1674 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1675 mark_unsync(sptep);
1676 }
1677 }
1678
1679 static void mark_unsync(u64 *spte)
1680 {
1681 struct kvm_mmu_page *sp;
1682 unsigned int index;
1683
1684 sp = sptep_to_sp(spte);
1685 index = spte - sp->spt;
1686 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
1687 return;
1688 if (sp->unsync_children++)
1689 return;
1690 kvm_mmu_mark_parents_unsync(sp);
1691 }
1692
1693 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
1694 struct kvm_mmu_page *sp)
1695 {
1696 return 0;
1697 }
1698
1699 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
1700 struct kvm_mmu_page *sp, u64 *spte,
1701 const void *pte)
1702 {
1703 WARN_ON(1);
1704 }
1705
1706 #define KVM_PAGE_ARRAY_NR 16
1707
1708 struct kvm_mmu_pages {
1709 struct mmu_page_and_offset {
1710 struct kvm_mmu_page *sp;
1711 unsigned int idx;
1712 } page[KVM_PAGE_ARRAY_NR];
1713 unsigned int nr;
1714 };
1715
1716 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1717 int idx)
1718 {
1719 int i;
1720
1721 if (sp->unsync)
1722 for (i=0; i < pvec->nr; i++)
1723 if (pvec->page[i].sp == sp)
1724 return 0;
1725
1726 pvec->page[pvec->nr].sp = sp;
1727 pvec->page[pvec->nr].idx = idx;
1728 pvec->nr++;
1729 return (pvec->nr == KVM_PAGE_ARRAY_NR);
1730 }
1731
1732 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1733 {
1734 --sp->unsync_children;
1735 WARN_ON((int)sp->unsync_children < 0);
1736 __clear_bit(idx, sp->unsync_child_bitmap);
1737 }
1738
1739 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1740 struct kvm_mmu_pages *pvec)
1741 {
1742 int i, ret, nr_unsync_leaf = 0;
1743
1744 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1745 struct kvm_mmu_page *child;
1746 u64 ent = sp->spt[i];
1747
1748 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1749 clear_unsync_child_bit(sp, i);
1750 continue;
1751 }
1752
1753 child = to_shadow_page(ent & PT64_BASE_ADDR_MASK);
1754
1755 if (child->unsync_children) {
1756 if (mmu_pages_add(pvec, child, i))
1757 return -ENOSPC;
1758
1759 ret = __mmu_unsync_walk(child, pvec);
1760 if (!ret) {
1761 clear_unsync_child_bit(sp, i);
1762 continue;
1763 } else if (ret > 0) {
1764 nr_unsync_leaf += ret;
1765 } else
1766 return ret;
1767 } else if (child->unsync) {
1768 nr_unsync_leaf++;
1769 if (mmu_pages_add(pvec, child, i))
1770 return -ENOSPC;
1771 } else
1772 clear_unsync_child_bit(sp, i);
1773 }
1774
1775 return nr_unsync_leaf;
1776 }
1777
1778 #define INVALID_INDEX (-1)
1779
1780 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1781 struct kvm_mmu_pages *pvec)
1782 {
1783 pvec->nr = 0;
1784 if (!sp->unsync_children)
1785 return 0;
1786
1787 mmu_pages_add(pvec, sp, INVALID_INDEX);
1788 return __mmu_unsync_walk(sp, pvec);
1789 }
1790
1791 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1792 {
1793 WARN_ON(!sp->unsync);
1794 trace_kvm_mmu_sync_page(sp);
1795 sp->unsync = 0;
1796 --kvm->stat.mmu_unsync;
1797 }
1798
1799 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1800 struct list_head *invalid_list);
1801 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1802 struct list_head *invalid_list);
1803
1804 #define for_each_valid_sp(_kvm, _sp, _list) \
1805 hlist_for_each_entry(_sp, _list, hash_link) \
1806 if (is_obsolete_sp((_kvm), (_sp))) { \
1807 } else
1808
1809 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
1810 for_each_valid_sp(_kvm, _sp, \
1811 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)]) \
1812 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
1813
1814 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
1815 {
1816 return sp->role.cr0_wp && sp->role.smap_andnot_wp;
1817 }
1818
1819 /* @sp->gfn should be write-protected at the call site */
1820 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1821 struct list_head *invalid_list)
1822 {
1823 if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
1824 vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
1825 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
1826 return false;
1827 }
1828
1829 return true;
1830 }
1831
1832 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
1833 struct list_head *invalid_list,
1834 bool remote_flush)
1835 {
1836 if (!remote_flush && list_empty(invalid_list))
1837 return false;
1838
1839 if (!list_empty(invalid_list))
1840 kvm_mmu_commit_zap_page(kvm, invalid_list);
1841 else
1842 kvm_flush_remote_tlbs(kvm);
1843 return true;
1844 }
1845
1846 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
1847 struct list_head *invalid_list,
1848 bool remote_flush, bool local_flush)
1849 {
1850 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
1851 return;
1852
1853 if (local_flush)
1854 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1855 }
1856
1857 #ifdef CONFIG_KVM_MMU_AUDIT
1858 #include "mmu_audit.c"
1859 #else
1860 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
1861 static void mmu_audit_disable(void) { }
1862 #endif
1863
1864 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
1865 {
1866 return sp->role.invalid ||
1867 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
1868 }
1869
1870 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1871 struct list_head *invalid_list)
1872 {
1873 kvm_unlink_unsync_page(vcpu->kvm, sp);
1874 return __kvm_sync_page(vcpu, sp, invalid_list);
1875 }
1876
1877 /* @gfn should be write-protected at the call site */
1878 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
1879 struct list_head *invalid_list)
1880 {
1881 struct kvm_mmu_page *s;
1882 bool ret = false;
1883
1884 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
1885 if (!s->unsync)
1886 continue;
1887
1888 WARN_ON(s->role.level != PG_LEVEL_4K);
1889 ret |= kvm_sync_page(vcpu, s, invalid_list);
1890 }
1891
1892 return ret;
1893 }
1894
1895 struct mmu_page_path {
1896 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
1897 unsigned int idx[PT64_ROOT_MAX_LEVEL];
1898 };
1899
1900 #define for_each_sp(pvec, sp, parents, i) \
1901 for (i = mmu_pages_first(&pvec, &parents); \
1902 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
1903 i = mmu_pages_next(&pvec, &parents, i))
1904
1905 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1906 struct mmu_page_path *parents,
1907 int i)
1908 {
1909 int n;
1910
1911 for (n = i+1; n < pvec->nr; n++) {
1912 struct kvm_mmu_page *sp = pvec->page[n].sp;
1913 unsigned idx = pvec->page[n].idx;
1914 int level = sp->role.level;
1915
1916 parents->idx[level-1] = idx;
1917 if (level == PG_LEVEL_4K)
1918 break;
1919
1920 parents->parent[level-2] = sp;
1921 }
1922
1923 return n;
1924 }
1925
1926 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
1927 struct mmu_page_path *parents)
1928 {
1929 struct kvm_mmu_page *sp;
1930 int level;
1931
1932 if (pvec->nr == 0)
1933 return 0;
1934
1935 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
1936
1937 sp = pvec->page[0].sp;
1938 level = sp->role.level;
1939 WARN_ON(level == PG_LEVEL_4K);
1940
1941 parents->parent[level-2] = sp;
1942
1943 /* Also set up a sentinel. Further entries in pvec are all
1944 * children of sp, so this element is never overwritten.
1945 */
1946 parents->parent[level-1] = NULL;
1947 return mmu_pages_next(pvec, parents, 0);
1948 }
1949
1950 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
1951 {
1952 struct kvm_mmu_page *sp;
1953 unsigned int level = 0;
1954
1955 do {
1956 unsigned int idx = parents->idx[level];
1957 sp = parents->parent[level];
1958 if (!sp)
1959 return;
1960
1961 WARN_ON(idx == INVALID_INDEX);
1962 clear_unsync_child_bit(sp, idx);
1963 level++;
1964 } while (!sp->unsync_children);
1965 }
1966
1967 static void mmu_sync_children(struct kvm_vcpu *vcpu,
1968 struct kvm_mmu_page *parent)
1969 {
1970 int i;
1971 struct kvm_mmu_page *sp;
1972 struct mmu_page_path parents;
1973 struct kvm_mmu_pages pages;
1974 LIST_HEAD(invalid_list);
1975 bool flush = false;
1976
1977 while (mmu_unsync_walk(parent, &pages)) {
1978 bool protected = false;
1979
1980 for_each_sp(pages, sp, parents, i)
1981 protected |= rmap_write_protect(vcpu, sp->gfn);
1982
1983 if (protected) {
1984 kvm_flush_remote_tlbs(vcpu->kvm);
1985 flush = false;
1986 }
1987
1988 for_each_sp(pages, sp, parents, i) {
1989 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
1990 mmu_pages_clear_parents(&parents);
1991 }
1992 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
1993 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
1994 cond_resched_lock(&vcpu->kvm->mmu_lock);
1995 flush = false;
1996 }
1997 }
1998
1999 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2000 }
2001
2002 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2003 {
2004 atomic_set(&sp->write_flooding_count, 0);
2005 }
2006
2007 static void clear_sp_write_flooding_count(u64 *spte)
2008 {
2009 __clear_sp_write_flooding_count(sptep_to_sp(spte));
2010 }
2011
2012 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2013 gfn_t gfn,
2014 gva_t gaddr,
2015 unsigned level,
2016 int direct,
2017 unsigned int access)
2018 {
2019 bool direct_mmu = vcpu->arch.mmu->direct_map;
2020 union kvm_mmu_page_role role;
2021 struct hlist_head *sp_list;
2022 unsigned quadrant;
2023 struct kvm_mmu_page *sp;
2024 bool need_sync = false;
2025 bool flush = false;
2026 int collisions = 0;
2027 LIST_HEAD(invalid_list);
2028
2029 role = vcpu->arch.mmu->mmu_role.base;
2030 role.level = level;
2031 role.direct = direct;
2032 if (role.direct)
2033 role.gpte_is_8_bytes = true;
2034 role.access = access;
2035 if (!direct_mmu && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2036 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2037 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2038 role.quadrant = quadrant;
2039 }
2040
2041 sp_list = &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2042 for_each_valid_sp(vcpu->kvm, sp, sp_list) {
2043 if (sp->gfn != gfn) {
2044 collisions++;
2045 continue;
2046 }
2047
2048 if (!need_sync && sp->unsync)
2049 need_sync = true;
2050
2051 if (sp->role.word != role.word)
2052 continue;
2053
2054 if (direct_mmu)
2055 goto trace_get_page;
2056
2057 if (sp->unsync) {
2058 /* The page is good, but __kvm_sync_page might still end
2059 * up zapping it. If so, break in order to rebuild it.
2060 */
2061 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2062 break;
2063
2064 WARN_ON(!list_empty(&invalid_list));
2065 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2066 }
2067
2068 if (sp->unsync_children)
2069 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2070
2071 __clear_sp_write_flooding_count(sp);
2072
2073 trace_get_page:
2074 trace_kvm_mmu_get_page(sp, false);
2075 goto out;
2076 }
2077
2078 ++vcpu->kvm->stat.mmu_cache_miss;
2079
2080 sp = kvm_mmu_alloc_page(vcpu, direct);
2081
2082 sp->gfn = gfn;
2083 sp->role = role;
2084 hlist_add_head(&sp->hash_link, sp_list);
2085 if (!direct) {
2086 /*
2087 * we should do write protection before syncing pages
2088 * otherwise the content of the synced shadow page may
2089 * be inconsistent with guest page table.
2090 */
2091 account_shadowed(vcpu->kvm, sp);
2092 if (level == PG_LEVEL_4K && rmap_write_protect(vcpu, gfn))
2093 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2094
2095 if (level > PG_LEVEL_4K && need_sync)
2096 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2097 }
2098 trace_kvm_mmu_get_page(sp, true);
2099
2100 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2101 out:
2102 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2103 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2104 return sp;
2105 }
2106
2107 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2108 struct kvm_vcpu *vcpu, hpa_t root,
2109 u64 addr)
2110 {
2111 iterator->addr = addr;
2112 iterator->shadow_addr = root;
2113 iterator->level = vcpu->arch.mmu->shadow_root_level;
2114
2115 if (iterator->level == PT64_ROOT_4LEVEL &&
2116 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2117 !vcpu->arch.mmu->direct_map)
2118 --iterator->level;
2119
2120 if (iterator->level == PT32E_ROOT_LEVEL) {
2121 /*
2122 * prev_root is currently only used for 64-bit hosts. So only
2123 * the active root_hpa is valid here.
2124 */
2125 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2126
2127 iterator->shadow_addr
2128 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2129 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2130 --iterator->level;
2131 if (!iterator->shadow_addr)
2132 iterator->level = 0;
2133 }
2134 }
2135
2136 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2137 struct kvm_vcpu *vcpu, u64 addr)
2138 {
2139 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2140 addr);
2141 }
2142
2143 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2144 {
2145 if (iterator->level < PG_LEVEL_4K)
2146 return false;
2147
2148 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2149 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2150 return true;
2151 }
2152
2153 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2154 u64 spte)
2155 {
2156 if (is_last_spte(spte, iterator->level)) {
2157 iterator->level = 0;
2158 return;
2159 }
2160
2161 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2162 --iterator->level;
2163 }
2164
2165 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2166 {
2167 __shadow_walk_next(iterator, *iterator->sptep);
2168 }
2169
2170 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2171 struct kvm_mmu_page *sp)
2172 {
2173 u64 spte;
2174
2175 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2176
2177 spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2178
2179 mmu_spte_set(sptep, spte);
2180
2181 mmu_page_add_parent_pte(vcpu, sp, sptep);
2182
2183 if (sp->unsync_children || sp->unsync)
2184 mark_unsync(sptep);
2185 }
2186
2187 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2188 unsigned direct_access)
2189 {
2190 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2191 struct kvm_mmu_page *child;
2192
2193 /*
2194 * For the direct sp, if the guest pte's dirty bit
2195 * changed form clean to dirty, it will corrupt the
2196 * sp's access: allow writable in the read-only sp,
2197 * so we should update the spte at this point to get
2198 * a new sp with the correct access.
2199 */
2200 child = to_shadow_page(*sptep & PT64_BASE_ADDR_MASK);
2201 if (child->role.access == direct_access)
2202 return;
2203
2204 drop_parent_pte(child, sptep);
2205 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2206 }
2207 }
2208
2209 /* Returns the number of zapped non-leaf child shadow pages. */
2210 static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2211 u64 *spte, struct list_head *invalid_list)
2212 {
2213 u64 pte;
2214 struct kvm_mmu_page *child;
2215
2216 pte = *spte;
2217 if (is_shadow_present_pte(pte)) {
2218 if (is_last_spte(pte, sp->role.level)) {
2219 drop_spte(kvm, spte);
2220 if (is_large_pte(pte))
2221 --kvm->stat.lpages;
2222 } else {
2223 child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
2224 drop_parent_pte(child, spte);
2225
2226 /*
2227 * Recursively zap nested TDP SPs, parentless SPs are
2228 * unlikely to be used again in the near future. This
2229 * avoids retaining a large number of stale nested SPs.
2230 */
2231 if (tdp_enabled && invalid_list &&
2232 child->role.guest_mode && !child->parent_ptes.val)
2233 return kvm_mmu_prepare_zap_page(kvm, child,
2234 invalid_list);
2235 }
2236 } else if (is_mmio_spte(pte)) {
2237 mmu_spte_clear_no_track(spte);
2238 }
2239 return 0;
2240 }
2241
2242 static int kvm_mmu_page_unlink_children(struct kvm *kvm,
2243 struct kvm_mmu_page *sp,
2244 struct list_head *invalid_list)
2245 {
2246 int zapped = 0;
2247 unsigned i;
2248
2249 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2250 zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
2251
2252 return zapped;
2253 }
2254
2255 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2256 {
2257 u64 *sptep;
2258 struct rmap_iterator iter;
2259
2260 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2261 drop_parent_pte(sp, sptep);
2262 }
2263
2264 static int mmu_zap_unsync_children(struct kvm *kvm,
2265 struct kvm_mmu_page *parent,
2266 struct list_head *invalid_list)
2267 {
2268 int i, zapped = 0;
2269 struct mmu_page_path parents;
2270 struct kvm_mmu_pages pages;
2271
2272 if (parent->role.level == PG_LEVEL_4K)
2273 return 0;
2274
2275 while (mmu_unsync_walk(parent, &pages)) {
2276 struct kvm_mmu_page *sp;
2277
2278 for_each_sp(pages, sp, parents, i) {
2279 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2280 mmu_pages_clear_parents(&parents);
2281 zapped++;
2282 }
2283 }
2284
2285 return zapped;
2286 }
2287
2288 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2289 struct kvm_mmu_page *sp,
2290 struct list_head *invalid_list,
2291 int *nr_zapped)
2292 {
2293 bool list_unstable;
2294
2295 trace_kvm_mmu_prepare_zap_page(sp);
2296 ++kvm->stat.mmu_shadow_zapped;
2297 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2298 *nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
2299 kvm_mmu_unlink_parents(kvm, sp);
2300
2301 /* Zapping children means active_mmu_pages has become unstable. */
2302 list_unstable = *nr_zapped;
2303
2304 if (!sp->role.invalid && !sp->role.direct)
2305 unaccount_shadowed(kvm, sp);
2306
2307 if (sp->unsync)
2308 kvm_unlink_unsync_page(kvm, sp);
2309 if (!sp->root_count) {
2310 /* Count self */
2311 (*nr_zapped)++;
2312
2313 /*
2314 * Already invalid pages (previously active roots) are not on
2315 * the active page list. See list_del() in the "else" case of
2316 * !sp->root_count.
2317 */
2318 if (sp->role.invalid)
2319 list_add(&sp->link, invalid_list);
2320 else
2321 list_move(&sp->link, invalid_list);
2322 kvm_mod_used_mmu_pages(kvm, -1);
2323 } else {
2324 /*
2325 * Remove the active root from the active page list, the root
2326 * will be explicitly freed when the root_count hits zero.
2327 */
2328 list_del(&sp->link);
2329
2330 /*
2331 * Obsolete pages cannot be used on any vCPUs, see the comment
2332 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2333 * treats invalid shadow pages as being obsolete.
2334 */
2335 if (!is_obsolete_sp(kvm, sp))
2336 kvm_reload_remote_mmus(kvm);
2337 }
2338
2339 if (sp->lpage_disallowed)
2340 unaccount_huge_nx_page(kvm, sp);
2341
2342 sp->role.invalid = 1;
2343 return list_unstable;
2344 }
2345
2346 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2347 struct list_head *invalid_list)
2348 {
2349 int nr_zapped;
2350
2351 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2352 return nr_zapped;
2353 }
2354
2355 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2356 struct list_head *invalid_list)
2357 {
2358 struct kvm_mmu_page *sp, *nsp;
2359
2360 if (list_empty(invalid_list))
2361 return;
2362
2363 /*
2364 * We need to make sure everyone sees our modifications to
2365 * the page tables and see changes to vcpu->mode here. The barrier
2366 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2367 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2368 *
2369 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2370 * guest mode and/or lockless shadow page table walks.
2371 */
2372 kvm_flush_remote_tlbs(kvm);
2373
2374 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2375 WARN_ON(!sp->role.invalid || sp->root_count);
2376 kvm_mmu_free_page(sp);
2377 }
2378 }
2379
2380 static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
2381 unsigned long nr_to_zap)
2382 {
2383 unsigned long total_zapped = 0;
2384 struct kvm_mmu_page *sp, *tmp;
2385 LIST_HEAD(invalid_list);
2386 bool unstable;
2387 int nr_zapped;
2388
2389 if (list_empty(&kvm->arch.active_mmu_pages))
2390 return 0;
2391
2392 restart:
2393 list_for_each_entry_safe(sp, tmp, &kvm->arch.active_mmu_pages, link) {
2394 /*
2395 * Don't zap active root pages, the page itself can't be freed
2396 * and zapping it will just force vCPUs to realloc and reload.
2397 */
2398 if (sp->root_count)
2399 continue;
2400
2401 unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
2402 &nr_zapped);
2403 total_zapped += nr_zapped;
2404 if (total_zapped >= nr_to_zap)
2405 break;
2406
2407 if (unstable)
2408 goto restart;
2409 }
2410
2411 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2412
2413 kvm->stat.mmu_recycled += total_zapped;
2414 return total_zapped;
2415 }
2416
2417 static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2418 {
2419 if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2420 return kvm->arch.n_max_mmu_pages -
2421 kvm->arch.n_used_mmu_pages;
2422
2423 return 0;
2424 }
2425
2426 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2427 {
2428 unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2429
2430 if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2431 return 0;
2432
2433 kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2434
2435 if (!kvm_mmu_available_pages(vcpu->kvm))
2436 return -ENOSPC;
2437 return 0;
2438 }
2439
2440 /*
2441 * Changing the number of mmu pages allocated to the vm
2442 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2443 */
2444 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2445 {
2446 spin_lock(&kvm->mmu_lock);
2447
2448 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2449 kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
2450 goal_nr_mmu_pages);
2451
2452 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2453 }
2454
2455 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2456
2457 spin_unlock(&kvm->mmu_lock);
2458 }
2459
2460 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2461 {
2462 struct kvm_mmu_page *sp;
2463 LIST_HEAD(invalid_list);
2464 int r;
2465
2466 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2467 r = 0;
2468 spin_lock(&kvm->mmu_lock);
2469 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2470 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2471 sp->role.word);
2472 r = 1;
2473 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2474 }
2475 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2476 spin_unlock(&kvm->mmu_lock);
2477
2478 return r;
2479 }
2480 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2481
2482 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2483 {
2484 trace_kvm_mmu_unsync_page(sp);
2485 ++vcpu->kvm->stat.mmu_unsync;
2486 sp->unsync = 1;
2487
2488 kvm_mmu_mark_parents_unsync(sp);
2489 }
2490
2491 bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2492 bool can_unsync)
2493 {
2494 struct kvm_mmu_page *sp;
2495
2496 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2497 return true;
2498
2499 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2500 if (!can_unsync)
2501 return true;
2502
2503 if (sp->unsync)
2504 continue;
2505
2506 WARN_ON(sp->role.level != PG_LEVEL_4K);
2507 kvm_unsync_page(vcpu, sp);
2508 }
2509
2510 /*
2511 * We need to ensure that the marking of unsync pages is visible
2512 * before the SPTE is updated to allow writes because
2513 * kvm_mmu_sync_roots() checks the unsync flags without holding
2514 * the MMU lock and so can race with this. If the SPTE was updated
2515 * before the page had been marked as unsync-ed, something like the
2516 * following could happen:
2517 *
2518 * CPU 1 CPU 2
2519 * ---------------------------------------------------------------------
2520 * 1.2 Host updates SPTE
2521 * to be writable
2522 * 2.1 Guest writes a GPTE for GVA X.
2523 * (GPTE being in the guest page table shadowed
2524 * by the SP from CPU 1.)
2525 * This reads SPTE during the page table walk.
2526 * Since SPTE.W is read as 1, there is no
2527 * fault.
2528 *
2529 * 2.2 Guest issues TLB flush.
2530 * That causes a VM Exit.
2531 *
2532 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2533 * Since it is false, so it just returns.
2534 *
2535 * 2.4 Guest accesses GVA X.
2536 * Since the mapping in the SP was not updated,
2537 * so the old mapping for GVA X incorrectly
2538 * gets used.
2539 * 1.1 Host marks SP
2540 * as unsync
2541 * (sp->unsync = true)
2542 *
2543 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2544 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2545 * pairs with this write barrier.
2546 */
2547 smp_wmb();
2548
2549 return false;
2550 }
2551
2552 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2553 unsigned int pte_access, int level,
2554 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2555 bool can_unsync, bool host_writable)
2556 {
2557 u64 spte;
2558 struct kvm_mmu_page *sp;
2559 int ret;
2560
2561 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2562 return 0;
2563
2564 sp = sptep_to_sp(sptep);
2565
2566 ret = make_spte(vcpu, pte_access, level, gfn, pfn, *sptep, speculative,
2567 can_unsync, host_writable, sp_ad_disabled(sp), &spte);
2568
2569 if (spte & PT_WRITABLE_MASK)
2570 kvm_vcpu_mark_page_dirty(vcpu, gfn);
2571
2572 if (*sptep == spte)
2573 ret |= SET_SPTE_SPURIOUS;
2574 else if (mmu_spte_update(sptep, spte))
2575 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
2576 return ret;
2577 }
2578
2579 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2580 unsigned int pte_access, bool write_fault, int level,
2581 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2582 bool host_writable)
2583 {
2584 int was_rmapped = 0;
2585 int rmap_count;
2586 int set_spte_ret;
2587 int ret = RET_PF_FIXED;
2588 bool flush = false;
2589
2590 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2591 *sptep, write_fault, gfn);
2592
2593 if (is_shadow_present_pte(*sptep)) {
2594 /*
2595 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2596 * the parent of the now unreachable PTE.
2597 */
2598 if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2599 struct kvm_mmu_page *child;
2600 u64 pte = *sptep;
2601
2602 child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
2603 drop_parent_pte(child, sptep);
2604 flush = true;
2605 } else if (pfn != spte_to_pfn(*sptep)) {
2606 pgprintk("hfn old %llx new %llx\n",
2607 spte_to_pfn(*sptep), pfn);
2608 drop_spte(vcpu->kvm, sptep);
2609 flush = true;
2610 } else
2611 was_rmapped = 1;
2612 }
2613
2614 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
2615 speculative, true, host_writable);
2616 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
2617 if (write_fault)
2618 ret = RET_PF_EMULATE;
2619 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2620 }
2621
2622 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
2623 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
2624 KVM_PAGES_PER_HPAGE(level));
2625
2626 if (unlikely(is_mmio_spte(*sptep)))
2627 ret = RET_PF_EMULATE;
2628
2629 /*
2630 * The fault is fully spurious if and only if the new SPTE and old SPTE
2631 * are identical, and emulation is not required.
2632 */
2633 if ((set_spte_ret & SET_SPTE_SPURIOUS) && ret == RET_PF_FIXED) {
2634 WARN_ON_ONCE(!was_rmapped);
2635 return RET_PF_SPURIOUS;
2636 }
2637
2638 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2639 trace_kvm_mmu_set_spte(level, gfn, sptep);
2640 if (!was_rmapped && is_large_pte(*sptep))
2641 ++vcpu->kvm->stat.lpages;
2642
2643 if (is_shadow_present_pte(*sptep)) {
2644 if (!was_rmapped) {
2645 rmap_count = rmap_add(vcpu, sptep, gfn);
2646 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
2647 rmap_recycle(vcpu, sptep, gfn);
2648 }
2649 }
2650
2651 return ret;
2652 }
2653
2654 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
2655 bool no_dirty_log)
2656 {
2657 struct kvm_memory_slot *slot;
2658
2659 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
2660 if (!slot)
2661 return KVM_PFN_ERR_FAULT;
2662
2663 return gfn_to_pfn_memslot_atomic(slot, gfn);
2664 }
2665
2666 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2667 struct kvm_mmu_page *sp,
2668 u64 *start, u64 *end)
2669 {
2670 struct page *pages[PTE_PREFETCH_NUM];
2671 struct kvm_memory_slot *slot;
2672 unsigned int access = sp->role.access;
2673 int i, ret;
2674 gfn_t gfn;
2675
2676 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
2677 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2678 if (!slot)
2679 return -1;
2680
2681 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2682 if (ret <= 0)
2683 return -1;
2684
2685 for (i = 0; i < ret; i++, gfn++, start++) {
2686 mmu_set_spte(vcpu, start, access, false, sp->role.level, gfn,
2687 page_to_pfn(pages[i]), true, true);
2688 put_page(pages[i]);
2689 }
2690
2691 return 0;
2692 }
2693
2694 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2695 struct kvm_mmu_page *sp, u64 *sptep)
2696 {
2697 u64 *spte, *start = NULL;
2698 int i;
2699
2700 WARN_ON(!sp->role.direct);
2701
2702 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
2703 spte = sp->spt + i;
2704
2705 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
2706 if (is_shadow_present_pte(*spte) || spte == sptep) {
2707 if (!start)
2708 continue;
2709 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2710 break;
2711 start = NULL;
2712 } else if (!start)
2713 start = spte;
2714 }
2715 }
2716
2717 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2718 {
2719 struct kvm_mmu_page *sp;
2720
2721 sp = sptep_to_sp(sptep);
2722
2723 /*
2724 * Without accessed bits, there's no way to distinguish between
2725 * actually accessed translations and prefetched, so disable pte
2726 * prefetch if accessed bits aren't available.
2727 */
2728 if (sp_ad_disabled(sp))
2729 return;
2730
2731 if (sp->role.level > PG_LEVEL_4K)
2732 return;
2733
2734 __direct_pte_prefetch(vcpu, sp, sptep);
2735 }
2736
2737 static int host_pfn_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn,
2738 kvm_pfn_t pfn, struct kvm_memory_slot *slot)
2739 {
2740 unsigned long hva;
2741 pte_t *pte;
2742 int level;
2743
2744 if (!PageCompound(pfn_to_page(pfn)) && !kvm_is_zone_device_pfn(pfn))
2745 return PG_LEVEL_4K;
2746
2747 /*
2748 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
2749 * is not solely for performance, it's also necessary to avoid the
2750 * "writable" check in __gfn_to_hva_many(), which will always fail on
2751 * read-only memslots due to gfn_to_hva() assuming writes. Earlier
2752 * page fault steps have already verified the guest isn't writing a
2753 * read-only memslot.
2754 */
2755 hva = __gfn_to_hva_memslot(slot, gfn);
2756
2757 pte = lookup_address_in_mm(vcpu->kvm->mm, hva, &level);
2758 if (unlikely(!pte))
2759 return PG_LEVEL_4K;
2760
2761 return level;
2762 }
2763
2764 static int kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, gfn_t gfn,
2765 int max_level, kvm_pfn_t *pfnp,
2766 bool huge_page_disallowed, int *req_level)
2767 {
2768 struct kvm_memory_slot *slot;
2769 struct kvm_lpage_info *linfo;
2770 kvm_pfn_t pfn = *pfnp;
2771 kvm_pfn_t mask;
2772 int level;
2773
2774 *req_level = PG_LEVEL_4K;
2775
2776 if (unlikely(max_level == PG_LEVEL_4K))
2777 return PG_LEVEL_4K;
2778
2779 if (is_error_noslot_pfn(pfn) || kvm_is_reserved_pfn(pfn))
2780 return PG_LEVEL_4K;
2781
2782 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, true);
2783 if (!slot)
2784 return PG_LEVEL_4K;
2785
2786 max_level = min(max_level, max_huge_page_level);
2787 for ( ; max_level > PG_LEVEL_4K; max_level--) {
2788 linfo = lpage_info_slot(gfn, slot, max_level);
2789 if (!linfo->disallow_lpage)
2790 break;
2791 }
2792
2793 if (max_level == PG_LEVEL_4K)
2794 return PG_LEVEL_4K;
2795
2796 level = host_pfn_mapping_level(vcpu, gfn, pfn, slot);
2797 if (level == PG_LEVEL_4K)
2798 return level;
2799
2800 *req_level = level = min(level, max_level);
2801
2802 /*
2803 * Enforce the iTLB multihit workaround after capturing the requested
2804 * level, which will be used to do precise, accurate accounting.
2805 */
2806 if (huge_page_disallowed)
2807 return PG_LEVEL_4K;
2808
2809 /*
2810 * mmu_notifier_retry() was successful and mmu_lock is held, so
2811 * the pmd can't be split from under us.
2812 */
2813 mask = KVM_PAGES_PER_HPAGE(level) - 1;
2814 VM_BUG_ON((gfn & mask) != (pfn & mask));
2815 *pfnp = pfn & ~mask;
2816
2817 return level;
2818 }
2819
2820 static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
2821 gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
2822 {
2823 int level = *levelp;
2824 u64 spte = *it.sptep;
2825
2826 if (it.level == level && level > PG_LEVEL_4K &&
2827 is_shadow_present_pte(spte) &&
2828 !is_large_pte(spte)) {
2829 /*
2830 * A small SPTE exists for this pfn, but FNAME(fetch)
2831 * and __direct_map would like to create a large PTE
2832 * instead: just force them to go down another level,
2833 * patching back for them into pfn the next 9 bits of
2834 * the address.
2835 */
2836 u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
2837 *pfnp |= gfn & page_mask;
2838 (*levelp)--;
2839 }
2840 }
2841
2842 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
2843 int map_writable, int max_level, kvm_pfn_t pfn,
2844 bool prefault, bool is_tdp)
2845 {
2846 bool nx_huge_page_workaround_enabled = is_nx_huge_page_enabled();
2847 bool write = error_code & PFERR_WRITE_MASK;
2848 bool exec = error_code & PFERR_FETCH_MASK;
2849 bool huge_page_disallowed = exec && nx_huge_page_workaround_enabled;
2850 struct kvm_shadow_walk_iterator it;
2851 struct kvm_mmu_page *sp;
2852 int level, req_level, ret;
2853 gfn_t gfn = gpa >> PAGE_SHIFT;
2854 gfn_t base_gfn = gfn;
2855
2856 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
2857 return RET_PF_RETRY;
2858
2859 level = kvm_mmu_hugepage_adjust(vcpu, gfn, max_level, &pfn,
2860 huge_page_disallowed, &req_level);
2861
2862 trace_kvm_mmu_spte_requested(gpa, level, pfn);
2863 for_each_shadow_entry(vcpu, gpa, it) {
2864 /*
2865 * We cannot overwrite existing page tables with an NX
2866 * large page, as the leaf could be executable.
2867 */
2868 if (nx_huge_page_workaround_enabled)
2869 disallowed_hugepage_adjust(it, gfn, &pfn, &level);
2870
2871 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
2872 if (it.level == level)
2873 break;
2874
2875 drop_large_spte(vcpu, it.sptep);
2876 if (!is_shadow_present_pte(*it.sptep)) {
2877 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
2878 it.level - 1, true, ACC_ALL);
2879
2880 link_shadow_page(vcpu, it.sptep, sp);
2881 if (is_tdp && huge_page_disallowed &&
2882 req_level >= it.level)
2883 account_huge_nx_page(vcpu->kvm, sp);
2884 }
2885 }
2886
2887 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
2888 write, level, base_gfn, pfn, prefault,
2889 map_writable);
2890 if (ret == RET_PF_SPURIOUS)
2891 return ret;
2892
2893 direct_pte_prefetch(vcpu, it.sptep);
2894 ++vcpu->stat.pf_fixed;
2895 return ret;
2896 }
2897
2898 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
2899 {
2900 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
2901 }
2902
2903 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
2904 {
2905 /*
2906 * Do not cache the mmio info caused by writing the readonly gfn
2907 * into the spte otherwise read access on readonly gfn also can
2908 * caused mmio page fault and treat it as mmio access.
2909 */
2910 if (pfn == KVM_PFN_ERR_RO_FAULT)
2911 return RET_PF_EMULATE;
2912
2913 if (pfn == KVM_PFN_ERR_HWPOISON) {
2914 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
2915 return RET_PF_RETRY;
2916 }
2917
2918 return -EFAULT;
2919 }
2920
2921 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
2922 kvm_pfn_t pfn, unsigned int access,
2923 int *ret_val)
2924 {
2925 /* The pfn is invalid, report the error! */
2926 if (unlikely(is_error_pfn(pfn))) {
2927 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
2928 return true;
2929 }
2930
2931 if (unlikely(is_noslot_pfn(pfn)))
2932 vcpu_cache_mmio_info(vcpu, gva, gfn,
2933 access & shadow_mmio_access_mask);
2934
2935 return false;
2936 }
2937
2938 static bool page_fault_can_be_fast(u32 error_code)
2939 {
2940 /*
2941 * Do not fix the mmio spte with invalid generation number which
2942 * need to be updated by slow page fault path.
2943 */
2944 if (unlikely(error_code & PFERR_RSVD_MASK))
2945 return false;
2946
2947 /* See if the page fault is due to an NX violation */
2948 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
2949 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
2950 return false;
2951
2952 /*
2953 * #PF can be fast if:
2954 * 1. The shadow page table entry is not present, which could mean that
2955 * the fault is potentially caused by access tracking (if enabled).
2956 * 2. The shadow page table entry is present and the fault
2957 * is caused by write-protect, that means we just need change the W
2958 * bit of the spte which can be done out of mmu-lock.
2959 *
2960 * However, if access tracking is disabled we know that a non-present
2961 * page must be a genuine page fault where we have to create a new SPTE.
2962 * So, if access tracking is disabled, we return true only for write
2963 * accesses to a present page.
2964 */
2965
2966 return shadow_acc_track_mask != 0 ||
2967 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
2968 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
2969 }
2970
2971 /*
2972 * Returns true if the SPTE was fixed successfully. Otherwise,
2973 * someone else modified the SPTE from its original value.
2974 */
2975 static bool
2976 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2977 u64 *sptep, u64 old_spte, u64 new_spte)
2978 {
2979 gfn_t gfn;
2980
2981 WARN_ON(!sp->role.direct);
2982
2983 /*
2984 * Theoretically we could also set dirty bit (and flush TLB) here in
2985 * order to eliminate unnecessary PML logging. See comments in
2986 * set_spte. But fast_page_fault is very unlikely to happen with PML
2987 * enabled, so we do not do this. This might result in the same GPA
2988 * to be logged in PML buffer again when the write really happens, and
2989 * eventually to be called by mark_page_dirty twice. But it's also no
2990 * harm. This also avoids the TLB flush needed after setting dirty bit
2991 * so non-PML cases won't be impacted.
2992 *
2993 * Compare with set_spte where instead shadow_dirty_mask is set.
2994 */
2995 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
2996 return false;
2997
2998 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
2999 /*
3000 * The gfn of direct spte is stable since it is
3001 * calculated by sp->gfn.
3002 */
3003 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3004 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3005 }
3006
3007 return true;
3008 }
3009
3010 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3011 {
3012 if (fault_err_code & PFERR_FETCH_MASK)
3013 return is_executable_pte(spte);
3014
3015 if (fault_err_code & PFERR_WRITE_MASK)
3016 return is_writable_pte(spte);
3017
3018 /* Fault was on Read access */
3019 return spte & PT_PRESENT_MASK;
3020 }
3021
3022 /*
3023 * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3024 */
3025 static int fast_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
3026 u32 error_code)
3027 {
3028 struct kvm_shadow_walk_iterator iterator;
3029 struct kvm_mmu_page *sp;
3030 int ret = RET_PF_INVALID;
3031 u64 spte = 0ull;
3032 uint retry_count = 0;
3033
3034 if (!page_fault_can_be_fast(error_code))
3035 return ret;
3036
3037 walk_shadow_page_lockless_begin(vcpu);
3038
3039 do {
3040 u64 new_spte;
3041
3042 for_each_shadow_entry_lockless(vcpu, cr2_or_gpa, iterator, spte)
3043 if (!is_shadow_present_pte(spte))
3044 break;
3045
3046 sp = sptep_to_sp(iterator.sptep);
3047 if (!is_last_spte(spte, sp->role.level))
3048 break;
3049
3050 /*
3051 * Check whether the memory access that caused the fault would
3052 * still cause it if it were to be performed right now. If not,
3053 * then this is a spurious fault caused by TLB lazily flushed,
3054 * or some other CPU has already fixed the PTE after the
3055 * current CPU took the fault.
3056 *
3057 * Need not check the access of upper level table entries since
3058 * they are always ACC_ALL.
3059 */
3060 if (is_access_allowed(error_code, spte)) {
3061 ret = RET_PF_SPURIOUS;
3062 break;
3063 }
3064
3065 new_spte = spte;
3066
3067 if (is_access_track_spte(spte))
3068 new_spte = restore_acc_track_spte(new_spte);
3069
3070 /*
3071 * Currently, to simplify the code, write-protection can
3072 * be removed in the fast path only if the SPTE was
3073 * write-protected for dirty-logging or access tracking.
3074 */
3075 if ((error_code & PFERR_WRITE_MASK) &&
3076 spte_can_locklessly_be_made_writable(spte)) {
3077 new_spte |= PT_WRITABLE_MASK;
3078
3079 /*
3080 * Do not fix write-permission on the large spte. Since
3081 * we only dirty the first page into the dirty-bitmap in
3082 * fast_pf_fix_direct_spte(), other pages are missed
3083 * if its slot has dirty logging enabled.
3084 *
3085 * Instead, we let the slow page fault path create a
3086 * normal spte to fix the access.
3087 *
3088 * See the comments in kvm_arch_commit_memory_region().
3089 */
3090 if (sp->role.level > PG_LEVEL_4K)
3091 break;
3092 }
3093
3094 /* Verify that the fault can be handled in the fast path */
3095 if (new_spte == spte ||
3096 !is_access_allowed(error_code, new_spte))
3097 break;
3098
3099 /*
3100 * Currently, fast page fault only works for direct mapping
3101 * since the gfn is not stable for indirect shadow page. See
3102 * Documentation/virt/kvm/locking.rst to get more detail.
3103 */
3104 if (fast_pf_fix_direct_spte(vcpu, sp, iterator.sptep, spte,
3105 new_spte)) {
3106 ret = RET_PF_FIXED;
3107 break;
3108 }
3109
3110 if (++retry_count > 4) {
3111 printk_once(KERN_WARNING
3112 "kvm: Fast #PF retrying more than 4 times.\n");
3113 break;
3114 }
3115
3116 } while (true);
3117
3118 trace_fast_page_fault(vcpu, cr2_or_gpa, error_code, iterator.sptep,
3119 spte, ret);
3120 walk_shadow_page_lockless_end(vcpu);
3121
3122 return ret;
3123 }
3124
3125 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3126 struct list_head *invalid_list)
3127 {
3128 struct kvm_mmu_page *sp;
3129
3130 if (!VALID_PAGE(*root_hpa))
3131 return;
3132
3133 sp = to_shadow_page(*root_hpa & PT64_BASE_ADDR_MASK);
3134 --sp->root_count;
3135 if (!sp->root_count && sp->role.invalid)
3136 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3137
3138 *root_hpa = INVALID_PAGE;
3139 }
3140
3141 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3142 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3143 ulong roots_to_free)
3144 {
3145 struct kvm *kvm = vcpu->kvm;
3146 int i;
3147 LIST_HEAD(invalid_list);
3148 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3149
3150 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3151
3152 /* Before acquiring the MMU lock, see if we need to do any real work. */
3153 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3154 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3155 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3156 VALID_PAGE(mmu->prev_roots[i].hpa))
3157 break;
3158
3159 if (i == KVM_MMU_NUM_PREV_ROOTS)
3160 return;
3161 }
3162
3163 spin_lock(&kvm->mmu_lock);
3164
3165 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3166 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3167 mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3168 &invalid_list);
3169
3170 if (free_active_root) {
3171 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3172 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3173 mmu_free_root_page(kvm, &mmu->root_hpa, &invalid_list);
3174 } else {
3175 for (i = 0; i < 4; ++i)
3176 if (mmu->pae_root[i] != 0)
3177 mmu_free_root_page(kvm,
3178 &mmu->pae_root[i],
3179 &invalid_list);
3180 mmu->root_hpa = INVALID_PAGE;
3181 }
3182 mmu->root_pgd = 0;
3183 }
3184
3185 kvm_mmu_commit_zap_page(kvm, &invalid_list);
3186 spin_unlock(&kvm->mmu_lock);
3187 }
3188 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3189
3190 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3191 {
3192 int ret = 0;
3193
3194 if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3195 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3196 ret = 1;
3197 }
3198
3199 return ret;
3200 }
3201
3202 static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
3203 u8 level, bool direct)
3204 {
3205 struct kvm_mmu_page *sp;
3206
3207 spin_lock(&vcpu->kvm->mmu_lock);
3208
3209 if (make_mmu_pages_available(vcpu)) {
3210 spin_unlock(&vcpu->kvm->mmu_lock);
3211 return INVALID_PAGE;
3212 }
3213 sp = kvm_mmu_get_page(vcpu, gfn, gva, level, direct, ACC_ALL);
3214 ++sp->root_count;
3215
3216 spin_unlock(&vcpu->kvm->mmu_lock);
3217 return __pa(sp->spt);
3218 }
3219
3220 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3221 {
3222 u8 shadow_root_level = vcpu->arch.mmu->shadow_root_level;
3223 hpa_t root;
3224 unsigned i;
3225
3226 if (shadow_root_level >= PT64_ROOT_4LEVEL) {
3227 root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level, true);
3228 if (!VALID_PAGE(root))
3229 return -ENOSPC;
3230 vcpu->arch.mmu->root_hpa = root;
3231 } else if (shadow_root_level == PT32E_ROOT_LEVEL) {
3232 for (i = 0; i < 4; ++i) {
3233 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->pae_root[i]));
3234
3235 root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT),
3236 i << 30, PT32_ROOT_LEVEL, true);
3237 if (!VALID_PAGE(root))
3238 return -ENOSPC;
3239 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3240 }
3241 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3242 } else
3243 BUG();
3244
3245 /* root_pgd is ignored for direct MMUs. */
3246 vcpu->arch.mmu->root_pgd = 0;
3247
3248 return 0;
3249 }
3250
3251 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3252 {
3253 u64 pdptr, pm_mask;
3254 gfn_t root_gfn, root_pgd;
3255 hpa_t root;
3256 int i;
3257
3258 root_pgd = vcpu->arch.mmu->get_guest_pgd(vcpu);
3259 root_gfn = root_pgd >> PAGE_SHIFT;
3260
3261 if (mmu_check_root(vcpu, root_gfn))
3262 return 1;
3263
3264 /*
3265 * Do we shadow a long mode page table? If so we need to
3266 * write-protect the guests page table root.
3267 */
3268 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3269 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->root_hpa));
3270
3271 root = mmu_alloc_root(vcpu, root_gfn, 0,
3272 vcpu->arch.mmu->shadow_root_level, false);
3273 if (!VALID_PAGE(root))
3274 return -ENOSPC;
3275 vcpu->arch.mmu->root_hpa = root;
3276 goto set_root_pgd;
3277 }
3278
3279 /*
3280 * We shadow a 32 bit page table. This may be a legacy 2-level
3281 * or a PAE 3-level page table. In either case we need to be aware that
3282 * the shadow page table may be a PAE or a long mode page table.
3283 */
3284 pm_mask = PT_PRESENT_MASK;
3285 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3286 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3287
3288 for (i = 0; i < 4; ++i) {
3289 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->pae_root[i]));
3290 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3291 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3292 if (!(pdptr & PT_PRESENT_MASK)) {
3293 vcpu->arch.mmu->pae_root[i] = 0;
3294 continue;
3295 }
3296 root_gfn = pdptr >> PAGE_SHIFT;
3297 if (mmu_check_root(vcpu, root_gfn))
3298 return 1;
3299 }
3300
3301 root = mmu_alloc_root(vcpu, root_gfn, i << 30,
3302 PT32_ROOT_LEVEL, false);
3303 if (!VALID_PAGE(root))
3304 return -ENOSPC;
3305 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3306 }
3307 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3308
3309 /*
3310 * If we shadow a 32 bit page table with a long mode page
3311 * table we enter this path.
3312 */
3313 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3314 if (vcpu->arch.mmu->lm_root == NULL) {
3315 /*
3316 * The additional page necessary for this is only
3317 * allocated on demand.
3318 */
3319
3320 u64 *lm_root;
3321
3322 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3323 if (lm_root == NULL)
3324 return 1;
3325
3326 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3327
3328 vcpu->arch.mmu->lm_root = lm_root;
3329 }
3330
3331 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3332 }
3333
3334 set_root_pgd:
3335 vcpu->arch.mmu->root_pgd = root_pgd;
3336
3337 return 0;
3338 }
3339
3340 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3341 {
3342 if (vcpu->arch.mmu->direct_map)
3343 return mmu_alloc_direct_roots(vcpu);
3344 else
3345 return mmu_alloc_shadow_roots(vcpu);
3346 }
3347
3348 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3349 {
3350 int i;
3351 struct kvm_mmu_page *sp;
3352
3353 if (vcpu->arch.mmu->direct_map)
3354 return;
3355
3356 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3357 return;
3358
3359 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3360
3361 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3362 hpa_t root = vcpu->arch.mmu->root_hpa;
3363 sp = to_shadow_page(root);
3364
3365 /*
3366 * Even if another CPU was marking the SP as unsync-ed
3367 * simultaneously, any guest page table changes are not
3368 * guaranteed to be visible anyway until this VCPU issues a TLB
3369 * flush strictly after those changes are made. We only need to
3370 * ensure that the other CPU sets these flags before any actual
3371 * changes to the page tables are made. The comments in
3372 * mmu_need_write_protect() describe what could go wrong if this
3373 * requirement isn't satisfied.
3374 */
3375 if (!smp_load_acquire(&sp->unsync) &&
3376 !smp_load_acquire(&sp->unsync_children))
3377 return;
3378
3379 spin_lock(&vcpu->kvm->mmu_lock);
3380 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3381
3382 mmu_sync_children(vcpu, sp);
3383
3384 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3385 spin_unlock(&vcpu->kvm->mmu_lock);
3386 return;
3387 }
3388
3389 spin_lock(&vcpu->kvm->mmu_lock);
3390 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3391
3392 for (i = 0; i < 4; ++i) {
3393 hpa_t root = vcpu->arch.mmu->pae_root[i];
3394
3395 if (root && VALID_PAGE(root)) {
3396 root &= PT64_BASE_ADDR_MASK;
3397 sp = to_shadow_page(root);
3398 mmu_sync_children(vcpu, sp);
3399 }
3400 }
3401
3402 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3403 spin_unlock(&vcpu->kvm->mmu_lock);
3404 }
3405 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3406
3407 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
3408 u32 access, struct x86_exception *exception)
3409 {
3410 if (exception)
3411 exception->error_code = 0;
3412 return vaddr;
3413 }
3414
3415 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
3416 u32 access,
3417 struct x86_exception *exception)
3418 {
3419 if (exception)
3420 exception->error_code = 0;
3421 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3422 }
3423
3424 static bool
3425 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3426 {
3427 int bit7 = (pte >> 7) & 1;
3428
3429 return pte & rsvd_check->rsvd_bits_mask[bit7][level-1];
3430 }
3431
3432 static bool __is_bad_mt_xwr(struct rsvd_bits_validate *rsvd_check, u64 pte)
3433 {
3434 return rsvd_check->bad_mt_xwr & BIT_ULL(pte & 0x3f);
3435 }
3436
3437 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3438 {
3439 /*
3440 * A nested guest cannot use the MMIO cache if it is using nested
3441 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3442 */
3443 if (mmu_is_nested(vcpu))
3444 return false;
3445
3446 if (direct)
3447 return vcpu_match_mmio_gpa(vcpu, addr);
3448
3449 return vcpu_match_mmio_gva(vcpu, addr);
3450 }
3451
3452 /* return true if reserved bit is detected on spte. */
3453 static bool
3454 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3455 {
3456 struct kvm_shadow_walk_iterator iterator;
3457 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3458 struct rsvd_bits_validate *rsvd_check;
3459 int root, leaf;
3460 bool reserved = false;
3461
3462 rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
3463
3464 walk_shadow_page_lockless_begin(vcpu);
3465
3466 for (shadow_walk_init(&iterator, vcpu, addr),
3467 leaf = root = iterator.level;
3468 shadow_walk_okay(&iterator);
3469 __shadow_walk_next(&iterator, spte)) {
3470 spte = mmu_spte_get_lockless(iterator.sptep);
3471
3472 sptes[leaf - 1] = spte;
3473 leaf--;
3474
3475 if (!is_shadow_present_pte(spte))
3476 break;
3477
3478 /*
3479 * Use a bitwise-OR instead of a logical-OR to aggregate the
3480 * reserved bit and EPT's invalid memtype/XWR checks to avoid
3481 * adding a Jcc in the loop.
3482 */
3483 reserved |= __is_bad_mt_xwr(rsvd_check, spte) |
3484 __is_rsvd_bits_set(rsvd_check, spte, iterator.level);
3485 }
3486
3487 walk_shadow_page_lockless_end(vcpu);
3488
3489 if (reserved) {
3490 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3491 __func__, addr);
3492 while (root > leaf) {
3493 pr_err("------ spte 0x%llx level %d.\n",
3494 sptes[root - 1], root);
3495 root--;
3496 }
3497 }
3498
3499 *sptep = spte;
3500 return reserved;
3501 }
3502
3503 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3504 {
3505 u64 spte;
3506 bool reserved;
3507
3508 if (mmio_info_in_cache(vcpu, addr, direct))
3509 return RET_PF_EMULATE;
3510
3511 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3512 if (WARN_ON(reserved))
3513 return -EINVAL;
3514
3515 if (is_mmio_spte(spte)) {
3516 gfn_t gfn = get_mmio_spte_gfn(spte);
3517 unsigned int access = get_mmio_spte_access(spte);
3518
3519 if (!check_mmio_spte(vcpu, spte))
3520 return RET_PF_INVALID;
3521
3522 if (direct)
3523 addr = 0;
3524
3525 trace_handle_mmio_page_fault(addr, gfn, access);
3526 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3527 return RET_PF_EMULATE;
3528 }
3529
3530 /*
3531 * If the page table is zapped by other cpus, let CPU fault again on
3532 * the address.
3533 */
3534 return RET_PF_RETRY;
3535 }
3536
3537 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3538 u32 error_code, gfn_t gfn)
3539 {
3540 if (unlikely(error_code & PFERR_RSVD_MASK))
3541 return false;
3542
3543 if (!(error_code & PFERR_PRESENT_MASK) ||
3544 !(error_code & PFERR_WRITE_MASK))
3545 return false;
3546
3547 /*
3548 * guest is writing the page which is write tracked which can
3549 * not be fixed by page fault handler.
3550 */
3551 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
3552 return true;
3553
3554 return false;
3555 }
3556
3557 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3558 {
3559 struct kvm_shadow_walk_iterator iterator;
3560 u64 spte;
3561
3562 walk_shadow_page_lockless_begin(vcpu);
3563 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
3564 clear_sp_write_flooding_count(iterator.sptep);
3565 if (!is_shadow_present_pte(spte))
3566 break;
3567 }
3568 walk_shadow_page_lockless_end(vcpu);
3569 }
3570
3571 static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
3572 gfn_t gfn)
3573 {
3574 struct kvm_arch_async_pf arch;
3575
3576 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
3577 arch.gfn = gfn;
3578 arch.direct_map = vcpu->arch.mmu->direct_map;
3579 arch.cr3 = vcpu->arch.mmu->get_guest_pgd(vcpu);
3580
3581 return kvm_setup_async_pf(vcpu, cr2_or_gpa,
3582 kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
3583 }
3584
3585 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3586 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
3587 bool *writable)
3588 {
3589 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3590 bool async;
3591
3592 /* Don't expose private memslots to L2. */
3593 if (is_guest_mode(vcpu) && !kvm_is_visible_memslot(slot)) {
3594 *pfn = KVM_PFN_NOSLOT;
3595 *writable = false;
3596 return false;
3597 }
3598
3599 async = false;
3600 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
3601 if (!async)
3602 return false; /* *pfn has correct page already */
3603
3604 if (!prefault && kvm_can_do_async_pf(vcpu)) {
3605 trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
3606 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
3607 trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
3608 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
3609 return true;
3610 } else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
3611 return true;
3612 }
3613
3614 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
3615 return false;
3616 }
3617
3618 static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
3619 bool prefault, int max_level, bool is_tdp)
3620 {
3621 bool write = error_code & PFERR_WRITE_MASK;
3622 bool map_writable;
3623
3624 gfn_t gfn = gpa >> PAGE_SHIFT;
3625 unsigned long mmu_seq;
3626 kvm_pfn_t pfn;
3627 int r;
3628
3629 if (page_fault_handle_page_track(vcpu, error_code, gfn))
3630 return RET_PF_EMULATE;
3631
3632 r = fast_page_fault(vcpu, gpa, error_code);
3633 if (r != RET_PF_INVALID)
3634 return r;
3635
3636 r = mmu_topup_memory_caches(vcpu, false);
3637 if (r)
3638 return r;
3639
3640 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3641 smp_rmb();
3642
3643 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
3644 return RET_PF_RETRY;
3645
3646 if (handle_abnormal_pfn(vcpu, is_tdp ? 0 : gpa, gfn, pfn, ACC_ALL, &r))
3647 return r;
3648
3649 r = RET_PF_RETRY;
3650 spin_lock(&vcpu->kvm->mmu_lock);
3651 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3652 goto out_unlock;
3653 r = make_mmu_pages_available(vcpu);
3654 if (r)
3655 goto out_unlock;
3656 r = __direct_map(vcpu, gpa, error_code, map_writable, max_level, pfn,
3657 prefault, is_tdp);
3658
3659 out_unlock:
3660 spin_unlock(&vcpu->kvm->mmu_lock);
3661 kvm_release_pfn_clean(pfn);
3662 return r;
3663 }
3664
3665 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
3666 u32 error_code, bool prefault)
3667 {
3668 pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
3669
3670 /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
3671 return direct_page_fault(vcpu, gpa & PAGE_MASK, error_code, prefault,
3672 PG_LEVEL_2M, false);
3673 }
3674
3675 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
3676 u64 fault_address, char *insn, int insn_len)
3677 {
3678 int r = 1;
3679 u32 flags = vcpu->arch.apf.host_apf_flags;
3680
3681 #ifndef CONFIG_X86_64
3682 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
3683 if (WARN_ON_ONCE(fault_address >> 32))
3684 return -EFAULT;
3685 #endif
3686
3687 vcpu->arch.l1tf_flush_l1d = true;
3688 if (!flags) {
3689 trace_kvm_page_fault(fault_address, error_code);
3690
3691 if (kvm_event_needs_reinjection(vcpu))
3692 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
3693 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
3694 insn_len);
3695 } else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
3696 vcpu->arch.apf.host_apf_flags = 0;
3697 local_irq_disable();
3698 kvm_async_pf_task_wait_schedule(fault_address);
3699 local_irq_enable();
3700 } else {
3701 WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
3702 }
3703
3704 return r;
3705 }
3706 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
3707
3708 int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
3709 bool prefault)
3710 {
3711 int max_level;
3712
3713 for (max_level = KVM_MAX_HUGEPAGE_LEVEL;
3714 max_level > PG_LEVEL_4K;
3715 max_level--) {
3716 int page_num = KVM_PAGES_PER_HPAGE(max_level);
3717 gfn_t base = (gpa >> PAGE_SHIFT) & ~(page_num - 1);
3718
3719 if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
3720 break;
3721 }
3722
3723 return direct_page_fault(vcpu, gpa, error_code, prefault,
3724 max_level, true);
3725 }
3726
3727 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
3728 struct kvm_mmu *context)
3729 {
3730 context->page_fault = nonpaging_page_fault;
3731 context->gva_to_gpa = nonpaging_gva_to_gpa;
3732 context->sync_page = nonpaging_sync_page;
3733 context->invlpg = NULL;
3734 context->update_pte = nonpaging_update_pte;
3735 context->root_level = 0;
3736 context->shadow_root_level = PT32E_ROOT_LEVEL;
3737 context->direct_map = true;
3738 context->nx = false;
3739 }
3740
3741 static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
3742 union kvm_mmu_page_role role)
3743 {
3744 return (role.direct || pgd == root->pgd) &&
3745 VALID_PAGE(root->hpa) && to_shadow_page(root->hpa) &&
3746 role.word == to_shadow_page(root->hpa)->role.word;
3747 }
3748
3749 /*
3750 * Find out if a previously cached root matching the new pgd/role is available.
3751 * The current root is also inserted into the cache.
3752 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
3753 * returned.
3754 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
3755 * false is returned. This root should now be freed by the caller.
3756 */
3757 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_pgd,
3758 union kvm_mmu_page_role new_role)
3759 {
3760 uint i;
3761 struct kvm_mmu_root_info root;
3762 struct kvm_mmu *mmu = vcpu->arch.mmu;
3763
3764 root.pgd = mmu->root_pgd;
3765 root.hpa = mmu->root_hpa;
3766
3767 if (is_root_usable(&root, new_pgd, new_role))
3768 return true;
3769
3770 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
3771 swap(root, mmu->prev_roots[i]);
3772
3773 if (is_root_usable(&root, new_pgd, new_role))
3774 break;
3775 }
3776
3777 mmu->root_hpa = root.hpa;
3778 mmu->root_pgd = root.pgd;
3779
3780 return i < KVM_MMU_NUM_PREV_ROOTS;
3781 }
3782
3783 static bool fast_pgd_switch(struct kvm_vcpu *vcpu, gpa_t new_pgd,
3784 union kvm_mmu_page_role new_role)
3785 {
3786 struct kvm_mmu *mmu = vcpu->arch.mmu;
3787
3788 /*
3789 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
3790 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
3791 * later if necessary.
3792 */
3793 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3794 mmu->root_level >= PT64_ROOT_4LEVEL)
3795 return cached_root_available(vcpu, new_pgd, new_role);
3796
3797 return false;
3798 }
3799
3800 static void __kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd,
3801 union kvm_mmu_page_role new_role,
3802 bool skip_tlb_flush, bool skip_mmu_sync)
3803 {
3804 if (!fast_pgd_switch(vcpu, new_pgd, new_role)) {
3805 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, KVM_MMU_ROOT_CURRENT);
3806 return;
3807 }
3808
3809 /*
3810 * It's possible that the cached previous root page is obsolete because
3811 * of a change in the MMU generation number. However, changing the
3812 * generation number is accompanied by KVM_REQ_MMU_RELOAD, which will
3813 * free the root set here and allocate a new one.
3814 */
3815 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
3816
3817 if (!skip_mmu_sync || force_flush_and_sync_on_reuse)
3818 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
3819 if (!skip_tlb_flush || force_flush_and_sync_on_reuse)
3820 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3821
3822 /*
3823 * The last MMIO access's GVA and GPA are cached in the VCPU. When
3824 * switching to a new CR3, that GVA->GPA mapping may no longer be
3825 * valid. So clear any cached MMIO info even when we don't need to sync
3826 * the shadow page tables.
3827 */
3828 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3829
3830 __clear_sp_write_flooding_count(to_shadow_page(vcpu->arch.mmu->root_hpa));
3831 }
3832
3833 void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd, bool skip_tlb_flush,
3834 bool skip_mmu_sync)
3835 {
3836 __kvm_mmu_new_pgd(vcpu, new_pgd, kvm_mmu_calc_root_page_role(vcpu),
3837 skip_tlb_flush, skip_mmu_sync);
3838 }
3839 EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
3840
3841 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
3842 {
3843 return kvm_read_cr3(vcpu);
3844 }
3845
3846 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
3847 unsigned int access, int *nr_present)
3848 {
3849 if (unlikely(is_mmio_spte(*sptep))) {
3850 if (gfn != get_mmio_spte_gfn(*sptep)) {
3851 mmu_spte_clear_no_track(sptep);
3852 return true;
3853 }
3854
3855 (*nr_present)++;
3856 mark_mmio_spte(vcpu, sptep, gfn, access);
3857 return true;
3858 }
3859
3860 return false;
3861 }
3862
3863 static inline bool is_last_gpte(struct kvm_mmu *mmu,
3864 unsigned level, unsigned gpte)
3865 {
3866 /*
3867 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
3868 * If it is clear, there are no large pages at this level, so clear
3869 * PT_PAGE_SIZE_MASK in gpte if that is the case.
3870 */
3871 gpte &= level - mmu->last_nonleaf_level;
3872
3873 /*
3874 * PG_LEVEL_4K always terminates. The RHS has bit 7 set
3875 * iff level <= PG_LEVEL_4K, which for our purpose means
3876 * level == PG_LEVEL_4K; set PT_PAGE_SIZE_MASK in gpte then.
3877 */
3878 gpte |= level - PG_LEVEL_4K - 1;
3879
3880 return gpte & PT_PAGE_SIZE_MASK;
3881 }
3882
3883 #define PTTYPE_EPT 18 /* arbitrary */
3884 #define PTTYPE PTTYPE_EPT
3885 #include "paging_tmpl.h"
3886 #undef PTTYPE
3887
3888 #define PTTYPE 64
3889 #include "paging_tmpl.h"
3890 #undef PTTYPE
3891
3892 #define PTTYPE 32
3893 #include "paging_tmpl.h"
3894 #undef PTTYPE
3895
3896 static void
3897 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
3898 struct rsvd_bits_validate *rsvd_check,
3899 int maxphyaddr, int level, bool nx, bool gbpages,
3900 bool pse, bool amd)
3901 {
3902 u64 exb_bit_rsvd = 0;
3903 u64 gbpages_bit_rsvd = 0;
3904 u64 nonleaf_bit8_rsvd = 0;
3905
3906 rsvd_check->bad_mt_xwr = 0;
3907
3908 if (!nx)
3909 exb_bit_rsvd = rsvd_bits(63, 63);
3910 if (!gbpages)
3911 gbpages_bit_rsvd = rsvd_bits(7, 7);
3912
3913 /*
3914 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
3915 * leaf entries) on AMD CPUs only.
3916 */
3917 if (amd)
3918 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
3919
3920 switch (level) {
3921 case PT32_ROOT_LEVEL:
3922 /* no rsvd bits for 2 level 4K page table entries */
3923 rsvd_check->rsvd_bits_mask[0][1] = 0;
3924 rsvd_check->rsvd_bits_mask[0][0] = 0;
3925 rsvd_check->rsvd_bits_mask[1][0] =
3926 rsvd_check->rsvd_bits_mask[0][0];
3927
3928 if (!pse) {
3929 rsvd_check->rsvd_bits_mask[1][1] = 0;
3930 break;
3931 }
3932
3933 if (is_cpuid_PSE36())
3934 /* 36bits PSE 4MB page */
3935 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
3936 else
3937 /* 32 bits PSE 4MB page */
3938 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
3939 break;
3940 case PT32E_ROOT_LEVEL:
3941 rsvd_check->rsvd_bits_mask[0][2] =
3942 rsvd_bits(maxphyaddr, 63) |
3943 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
3944 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
3945 rsvd_bits(maxphyaddr, 62); /* PDE */
3946 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
3947 rsvd_bits(maxphyaddr, 62); /* PTE */
3948 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
3949 rsvd_bits(maxphyaddr, 62) |
3950 rsvd_bits(13, 20); /* large page */
3951 rsvd_check->rsvd_bits_mask[1][0] =
3952 rsvd_check->rsvd_bits_mask[0][0];
3953 break;
3954 case PT64_ROOT_5LEVEL:
3955 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
3956 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
3957 rsvd_bits(maxphyaddr, 51);
3958 rsvd_check->rsvd_bits_mask[1][4] =
3959 rsvd_check->rsvd_bits_mask[0][4];
3960 fallthrough;
3961 case PT64_ROOT_4LEVEL:
3962 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
3963 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
3964 rsvd_bits(maxphyaddr, 51);
3965 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
3966 gbpages_bit_rsvd |
3967 rsvd_bits(maxphyaddr, 51);
3968 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
3969 rsvd_bits(maxphyaddr, 51);
3970 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
3971 rsvd_bits(maxphyaddr, 51);
3972 rsvd_check->rsvd_bits_mask[1][3] =
3973 rsvd_check->rsvd_bits_mask[0][3];
3974 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
3975 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
3976 rsvd_bits(13, 29);
3977 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
3978 rsvd_bits(maxphyaddr, 51) |
3979 rsvd_bits(13, 20); /* large page */
3980 rsvd_check->rsvd_bits_mask[1][0] =
3981 rsvd_check->rsvd_bits_mask[0][0];
3982 break;
3983 }
3984 }
3985
3986 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
3987 struct kvm_mmu *context)
3988 {
3989 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
3990 cpuid_maxphyaddr(vcpu), context->root_level,
3991 context->nx,
3992 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
3993 is_pse(vcpu),
3994 guest_cpuid_is_amd_or_hygon(vcpu));
3995 }
3996
3997 static void
3998 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
3999 int maxphyaddr, bool execonly)
4000 {
4001 u64 bad_mt_xwr;
4002
4003 rsvd_check->rsvd_bits_mask[0][4] =
4004 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4005 rsvd_check->rsvd_bits_mask[0][3] =
4006 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4007 rsvd_check->rsvd_bits_mask[0][2] =
4008 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4009 rsvd_check->rsvd_bits_mask[0][1] =
4010 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4011 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4012
4013 /* large page */
4014 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4015 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4016 rsvd_check->rsvd_bits_mask[1][2] =
4017 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4018 rsvd_check->rsvd_bits_mask[1][1] =
4019 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4020 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4021
4022 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4023 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4024 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4025 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4026 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4027 if (!execonly) {
4028 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4029 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4030 }
4031 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4032 }
4033
4034 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4035 struct kvm_mmu *context, bool execonly)
4036 {
4037 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4038 cpuid_maxphyaddr(vcpu), execonly);
4039 }
4040
4041 /*
4042 * the page table on host is the shadow page table for the page
4043 * table in guest or amd nested guest, its mmu features completely
4044 * follow the features in guest.
4045 */
4046 void
4047 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4048 {
4049 bool uses_nx = context->nx ||
4050 context->mmu_role.base.smep_andnot_wp;
4051 struct rsvd_bits_validate *shadow_zero_check;
4052 int i;
4053
4054 /*
4055 * Passing "true" to the last argument is okay; it adds a check
4056 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4057 */
4058 shadow_zero_check = &context->shadow_zero_check;
4059 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4060 shadow_phys_bits,
4061 context->shadow_root_level, uses_nx,
4062 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4063 is_pse(vcpu), true);
4064
4065 if (!shadow_me_mask)
4066 return;
4067
4068 for (i = context->shadow_root_level; --i >= 0;) {
4069 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4070 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4071 }
4072
4073 }
4074 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4075
4076 static inline bool boot_cpu_is_amd(void)
4077 {
4078 WARN_ON_ONCE(!tdp_enabled);
4079 return shadow_x_mask == 0;
4080 }
4081
4082 /*
4083 * the direct page table on host, use as much mmu features as
4084 * possible, however, kvm currently does not do execution-protection.
4085 */
4086 static void
4087 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4088 struct kvm_mmu *context)
4089 {
4090 struct rsvd_bits_validate *shadow_zero_check;
4091 int i;
4092
4093 shadow_zero_check = &context->shadow_zero_check;
4094
4095 if (boot_cpu_is_amd())
4096 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4097 shadow_phys_bits,
4098 context->shadow_root_level, false,
4099 boot_cpu_has(X86_FEATURE_GBPAGES),
4100 true, true);
4101 else
4102 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4103 shadow_phys_bits,
4104 false);
4105
4106 if (!shadow_me_mask)
4107 return;
4108
4109 for (i = context->shadow_root_level; --i >= 0;) {
4110 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4111 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4112 }
4113 }
4114
4115 /*
4116 * as the comments in reset_shadow_zero_bits_mask() except it
4117 * is the shadow page table for intel nested guest.
4118 */
4119 static void
4120 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4121 struct kvm_mmu *context, bool execonly)
4122 {
4123 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4124 shadow_phys_bits, execonly);
4125 }
4126
4127 #define BYTE_MASK(access) \
4128 ((1 & (access) ? 2 : 0) | \
4129 (2 & (access) ? 4 : 0) | \
4130 (3 & (access) ? 8 : 0) | \
4131 (4 & (access) ? 16 : 0) | \
4132 (5 & (access) ? 32 : 0) | \
4133 (6 & (access) ? 64 : 0) | \
4134 (7 & (access) ? 128 : 0))
4135
4136
4137 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4138 struct kvm_mmu *mmu, bool ept)
4139 {
4140 unsigned byte;
4141
4142 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4143 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4144 const u8 u = BYTE_MASK(ACC_USER_MASK);
4145
4146 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4147 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4148 bool cr0_wp = is_write_protection(vcpu);
4149
4150 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4151 unsigned pfec = byte << 1;
4152
4153 /*
4154 * Each "*f" variable has a 1 bit for each UWX value
4155 * that causes a fault with the given PFEC.
4156 */
4157
4158 /* Faults from writes to non-writable pages */
4159 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4160 /* Faults from user mode accesses to supervisor pages */
4161 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4162 /* Faults from fetches of non-executable pages*/
4163 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4164 /* Faults from kernel mode fetches of user pages */
4165 u8 smepf = 0;
4166 /* Faults from kernel mode accesses of user pages */
4167 u8 smapf = 0;
4168
4169 if (!ept) {
4170 /* Faults from kernel mode accesses to user pages */
4171 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4172
4173 /* Not really needed: !nx will cause pte.nx to fault */
4174 if (!mmu->nx)
4175 ff = 0;
4176
4177 /* Allow supervisor writes if !cr0.wp */
4178 if (!cr0_wp)
4179 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4180
4181 /* Disallow supervisor fetches of user code if cr4.smep */
4182 if (cr4_smep)
4183 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4184
4185 /*
4186 * SMAP:kernel-mode data accesses from user-mode
4187 * mappings should fault. A fault is considered
4188 * as a SMAP violation if all of the following
4189 * conditions are true:
4190 * - X86_CR4_SMAP is set in CR4
4191 * - A user page is accessed
4192 * - The access is not a fetch
4193 * - Page fault in kernel mode
4194 * - if CPL = 3 or X86_EFLAGS_AC is clear
4195 *
4196 * Here, we cover the first three conditions.
4197 * The fourth is computed dynamically in permission_fault();
4198 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4199 * *not* subject to SMAP restrictions.
4200 */
4201 if (cr4_smap)
4202 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4203 }
4204
4205 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4206 }
4207 }
4208
4209 /*
4210 * PKU is an additional mechanism by which the paging controls access to
4211 * user-mode addresses based on the value in the PKRU register. Protection
4212 * key violations are reported through a bit in the page fault error code.
4213 * Unlike other bits of the error code, the PK bit is not known at the
4214 * call site of e.g. gva_to_gpa; it must be computed directly in
4215 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4216 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4217 *
4218 * In particular the following conditions come from the error code, the
4219 * page tables and the machine state:
4220 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4221 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4222 * - PK is always zero if U=0 in the page tables
4223 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4224 *
4225 * The PKRU bitmask caches the result of these four conditions. The error
4226 * code (minus the P bit) and the page table's U bit form an index into the
4227 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4228 * with the two bits of the PKRU register corresponding to the protection key.
4229 * For the first three conditions above the bits will be 00, thus masking
4230 * away both AD and WD. For all reads or if the last condition holds, WD
4231 * only will be masked away.
4232 */
4233 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4234 bool ept)
4235 {
4236 unsigned bit;
4237 bool wp;
4238
4239 if (ept) {
4240 mmu->pkru_mask = 0;
4241 return;
4242 }
4243
4244 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4245 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4246 mmu->pkru_mask = 0;
4247 return;
4248 }
4249
4250 wp = is_write_protection(vcpu);
4251
4252 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4253 unsigned pfec, pkey_bits;
4254 bool check_pkey, check_write, ff, uf, wf, pte_user;
4255
4256 pfec = bit << 1;
4257 ff = pfec & PFERR_FETCH_MASK;
4258 uf = pfec & PFERR_USER_MASK;
4259 wf = pfec & PFERR_WRITE_MASK;
4260
4261 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4262 pte_user = pfec & PFERR_RSVD_MASK;
4263
4264 /*
4265 * Only need to check the access which is not an
4266 * instruction fetch and is to a user page.
4267 */
4268 check_pkey = (!ff && pte_user);
4269 /*
4270 * write access is controlled by PKRU if it is a
4271 * user access or CR0.WP = 1.
4272 */
4273 check_write = check_pkey && wf && (uf || wp);
4274
4275 /* PKRU.AD stops both read and write access. */
4276 pkey_bits = !!check_pkey;
4277 /* PKRU.WD stops write access. */
4278 pkey_bits |= (!!check_write) << 1;
4279
4280 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4281 }
4282 }
4283
4284 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4285 {
4286 unsigned root_level = mmu->root_level;
4287
4288 mmu->last_nonleaf_level = root_level;
4289 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4290 mmu->last_nonleaf_level++;
4291 }
4292
4293 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4294 struct kvm_mmu *context,
4295 int level)
4296 {
4297 context->nx = is_nx(vcpu);
4298 context->root_level = level;
4299
4300 reset_rsvds_bits_mask(vcpu, context);
4301 update_permission_bitmask(vcpu, context, false);
4302 update_pkru_bitmask(vcpu, context, false);
4303 update_last_nonleaf_level(vcpu, context);
4304
4305 MMU_WARN_ON(!is_pae(vcpu));
4306 context->page_fault = paging64_page_fault;
4307 context->gva_to_gpa = paging64_gva_to_gpa;
4308 context->sync_page = paging64_sync_page;
4309 context->invlpg = paging64_invlpg;
4310 context->update_pte = paging64_update_pte;
4311 context->shadow_root_level = level;
4312 context->direct_map = false;
4313 }
4314
4315 static void paging64_init_context(struct kvm_vcpu *vcpu,
4316 struct kvm_mmu *context)
4317 {
4318 int root_level = is_la57_mode(vcpu) ?
4319 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4320
4321 paging64_init_context_common(vcpu, context, root_level);
4322 }
4323
4324 static void paging32_init_context(struct kvm_vcpu *vcpu,
4325 struct kvm_mmu *context)
4326 {
4327 context->nx = false;
4328 context->root_level = PT32_ROOT_LEVEL;
4329
4330 reset_rsvds_bits_mask(vcpu, context);
4331 update_permission_bitmask(vcpu, context, false);
4332 update_pkru_bitmask(vcpu, context, false);
4333 update_last_nonleaf_level(vcpu, context);
4334
4335 context->page_fault = paging32_page_fault;
4336 context->gva_to_gpa = paging32_gva_to_gpa;
4337 context->sync_page = paging32_sync_page;
4338 context->invlpg = paging32_invlpg;
4339 context->update_pte = paging32_update_pte;
4340 context->shadow_root_level = PT32E_ROOT_LEVEL;
4341 context->direct_map = false;
4342 }
4343
4344 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4345 struct kvm_mmu *context)
4346 {
4347 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4348 }
4349
4350 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4351 {
4352 union kvm_mmu_extended_role ext = {0};
4353
4354 ext.cr0_pg = !!is_paging(vcpu);
4355 ext.cr4_pae = !!is_pae(vcpu);
4356 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4357 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4358 ext.cr4_pse = !!is_pse(vcpu);
4359 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4360 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4361
4362 ext.valid = 1;
4363
4364 return ext;
4365 }
4366
4367 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4368 bool base_only)
4369 {
4370 union kvm_mmu_role role = {0};
4371
4372 role.base.access = ACC_ALL;
4373 role.base.nxe = !!is_nx(vcpu);
4374 role.base.cr0_wp = is_write_protection(vcpu);
4375 role.base.smm = is_smm(vcpu);
4376 role.base.guest_mode = is_guest_mode(vcpu);
4377
4378 if (base_only)
4379 return role;
4380
4381 role.ext = kvm_calc_mmu_role_ext(vcpu);
4382
4383 return role;
4384 }
4385
4386 static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
4387 {
4388 /* Use 5-level TDP if and only if it's useful/necessary. */
4389 if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
4390 return 4;
4391
4392 return max_tdp_level;
4393 }
4394
4395 static union kvm_mmu_role
4396 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4397 {
4398 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4399
4400 role.base.ad_disabled = (shadow_accessed_mask == 0);
4401 role.base.level = kvm_mmu_get_tdp_level(vcpu);
4402 role.base.direct = true;
4403 role.base.gpte_is_8_bytes = true;
4404
4405 return role;
4406 }
4407
4408 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4409 {
4410 struct kvm_mmu *context = &vcpu->arch.root_mmu;
4411 union kvm_mmu_role new_role =
4412 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4413
4414 if (new_role.as_u64 == context->mmu_role.as_u64)
4415 return;
4416
4417 context->mmu_role.as_u64 = new_role.as_u64;
4418 context->page_fault = kvm_tdp_page_fault;
4419 context->sync_page = nonpaging_sync_page;
4420 context->invlpg = NULL;
4421 context->update_pte = nonpaging_update_pte;
4422 context->shadow_root_level = kvm_mmu_get_tdp_level(vcpu);
4423 context->direct_map = true;
4424 context->get_guest_pgd = get_cr3;
4425 context->get_pdptr = kvm_pdptr_read;
4426 context->inject_page_fault = kvm_inject_page_fault;
4427
4428 if (!is_paging(vcpu)) {
4429 context->nx = false;
4430 context->gva_to_gpa = nonpaging_gva_to_gpa;
4431 context->root_level = 0;
4432 } else if (is_long_mode(vcpu)) {
4433 context->nx = is_nx(vcpu);
4434 context->root_level = is_la57_mode(vcpu) ?
4435 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4436 reset_rsvds_bits_mask(vcpu, context);
4437 context->gva_to_gpa = paging64_gva_to_gpa;
4438 } else if (is_pae(vcpu)) {
4439 context->nx = is_nx(vcpu);
4440 context->root_level = PT32E_ROOT_LEVEL;
4441 reset_rsvds_bits_mask(vcpu, context);
4442 context->gva_to_gpa = paging64_gva_to_gpa;
4443 } else {
4444 context->nx = false;
4445 context->root_level = PT32_ROOT_LEVEL;
4446 reset_rsvds_bits_mask(vcpu, context);
4447 context->gva_to_gpa = paging32_gva_to_gpa;
4448 }
4449
4450 update_permission_bitmask(vcpu, context, false);
4451 update_pkru_bitmask(vcpu, context, false);
4452 update_last_nonleaf_level(vcpu, context);
4453 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4454 }
4455
4456 static union kvm_mmu_role
4457 kvm_calc_shadow_root_page_role_common(struct kvm_vcpu *vcpu, bool base_only)
4458 {
4459 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4460
4461 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4462 !is_write_protection(vcpu);
4463 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4464 !is_write_protection(vcpu);
4465 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4466
4467 return role;
4468 }
4469
4470 static union kvm_mmu_role
4471 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4472 {
4473 union kvm_mmu_role role =
4474 kvm_calc_shadow_root_page_role_common(vcpu, base_only);
4475
4476 role.base.direct = !is_paging(vcpu);
4477
4478 if (!is_long_mode(vcpu))
4479 role.base.level = PT32E_ROOT_LEVEL;
4480 else if (is_la57_mode(vcpu))
4481 role.base.level = PT64_ROOT_5LEVEL;
4482 else
4483 role.base.level = PT64_ROOT_4LEVEL;
4484
4485 return role;
4486 }
4487
4488 static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
4489 u32 cr0, u32 cr4, u32 efer,
4490 union kvm_mmu_role new_role)
4491 {
4492 if (!(cr0 & X86_CR0_PG))
4493 nonpaging_init_context(vcpu, context);
4494 else if (efer & EFER_LMA)
4495 paging64_init_context(vcpu, context);
4496 else if (cr4 & X86_CR4_PAE)
4497 paging32E_init_context(vcpu, context);
4498 else
4499 paging32_init_context(vcpu, context);
4500
4501 context->mmu_role.as_u64 = new_role.as_u64;
4502 reset_shadow_zero_bits_mask(vcpu, context);
4503 }
4504
4505 static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu, u32 cr0, u32 cr4, u32 efer)
4506 {
4507 struct kvm_mmu *context = &vcpu->arch.root_mmu;
4508 union kvm_mmu_role new_role =
4509 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4510
4511 if (new_role.as_u64 != context->mmu_role.as_u64)
4512 shadow_mmu_init_context(vcpu, context, cr0, cr4, efer, new_role);
4513 }
4514
4515 static union kvm_mmu_role
4516 kvm_calc_shadow_npt_root_page_role(struct kvm_vcpu *vcpu)
4517 {
4518 union kvm_mmu_role role =
4519 kvm_calc_shadow_root_page_role_common(vcpu, false);
4520
4521 role.base.direct = false;
4522 role.base.level = kvm_mmu_get_tdp_level(vcpu);
4523
4524 return role;
4525 }
4526
4527 void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, u32 cr0, u32 cr4, u32 efer,
4528 gpa_t nested_cr3)
4529 {
4530 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
4531 union kvm_mmu_role new_role = kvm_calc_shadow_npt_root_page_role(vcpu);
4532
4533 context->shadow_root_level = new_role.base.level;
4534
4535 __kvm_mmu_new_pgd(vcpu, nested_cr3, new_role.base, false, false);
4536
4537 if (new_role.as_u64 != context->mmu_role.as_u64)
4538 shadow_mmu_init_context(vcpu, context, cr0, cr4, efer, new_role);
4539 }
4540 EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
4541
4542 static union kvm_mmu_role
4543 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4544 bool execonly, u8 level)
4545 {
4546 union kvm_mmu_role role = {0};
4547
4548 /* SMM flag is inherited from root_mmu */
4549 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
4550
4551 role.base.level = level;
4552 role.base.gpte_is_8_bytes = true;
4553 role.base.direct = false;
4554 role.base.ad_disabled = !accessed_dirty;
4555 role.base.guest_mode = true;
4556 role.base.access = ACC_ALL;
4557
4558 /*
4559 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
4560 * SMAP variation to denote shadow EPT entries.
4561 */
4562 role.base.cr0_wp = true;
4563 role.base.smap_andnot_wp = true;
4564
4565 role.ext = kvm_calc_mmu_role_ext(vcpu);
4566 role.ext.execonly = execonly;
4567
4568 return role;
4569 }
4570
4571 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4572 bool accessed_dirty, gpa_t new_eptp)
4573 {
4574 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
4575 u8 level = vmx_eptp_page_walk_level(new_eptp);
4576 union kvm_mmu_role new_role =
4577 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
4578 execonly, level);
4579
4580 __kvm_mmu_new_pgd(vcpu, new_eptp, new_role.base, true, true);
4581
4582 if (new_role.as_u64 == context->mmu_role.as_u64)
4583 return;
4584
4585 context->shadow_root_level = level;
4586
4587 context->nx = true;
4588 context->ept_ad = accessed_dirty;
4589 context->page_fault = ept_page_fault;
4590 context->gva_to_gpa = ept_gva_to_gpa;
4591 context->sync_page = ept_sync_page;
4592 context->invlpg = ept_invlpg;
4593 context->update_pte = ept_update_pte;
4594 context->root_level = level;
4595 context->direct_map = false;
4596 context->mmu_role.as_u64 = new_role.as_u64;
4597
4598 update_permission_bitmask(vcpu, context, true);
4599 update_pkru_bitmask(vcpu, context, true);
4600 update_last_nonleaf_level(vcpu, context);
4601 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
4602 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
4603 }
4604 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4605
4606 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
4607 {
4608 struct kvm_mmu *context = &vcpu->arch.root_mmu;
4609
4610 kvm_init_shadow_mmu(vcpu,
4611 kvm_read_cr0_bits(vcpu, X86_CR0_PG),
4612 kvm_read_cr4_bits(vcpu, X86_CR4_PAE),
4613 vcpu->arch.efer);
4614
4615 context->get_guest_pgd = get_cr3;
4616 context->get_pdptr = kvm_pdptr_read;
4617 context->inject_page_fault = kvm_inject_page_fault;
4618 }
4619
4620 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
4621 {
4622 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
4623 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4624
4625 if (new_role.as_u64 == g_context->mmu_role.as_u64)
4626 return;
4627
4628 g_context->mmu_role.as_u64 = new_role.as_u64;
4629 g_context->get_guest_pgd = get_cr3;
4630 g_context->get_pdptr = kvm_pdptr_read;
4631 g_context->inject_page_fault = kvm_inject_page_fault;
4632
4633 /*
4634 * L2 page tables are never shadowed, so there is no need to sync
4635 * SPTEs.
4636 */
4637 g_context->invlpg = NULL;
4638
4639 /*
4640 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
4641 * L1's nested page tables (e.g. EPT12). The nested translation
4642 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
4643 * L2's page tables as the first level of translation and L1's
4644 * nested page tables as the second level of translation. Basically
4645 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
4646 */
4647 if (!is_paging(vcpu)) {
4648 g_context->nx = false;
4649 g_context->root_level = 0;
4650 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
4651 } else if (is_long_mode(vcpu)) {
4652 g_context->nx = is_nx(vcpu);
4653 g_context->root_level = is_la57_mode(vcpu) ?
4654 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4655 reset_rsvds_bits_mask(vcpu, g_context);
4656 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4657 } else if (is_pae(vcpu)) {
4658 g_context->nx = is_nx(vcpu);
4659 g_context->root_level = PT32E_ROOT_LEVEL;
4660 reset_rsvds_bits_mask(vcpu, g_context);
4661 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4662 } else {
4663 g_context->nx = false;
4664 g_context->root_level = PT32_ROOT_LEVEL;
4665 reset_rsvds_bits_mask(vcpu, g_context);
4666 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
4667 }
4668
4669 update_permission_bitmask(vcpu, g_context, false);
4670 update_pkru_bitmask(vcpu, g_context, false);
4671 update_last_nonleaf_level(vcpu, g_context);
4672 }
4673
4674 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
4675 {
4676 if (reset_roots) {
4677 uint i;
4678
4679 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
4680
4681 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4682 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
4683 }
4684
4685 if (mmu_is_nested(vcpu))
4686 init_kvm_nested_mmu(vcpu);
4687 else if (tdp_enabled)
4688 init_kvm_tdp_mmu(vcpu);
4689 else
4690 init_kvm_softmmu(vcpu);
4691 }
4692 EXPORT_SYMBOL_GPL(kvm_init_mmu);
4693
4694 static union kvm_mmu_page_role
4695 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
4696 {
4697 union kvm_mmu_role role;
4698
4699 if (tdp_enabled)
4700 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
4701 else
4702 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
4703
4704 return role.base;
4705 }
4706
4707 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
4708 {
4709 kvm_mmu_unload(vcpu);
4710 kvm_init_mmu(vcpu, true);
4711 }
4712 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
4713
4714 int kvm_mmu_load(struct kvm_vcpu *vcpu)
4715 {
4716 int r;
4717
4718 r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->direct_map);
4719 if (r)
4720 goto out;
4721 r = mmu_alloc_roots(vcpu);
4722 kvm_mmu_sync_roots(vcpu);
4723 if (r)
4724 goto out;
4725 kvm_mmu_load_pgd(vcpu);
4726 kvm_x86_ops.tlb_flush_current(vcpu);
4727 out:
4728 return r;
4729 }
4730 EXPORT_SYMBOL_GPL(kvm_mmu_load);
4731
4732 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
4733 {
4734 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
4735 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
4736 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
4737 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
4738 }
4739 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
4740
4741 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
4742 struct kvm_mmu_page *sp, u64 *spte,
4743 const void *new)
4744 {
4745 if (sp->role.level != PG_LEVEL_4K) {
4746 ++vcpu->kvm->stat.mmu_pde_zapped;
4747 return;
4748 }
4749
4750 ++vcpu->kvm->stat.mmu_pte_updated;
4751 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
4752 }
4753
4754 static bool need_remote_flush(u64 old, u64 new)
4755 {
4756 if (!is_shadow_present_pte(old))
4757 return false;
4758 if (!is_shadow_present_pte(new))
4759 return true;
4760 if ((old ^ new) & PT64_BASE_ADDR_MASK)
4761 return true;
4762 old ^= shadow_nx_mask;
4763 new ^= shadow_nx_mask;
4764 return (old & ~new & PT64_PERM_MASK) != 0;
4765 }
4766
4767 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
4768 int *bytes)
4769 {
4770 u64 gentry = 0;
4771 int r;
4772
4773 /*
4774 * Assume that the pte write on a page table of the same type
4775 * as the current vcpu paging mode since we update the sptes only
4776 * when they have the same mode.
4777 */
4778 if (is_pae(vcpu) && *bytes == 4) {
4779 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
4780 *gpa &= ~(gpa_t)7;
4781 *bytes = 8;
4782 }
4783
4784 if (*bytes == 4 || *bytes == 8) {
4785 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
4786 if (r)
4787 gentry = 0;
4788 }
4789
4790 return gentry;
4791 }
4792
4793 /*
4794 * If we're seeing too many writes to a page, it may no longer be a page table,
4795 * or we may be forking, in which case it is better to unmap the page.
4796 */
4797 static bool detect_write_flooding(struct kvm_mmu_page *sp)
4798 {
4799 /*
4800 * Skip write-flooding detected for the sp whose level is 1, because
4801 * it can become unsync, then the guest page is not write-protected.
4802 */
4803 if (sp->role.level == PG_LEVEL_4K)
4804 return false;
4805
4806 atomic_inc(&sp->write_flooding_count);
4807 return atomic_read(&sp->write_flooding_count) >= 3;
4808 }
4809
4810 /*
4811 * Misaligned accesses are too much trouble to fix up; also, they usually
4812 * indicate a page is not used as a page table.
4813 */
4814 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
4815 int bytes)
4816 {
4817 unsigned offset, pte_size, misaligned;
4818
4819 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
4820 gpa, bytes, sp->role.word);
4821
4822 offset = offset_in_page(gpa);
4823 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
4824
4825 /*
4826 * Sometimes, the OS only writes the last one bytes to update status
4827 * bits, for example, in linux, andb instruction is used in clear_bit().
4828 */
4829 if (!(offset & (pte_size - 1)) && bytes == 1)
4830 return false;
4831
4832 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
4833 misaligned |= bytes < 4;
4834
4835 return misaligned;
4836 }
4837
4838 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
4839 {
4840 unsigned page_offset, quadrant;
4841 u64 *spte;
4842 int level;
4843
4844 page_offset = offset_in_page(gpa);
4845 level = sp->role.level;
4846 *nspte = 1;
4847 if (!sp->role.gpte_is_8_bytes) {
4848 page_offset <<= 1; /* 32->64 */
4849 /*
4850 * A 32-bit pde maps 4MB while the shadow pdes map
4851 * only 2MB. So we need to double the offset again
4852 * and zap two pdes instead of one.
4853 */
4854 if (level == PT32_ROOT_LEVEL) {
4855 page_offset &= ~7; /* kill rounding error */
4856 page_offset <<= 1;
4857 *nspte = 2;
4858 }
4859 quadrant = page_offset >> PAGE_SHIFT;
4860 page_offset &= ~PAGE_MASK;
4861 if (quadrant != sp->role.quadrant)
4862 return NULL;
4863 }
4864
4865 spte = &sp->spt[page_offset / sizeof(*spte)];
4866 return spte;
4867 }
4868
4869 /*
4870 * Ignore various flags when determining if a SPTE can be immediately
4871 * overwritten for the current MMU.
4872 * - level: explicitly checked in mmu_pte_write_new_pte(), and will never
4873 * match the current MMU role, as MMU's level tracks the root level.
4874 * - access: updated based on the new guest PTE
4875 * - quadrant: handled by get_written_sptes()
4876 * - invalid: always false (loop only walks valid shadow pages)
4877 */
4878 static const union kvm_mmu_page_role role_ign = {
4879 .level = 0xf,
4880 .access = 0x7,
4881 .quadrant = 0x3,
4882 .invalid = 0x1,
4883 };
4884
4885 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
4886 const u8 *new, int bytes,
4887 struct kvm_page_track_notifier_node *node)
4888 {
4889 gfn_t gfn = gpa >> PAGE_SHIFT;
4890 struct kvm_mmu_page *sp;
4891 LIST_HEAD(invalid_list);
4892 u64 entry, gentry, *spte;
4893 int npte;
4894 bool remote_flush, local_flush;
4895
4896 /*
4897 * If we don't have indirect shadow pages, it means no page is
4898 * write-protected, so we can exit simply.
4899 */
4900 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
4901 return;
4902
4903 remote_flush = local_flush = false;
4904
4905 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
4906
4907 /*
4908 * No need to care whether allocation memory is successful
4909 * or not since pte prefetch is skiped if it does not have
4910 * enough objects in the cache.
4911 */
4912 mmu_topup_memory_caches(vcpu, true);
4913
4914 spin_lock(&vcpu->kvm->mmu_lock);
4915
4916 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
4917
4918 ++vcpu->kvm->stat.mmu_pte_write;
4919 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
4920
4921 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
4922 if (detect_write_misaligned(sp, gpa, bytes) ||
4923 detect_write_flooding(sp)) {
4924 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
4925 ++vcpu->kvm->stat.mmu_flooded;
4926 continue;
4927 }
4928
4929 spte = get_written_sptes(sp, gpa, &npte);
4930 if (!spte)
4931 continue;
4932
4933 local_flush = true;
4934 while (npte--) {
4935 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
4936
4937 entry = *spte;
4938 mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
4939 if (gentry &&
4940 !((sp->role.word ^ base_role) & ~role_ign.word) &&
4941 rmap_can_add(vcpu))
4942 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
4943 if (need_remote_flush(entry, *spte))
4944 remote_flush = true;
4945 ++spte;
4946 }
4947 }
4948 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
4949 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
4950 spin_unlock(&vcpu->kvm->mmu_lock);
4951 }
4952
4953 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
4954 {
4955 gpa_t gpa;
4956 int r;
4957
4958 if (vcpu->arch.mmu->direct_map)
4959 return 0;
4960
4961 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
4962
4963 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4964
4965 return r;
4966 }
4967 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
4968
4969 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
4970 void *insn, int insn_len)
4971 {
4972 int r, emulation_type = EMULTYPE_PF;
4973 bool direct = vcpu->arch.mmu->direct_map;
4974
4975 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
4976 return RET_PF_RETRY;
4977
4978 r = RET_PF_INVALID;
4979 if (unlikely(error_code & PFERR_RSVD_MASK)) {
4980 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
4981 if (r == RET_PF_EMULATE)
4982 goto emulate;
4983 }
4984
4985 if (r == RET_PF_INVALID) {
4986 r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
4987 lower_32_bits(error_code), false);
4988 if (WARN_ON_ONCE(r == RET_PF_INVALID))
4989 return -EIO;
4990 }
4991
4992 if (r < 0)
4993 return r;
4994 if (r != RET_PF_EMULATE)
4995 return 1;
4996
4997 /*
4998 * Before emulating the instruction, check if the error code
4999 * was due to a RO violation while translating the guest page.
5000 * This can occur when using nested virtualization with nested
5001 * paging in both guests. If true, we simply unprotect the page
5002 * and resume the guest.
5003 */
5004 if (vcpu->arch.mmu->direct_map &&
5005 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5006 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5007 return 1;
5008 }
5009
5010 /*
5011 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5012 * optimistically try to just unprotect the page and let the processor
5013 * re-execute the instruction that caused the page fault. Do not allow
5014 * retrying MMIO emulation, as it's not only pointless but could also
5015 * cause us to enter an infinite loop because the processor will keep
5016 * faulting on the non-existent MMIO address. Retrying an instruction
5017 * from a nested guest is also pointless and dangerous as we are only
5018 * explicitly shadowing L1's page tables, i.e. unprotecting something
5019 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5020 */
5021 if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5022 emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5023 emulate:
5024 return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5025 insn_len);
5026 }
5027 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5028
5029 void kvm_mmu_invalidate_gva(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5030 gva_t gva, hpa_t root_hpa)
5031 {
5032 int i;
5033
5034 /* It's actually a GPA for vcpu->arch.guest_mmu. */
5035 if (mmu != &vcpu->arch.guest_mmu) {
5036 /* INVLPG on a non-canonical address is a NOP according to the SDM. */
5037 if (is_noncanonical_address(gva, vcpu))
5038 return;
5039
5040 kvm_x86_ops.tlb_flush_gva(vcpu, gva);
5041 }
5042
5043 if (!mmu->invlpg)
5044 return;
5045
5046 if (root_hpa == INVALID_PAGE) {
5047 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5048
5049 /*
5050 * INVLPG is required to invalidate any global mappings for the VA,
5051 * irrespective of PCID. Since it would take us roughly similar amount
5052 * of work to determine whether any of the prev_root mappings of the VA
5053 * is marked global, or to just sync it blindly, so we might as well
5054 * just always sync it.
5055 *
5056 * Mappings not reachable via the current cr3 or the prev_roots will be
5057 * synced when switching to that cr3, so nothing needs to be done here
5058 * for them.
5059 */
5060 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5061 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5062 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5063 } else {
5064 mmu->invlpg(vcpu, gva, root_hpa);
5065 }
5066 }
5067 EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_gva);
5068
5069 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5070 {
5071 kvm_mmu_invalidate_gva(vcpu, vcpu->arch.mmu, gva, INVALID_PAGE);
5072 ++vcpu->stat.invlpg;
5073 }
5074 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5075
5076
5077 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5078 {
5079 struct kvm_mmu *mmu = vcpu->arch.mmu;
5080 bool tlb_flush = false;
5081 uint i;
5082
5083 if (pcid == kvm_get_active_pcid(vcpu)) {
5084 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5085 tlb_flush = true;
5086 }
5087
5088 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5089 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5090 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd)) {
5091 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5092 tlb_flush = true;
5093 }
5094 }
5095
5096 if (tlb_flush)
5097 kvm_x86_ops.tlb_flush_gva(vcpu, gva);
5098
5099 ++vcpu->stat.invlpg;
5100
5101 /*
5102 * Mappings not reachable via the current cr3 or the prev_roots will be
5103 * synced when switching to that cr3, so nothing needs to be done here
5104 * for them.
5105 */
5106 }
5107 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5108
5109 void kvm_configure_mmu(bool enable_tdp, int tdp_max_root_level,
5110 int tdp_huge_page_level)
5111 {
5112 tdp_enabled = enable_tdp;
5113 max_tdp_level = tdp_max_root_level;
5114
5115 /*
5116 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5117 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5118 * the kernel is not. But, KVM never creates a page size greater than
5119 * what is used by the kernel for any given HVA, i.e. the kernel's
5120 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5121 */
5122 if (tdp_enabled)
5123 max_huge_page_level = tdp_huge_page_level;
5124 else if (boot_cpu_has(X86_FEATURE_GBPAGES))
5125 max_huge_page_level = PG_LEVEL_1G;
5126 else
5127 max_huge_page_level = PG_LEVEL_2M;
5128 }
5129 EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5130
5131 /* The return value indicates if tlb flush on all vcpus is needed. */
5132 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5133
5134 /* The caller should hold mmu-lock before calling this function. */
5135 static __always_inline bool
5136 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5137 slot_level_handler fn, int start_level, int end_level,
5138 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5139 {
5140 struct slot_rmap_walk_iterator iterator;
5141 bool flush = false;
5142
5143 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5144 end_gfn, &iterator) {
5145 if (iterator.rmap)
5146 flush |= fn(kvm, iterator.rmap);
5147
5148 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5149 if (flush && lock_flush_tlb) {
5150 kvm_flush_remote_tlbs_with_address(kvm,
5151 start_gfn,
5152 iterator.gfn - start_gfn + 1);
5153 flush = false;
5154 }
5155 cond_resched_lock(&kvm->mmu_lock);
5156 }
5157 }
5158
5159 if (flush && lock_flush_tlb) {
5160 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5161 end_gfn - start_gfn + 1);
5162 flush = false;
5163 }
5164
5165 return flush;
5166 }
5167
5168 static __always_inline bool
5169 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5170 slot_level_handler fn, int start_level, int end_level,
5171 bool lock_flush_tlb)
5172 {
5173 return slot_handle_level_range(kvm, memslot, fn, start_level,
5174 end_level, memslot->base_gfn,
5175 memslot->base_gfn + memslot->npages - 1,
5176 lock_flush_tlb);
5177 }
5178
5179 static __always_inline bool
5180 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5181 slot_level_handler fn, bool lock_flush_tlb)
5182 {
5183 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5184 KVM_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5185 }
5186
5187 static __always_inline bool
5188 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5189 slot_level_handler fn, bool lock_flush_tlb)
5190 {
5191 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K + 1,
5192 KVM_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5193 }
5194
5195 static __always_inline bool
5196 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5197 slot_level_handler fn, bool lock_flush_tlb)
5198 {
5199 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5200 PG_LEVEL_4K, lock_flush_tlb);
5201 }
5202
5203 static void free_mmu_pages(struct kvm_mmu *mmu)
5204 {
5205 free_page((unsigned long)mmu->pae_root);
5206 free_page((unsigned long)mmu->lm_root);
5207 }
5208
5209 static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5210 {
5211 struct page *page;
5212 int i;
5213
5214 mmu->root_hpa = INVALID_PAGE;
5215 mmu->root_pgd = 0;
5216 mmu->translate_gpa = translate_gpa;
5217 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5218 mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5219
5220 /*
5221 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5222 * while the PDP table is a per-vCPU construct that's allocated at MMU
5223 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5224 * x86_64. Therefore we need to allocate the PDP table in the first
5225 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5226 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5227 * skip allocating the PDP table.
5228 */
5229 if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5230 return 0;
5231
5232 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5233 if (!page)
5234 return -ENOMEM;
5235
5236 mmu->pae_root = page_address(page);
5237 for (i = 0; i < 4; ++i)
5238 mmu->pae_root[i] = INVALID_PAGE;
5239
5240 return 0;
5241 }
5242
5243 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5244 {
5245 int ret;
5246
5247 vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
5248 vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
5249
5250 vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
5251 vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
5252
5253 vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
5254
5255 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5256 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5257
5258 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5259
5260 ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
5261 if (ret)
5262 return ret;
5263
5264 ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
5265 if (ret)
5266 goto fail_allocate_root;
5267
5268 return ret;
5269 fail_allocate_root:
5270 free_mmu_pages(&vcpu->arch.guest_mmu);
5271 return ret;
5272 }
5273
5274 #define BATCH_ZAP_PAGES 10
5275 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5276 {
5277 struct kvm_mmu_page *sp, *node;
5278 int nr_zapped, batch = 0;
5279
5280 restart:
5281 list_for_each_entry_safe_reverse(sp, node,
5282 &kvm->arch.active_mmu_pages, link) {
5283 /*
5284 * No obsolete valid page exists before a newly created page
5285 * since active_mmu_pages is a FIFO list.
5286 */
5287 if (!is_obsolete_sp(kvm, sp))
5288 break;
5289
5290 /*
5291 * Invalid pages should never land back on the list of active
5292 * pages. Skip the bogus page, otherwise we'll get stuck in an
5293 * infinite loop if the page gets put back on the list (again).
5294 */
5295 if (WARN_ON(sp->role.invalid))
5296 continue;
5297
5298 /*
5299 * No need to flush the TLB since we're only zapping shadow
5300 * pages with an obsolete generation number and all vCPUS have
5301 * loaded a new root, i.e. the shadow pages being zapped cannot
5302 * be in active use by the guest.
5303 */
5304 if (batch >= BATCH_ZAP_PAGES &&
5305 cond_resched_lock(&kvm->mmu_lock)) {
5306 batch = 0;
5307 goto restart;
5308 }
5309
5310 if (__kvm_mmu_prepare_zap_page(kvm, sp,
5311 &kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
5312 batch += nr_zapped;
5313 goto restart;
5314 }
5315 }
5316
5317 /*
5318 * Trigger a remote TLB flush before freeing the page tables to ensure
5319 * KVM is not in the middle of a lockless shadow page table walk, which
5320 * may reference the pages.
5321 */
5322 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5323 }
5324
5325 /*
5326 * Fast invalidate all shadow pages and use lock-break technique
5327 * to zap obsolete pages.
5328 *
5329 * It's required when memslot is being deleted or VM is being
5330 * destroyed, in these cases, we should ensure that KVM MMU does
5331 * not use any resource of the being-deleted slot or all slots
5332 * after calling the function.
5333 */
5334 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5335 {
5336 lockdep_assert_held(&kvm->slots_lock);
5337
5338 spin_lock(&kvm->mmu_lock);
5339 trace_kvm_mmu_zap_all_fast(kvm);
5340
5341 /*
5342 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
5343 * held for the entire duration of zapping obsolete pages, it's
5344 * impossible for there to be multiple invalid generations associated
5345 * with *valid* shadow pages at any given time, i.e. there is exactly
5346 * one valid generation and (at most) one invalid generation.
5347 */
5348 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
5349
5350 /*
5351 * Notify all vcpus to reload its shadow page table and flush TLB.
5352 * Then all vcpus will switch to new shadow page table with the new
5353 * mmu_valid_gen.
5354 *
5355 * Note: we need to do this under the protection of mmu_lock,
5356 * otherwise, vcpu would purge shadow page but miss tlb flush.
5357 */
5358 kvm_reload_remote_mmus(kvm);
5359
5360 kvm_zap_obsolete_pages(kvm);
5361 spin_unlock(&kvm->mmu_lock);
5362 }
5363
5364 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5365 {
5366 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5367 }
5368
5369 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5370 struct kvm_memory_slot *slot,
5371 struct kvm_page_track_notifier_node *node)
5372 {
5373 kvm_mmu_zap_all_fast(kvm);
5374 }
5375
5376 void kvm_mmu_init_vm(struct kvm *kvm)
5377 {
5378 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5379
5380 node->track_write = kvm_mmu_pte_write;
5381 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5382 kvm_page_track_register_notifier(kvm, node);
5383 }
5384
5385 void kvm_mmu_uninit_vm(struct kvm *kvm)
5386 {
5387 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5388
5389 kvm_page_track_unregister_notifier(kvm, node);
5390 }
5391
5392 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5393 {
5394 struct kvm_memslots *slots;
5395 struct kvm_memory_slot *memslot;
5396 int i;
5397
5398 spin_lock(&kvm->mmu_lock);
5399 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5400 slots = __kvm_memslots(kvm, i);
5401 kvm_for_each_memslot(memslot, slots) {
5402 gfn_t start, end;
5403
5404 start = max(gfn_start, memslot->base_gfn);
5405 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5406 if (start >= end)
5407 continue;
5408
5409 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5410 PG_LEVEL_4K,
5411 KVM_MAX_HUGEPAGE_LEVEL,
5412 start, end - 1, true);
5413 }
5414 }
5415
5416 spin_unlock(&kvm->mmu_lock);
5417 }
5418
5419 static bool slot_rmap_write_protect(struct kvm *kvm,
5420 struct kvm_rmap_head *rmap_head)
5421 {
5422 return __rmap_write_protect(kvm, rmap_head, false);
5423 }
5424
5425 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5426 struct kvm_memory_slot *memslot,
5427 int start_level)
5428 {
5429 bool flush;
5430
5431 spin_lock(&kvm->mmu_lock);
5432 flush = slot_handle_level(kvm, memslot, slot_rmap_write_protect,
5433 start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
5434 spin_unlock(&kvm->mmu_lock);
5435
5436 /*
5437 * We can flush all the TLBs out of the mmu lock without TLB
5438 * corruption since we just change the spte from writable to
5439 * readonly so that we only need to care the case of changing
5440 * spte from present to present (changing the spte from present
5441 * to nonpresent will flush all the TLBs immediately), in other
5442 * words, the only case we care is mmu_spte_update() where we
5443 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5444 * instead of PT_WRITABLE_MASK, that means it does not depend
5445 * on PT_WRITABLE_MASK anymore.
5446 */
5447 if (flush)
5448 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
5449 }
5450
5451 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5452 struct kvm_rmap_head *rmap_head)
5453 {
5454 u64 *sptep;
5455 struct rmap_iterator iter;
5456 int need_tlb_flush = 0;
5457 kvm_pfn_t pfn;
5458 struct kvm_mmu_page *sp;
5459
5460 restart:
5461 for_each_rmap_spte(rmap_head, &iter, sptep) {
5462 sp = sptep_to_sp(sptep);
5463 pfn = spte_to_pfn(*sptep);
5464
5465 /*
5466 * We cannot do huge page mapping for indirect shadow pages,
5467 * which are found on the last rmap (level = 1) when not using
5468 * tdp; such shadow pages are synced with the page table in
5469 * the guest, and the guest page table is using 4K page size
5470 * mapping if the indirect sp has level = 1.
5471 */
5472 if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
5473 (kvm_is_zone_device_pfn(pfn) ||
5474 PageCompound(pfn_to_page(pfn)))) {
5475 pte_list_remove(rmap_head, sptep);
5476
5477 if (kvm_available_flush_tlb_with_range())
5478 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5479 KVM_PAGES_PER_HPAGE(sp->role.level));
5480 else
5481 need_tlb_flush = 1;
5482
5483 goto restart;
5484 }
5485 }
5486
5487 return need_tlb_flush;
5488 }
5489
5490 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5491 const struct kvm_memory_slot *memslot)
5492 {
5493 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5494 spin_lock(&kvm->mmu_lock);
5495 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5496 kvm_mmu_zap_collapsible_spte, true);
5497 spin_unlock(&kvm->mmu_lock);
5498 }
5499
5500 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
5501 struct kvm_memory_slot *memslot)
5502 {
5503 /*
5504 * All current use cases for flushing the TLBs for a specific memslot
5505 * are related to dirty logging, and do the TLB flush out of mmu_lock.
5506 * The interaction between the various operations on memslot must be
5507 * serialized by slots_locks to ensure the TLB flush from one operation
5508 * is observed by any other operation on the same memslot.
5509 */
5510 lockdep_assert_held(&kvm->slots_lock);
5511 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5512 memslot->npages);
5513 }
5514
5515 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5516 struct kvm_memory_slot *memslot)
5517 {
5518 bool flush;
5519
5520 spin_lock(&kvm->mmu_lock);
5521 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5522 spin_unlock(&kvm->mmu_lock);
5523
5524 /*
5525 * It's also safe to flush TLBs out of mmu lock here as currently this
5526 * function is only used for dirty logging, in which case flushing TLB
5527 * out of mmu lock also guarantees no dirty pages will be lost in
5528 * dirty_bitmap.
5529 */
5530 if (flush)
5531 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
5532 }
5533 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5534
5535 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5536 struct kvm_memory_slot *memslot)
5537 {
5538 bool flush;
5539
5540 spin_lock(&kvm->mmu_lock);
5541 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5542 false);
5543 spin_unlock(&kvm->mmu_lock);
5544
5545 if (flush)
5546 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
5547 }
5548 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5549
5550 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5551 struct kvm_memory_slot *memslot)
5552 {
5553 bool flush;
5554
5555 spin_lock(&kvm->mmu_lock);
5556 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5557 spin_unlock(&kvm->mmu_lock);
5558
5559 if (flush)
5560 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
5561 }
5562 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5563
5564 void kvm_mmu_zap_all(struct kvm *kvm)
5565 {
5566 struct kvm_mmu_page *sp, *node;
5567 LIST_HEAD(invalid_list);
5568 int ign;
5569
5570 spin_lock(&kvm->mmu_lock);
5571 restart:
5572 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
5573 if (WARN_ON(sp->role.invalid))
5574 continue;
5575 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
5576 goto restart;
5577 if (cond_resched_lock(&kvm->mmu_lock))
5578 goto restart;
5579 }
5580
5581 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5582 spin_unlock(&kvm->mmu_lock);
5583 }
5584
5585 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5586 {
5587 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
5588
5589 gen &= MMIO_SPTE_GEN_MASK;
5590
5591 /*
5592 * Generation numbers are incremented in multiples of the number of
5593 * address spaces in order to provide unique generations across all
5594 * address spaces. Strip what is effectively the address space
5595 * modifier prior to checking for a wrap of the MMIO generation so
5596 * that a wrap in any address space is detected.
5597 */
5598 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5599
5600 /*
5601 * The very rare case: if the MMIO generation number has wrapped,
5602 * zap all shadow pages.
5603 */
5604 if (unlikely(gen == 0)) {
5605 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5606 kvm_mmu_zap_all_fast(kvm);
5607 }
5608 }
5609
5610 static unsigned long
5611 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
5612 {
5613 struct kvm *kvm;
5614 int nr_to_scan = sc->nr_to_scan;
5615 unsigned long freed = 0;
5616
5617 mutex_lock(&kvm_lock);
5618
5619 list_for_each_entry(kvm, &vm_list, vm_list) {
5620 int idx;
5621 LIST_HEAD(invalid_list);
5622
5623 /*
5624 * Never scan more than sc->nr_to_scan VM instances.
5625 * Will not hit this condition practically since we do not try
5626 * to shrink more than one VM and it is very unlikely to see
5627 * !n_used_mmu_pages so many times.
5628 */
5629 if (!nr_to_scan--)
5630 break;
5631 /*
5632 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5633 * here. We may skip a VM instance errorneosly, but we do not
5634 * want to shrink a VM that only started to populate its MMU
5635 * anyway.
5636 */
5637 if (!kvm->arch.n_used_mmu_pages &&
5638 !kvm_has_zapped_obsolete_pages(kvm))
5639 continue;
5640
5641 idx = srcu_read_lock(&kvm->srcu);
5642 spin_lock(&kvm->mmu_lock);
5643
5644 if (kvm_has_zapped_obsolete_pages(kvm)) {
5645 kvm_mmu_commit_zap_page(kvm,
5646 &kvm->arch.zapped_obsolete_pages);
5647 goto unlock;
5648 }
5649
5650 freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
5651
5652 unlock:
5653 spin_unlock(&kvm->mmu_lock);
5654 srcu_read_unlock(&kvm->srcu, idx);
5655
5656 /*
5657 * unfair on small ones
5658 * per-vm shrinkers cry out
5659 * sadness comes quickly
5660 */
5661 list_move_tail(&kvm->vm_list, &vm_list);
5662 break;
5663 }
5664
5665 mutex_unlock(&kvm_lock);
5666 return freed;
5667 }
5668
5669 static unsigned long
5670 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
5671 {
5672 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
5673 }
5674
5675 static struct shrinker mmu_shrinker = {
5676 .count_objects = mmu_shrink_count,
5677 .scan_objects = mmu_shrink_scan,
5678 .seeks = DEFAULT_SEEKS * 10,
5679 };
5680
5681 static void mmu_destroy_caches(void)
5682 {
5683 kmem_cache_destroy(pte_list_desc_cache);
5684 kmem_cache_destroy(mmu_page_header_cache);
5685 }
5686
5687 static void kvm_set_mmio_spte_mask(void)
5688 {
5689 u64 mask;
5690
5691 /*
5692 * Set a reserved PA bit in MMIO SPTEs to generate page faults with
5693 * PFEC.RSVD=1 on MMIO accesses. 64-bit PTEs (PAE, x86-64, and EPT
5694 * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
5695 * 52-bit physical addresses then there are no reserved PA bits in the
5696 * PTEs and so the reserved PA approach must be disabled.
5697 */
5698 if (shadow_phys_bits < 52)
5699 mask = BIT_ULL(51) | PT_PRESENT_MASK;
5700 else
5701 mask = 0;
5702
5703 kvm_mmu_set_mmio_spte_mask(mask, ACC_WRITE_MASK | ACC_USER_MASK);
5704 }
5705
5706 static bool get_nx_auto_mode(void)
5707 {
5708 /* Return true when CPU has the bug, and mitigations are ON */
5709 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
5710 }
5711
5712 static void __set_nx_huge_pages(bool val)
5713 {
5714 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
5715 }
5716
5717 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
5718 {
5719 bool old_val = nx_huge_pages;
5720 bool new_val;
5721
5722 /* In "auto" mode deploy workaround only if CPU has the bug. */
5723 if (sysfs_streq(val, "off"))
5724 new_val = 0;
5725 else if (sysfs_streq(val, "force"))
5726 new_val = 1;
5727 else if (sysfs_streq(val, "auto"))
5728 new_val = get_nx_auto_mode();
5729 else if (strtobool(val, &new_val) < 0)
5730 return -EINVAL;
5731
5732 __set_nx_huge_pages(new_val);
5733
5734 if (new_val != old_val) {
5735 struct kvm *kvm;
5736
5737 mutex_lock(&kvm_lock);
5738
5739 list_for_each_entry(kvm, &vm_list, vm_list) {
5740 mutex_lock(&kvm->slots_lock);
5741 kvm_mmu_zap_all_fast(kvm);
5742 mutex_unlock(&kvm->slots_lock);
5743
5744 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
5745 }
5746 mutex_unlock(&kvm_lock);
5747 }
5748
5749 return 0;
5750 }
5751
5752 int kvm_mmu_module_init(void)
5753 {
5754 int ret = -ENOMEM;
5755
5756 if (nx_huge_pages == -1)
5757 __set_nx_huge_pages(get_nx_auto_mode());
5758
5759 /*
5760 * MMU roles use union aliasing which is, generally speaking, an
5761 * undefined behavior. However, we supposedly know how compilers behave
5762 * and the current status quo is unlikely to change. Guardians below are
5763 * supposed to let us know if the assumption becomes false.
5764 */
5765 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
5766 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
5767 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
5768
5769 kvm_mmu_reset_all_pte_masks();
5770
5771 kvm_set_mmio_spte_mask();
5772
5773 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
5774 sizeof(struct pte_list_desc),
5775 0, SLAB_ACCOUNT, NULL);
5776 if (!pte_list_desc_cache)
5777 goto out;
5778
5779 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
5780 sizeof(struct kvm_mmu_page),
5781 0, SLAB_ACCOUNT, NULL);
5782 if (!mmu_page_header_cache)
5783 goto out;
5784
5785 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
5786 goto out;
5787
5788 ret = register_shrinker(&mmu_shrinker);
5789 if (ret)
5790 goto out;
5791
5792 return 0;
5793
5794 out:
5795 mmu_destroy_caches();
5796 return ret;
5797 }
5798
5799 /*
5800 * Calculate mmu pages needed for kvm.
5801 */
5802 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
5803 {
5804 unsigned long nr_mmu_pages;
5805 unsigned long nr_pages = 0;
5806 struct kvm_memslots *slots;
5807 struct kvm_memory_slot *memslot;
5808 int i;
5809
5810 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5811 slots = __kvm_memslots(kvm, i);
5812
5813 kvm_for_each_memslot(memslot, slots)
5814 nr_pages += memslot->npages;
5815 }
5816
5817 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
5818 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
5819
5820 return nr_mmu_pages;
5821 }
5822
5823 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
5824 {
5825 kvm_mmu_unload(vcpu);
5826 free_mmu_pages(&vcpu->arch.root_mmu);
5827 free_mmu_pages(&vcpu->arch.guest_mmu);
5828 mmu_free_memory_caches(vcpu);
5829 }
5830
5831 void kvm_mmu_module_exit(void)
5832 {
5833 mmu_destroy_caches();
5834 percpu_counter_destroy(&kvm_total_used_mmu_pages);
5835 unregister_shrinker(&mmu_shrinker);
5836 mmu_audit_disable();
5837 }
5838
5839 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
5840 {
5841 unsigned int old_val;
5842 int err;
5843
5844 old_val = nx_huge_pages_recovery_ratio;
5845 err = param_set_uint(val, kp);
5846 if (err)
5847 return err;
5848
5849 if (READ_ONCE(nx_huge_pages) &&
5850 !old_val && nx_huge_pages_recovery_ratio) {
5851 struct kvm *kvm;
5852
5853 mutex_lock(&kvm_lock);
5854
5855 list_for_each_entry(kvm, &vm_list, vm_list)
5856 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
5857
5858 mutex_unlock(&kvm_lock);
5859 }
5860
5861 return err;
5862 }
5863
5864 static void kvm_recover_nx_lpages(struct kvm *kvm)
5865 {
5866 int rcu_idx;
5867 struct kvm_mmu_page *sp;
5868 unsigned int ratio;
5869 LIST_HEAD(invalid_list);
5870 ulong to_zap;
5871
5872 rcu_idx = srcu_read_lock(&kvm->srcu);
5873 spin_lock(&kvm->mmu_lock);
5874
5875 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
5876 to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
5877 for ( ; to_zap; --to_zap) {
5878 if (list_empty(&kvm->arch.lpage_disallowed_mmu_pages))
5879 break;
5880
5881 /*
5882 * We use a separate list instead of just using active_mmu_pages
5883 * because the number of lpage_disallowed pages is expected to
5884 * be relatively small compared to the total.
5885 */
5886 sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
5887 struct kvm_mmu_page,
5888 lpage_disallowed_link);
5889 WARN_ON_ONCE(!sp->lpage_disallowed);
5890 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
5891 WARN_ON_ONCE(sp->lpage_disallowed);
5892
5893 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5894 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5895 cond_resched_lock(&kvm->mmu_lock);
5896 }
5897 }
5898 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5899
5900 spin_unlock(&kvm->mmu_lock);
5901 srcu_read_unlock(&kvm->srcu, rcu_idx);
5902 }
5903
5904 static long get_nx_lpage_recovery_timeout(u64 start_time)
5905 {
5906 return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
5907 ? start_time + 60 * HZ - get_jiffies_64()
5908 : MAX_SCHEDULE_TIMEOUT;
5909 }
5910
5911 static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
5912 {
5913 u64 start_time;
5914 long remaining_time;
5915
5916 while (true) {
5917 start_time = get_jiffies_64();
5918 remaining_time = get_nx_lpage_recovery_timeout(start_time);
5919
5920 set_current_state(TASK_INTERRUPTIBLE);
5921 while (!kthread_should_stop() && remaining_time > 0) {
5922 schedule_timeout(remaining_time);
5923 remaining_time = get_nx_lpage_recovery_timeout(start_time);
5924 set_current_state(TASK_INTERRUPTIBLE);
5925 }
5926
5927 set_current_state(TASK_RUNNING);
5928
5929 if (kthread_should_stop())
5930 return 0;
5931
5932 kvm_recover_nx_lpages(kvm);
5933 }
5934 }
5935
5936 int kvm_mmu_post_init_vm(struct kvm *kvm)
5937 {
5938 int err;
5939
5940 err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
5941 "kvm-nx-lpage-recovery",
5942 &kvm->arch.nx_lpage_recovery_thread);
5943 if (!err)
5944 kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
5945
5946 return err;
5947 }
5948
5949 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
5950 {
5951 if (kvm->arch.nx_lpage_recovery_thread)
5952 kthread_stop(kvm->arch.nx_lpage_recovery_thread);
5953 }