KVM: MMU: change kvm_mmu_hugepage_adjust() arguments to kvm_page_fault
[linux-block.git] / arch / x86 / kvm / mmu / tdp_mmu.c
CommitLineData
fe5db27d
BG
1// SPDX-License-Identifier: GPL-2.0
2
02c00b3a
BG
3#include "mmu.h"
4#include "mmu_internal.h"
bb18842e 5#include "mmutrace.h"
2f2fad08 6#include "tdp_iter.h"
fe5db27d 7#include "tdp_mmu.h"
02c00b3a 8#include "spte.h"
fe5db27d 9
9a77daac 10#include <asm/cmpxchg.h>
33dd3574
BG
11#include <trace/events/kvm.h>
12
71ba3f31 13static bool __read_mostly tdp_mmu_enabled = true;
95fb5b02 14module_param_named(tdp_mmu, tdp_mmu_enabled, bool, 0644);
fe5db27d
BG
15
16/* Initializes the TDP MMU for the VM, if enabled. */
d501f747 17bool kvm_mmu_init_tdp_mmu(struct kvm *kvm)
fe5db27d 18{
897218ff 19 if (!tdp_enabled || !READ_ONCE(tdp_mmu_enabled))
d501f747 20 return false;
fe5db27d
BG
21
22 /* This should not be changed for the lifetime of the VM. */
23 kvm->arch.tdp_mmu_enabled = true;
02c00b3a
BG
24
25 INIT_LIST_HEAD(&kvm->arch.tdp_mmu_roots);
9a77daac 26 spin_lock_init(&kvm->arch.tdp_mmu_pages_lock);
89c0fd49 27 INIT_LIST_HEAD(&kvm->arch.tdp_mmu_pages);
d501f747
BG
28
29 return true;
fe5db27d
BG
30}
31
6103bc07
BG
32static __always_inline void kvm_lockdep_assert_mmu_lock_held(struct kvm *kvm,
33 bool shared)
34{
35 if (shared)
36 lockdep_assert_held_read(&kvm->mmu_lock);
37 else
38 lockdep_assert_held_write(&kvm->mmu_lock);
39}
40
fe5db27d
BG
41void kvm_mmu_uninit_tdp_mmu(struct kvm *kvm)
42{
43 if (!kvm->arch.tdp_mmu_enabled)
44 return;
02c00b3a 45
524a1e4e 46 WARN_ON(!list_empty(&kvm->arch.tdp_mmu_pages));
02c00b3a 47 WARN_ON(!list_empty(&kvm->arch.tdp_mmu_roots));
7cca2d0b
BG
48
49 /*
50 * Ensure that all the outstanding RCU callbacks to free shadow pages
51 * can run before the VM is torn down.
52 */
53 rcu_barrier();
02c00b3a
BG
54}
55
2bdb3d84 56static bool zap_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root,
6103bc07
BG
57 gfn_t start, gfn_t end, bool can_yield, bool flush,
58 bool shared);
2bdb3d84
BG
59
60static void tdp_mmu_free_sp(struct kvm_mmu_page *sp)
a889ea54 61{
2bdb3d84
BG
62 free_page((unsigned long)sp->spt);
63 kmem_cache_free(mmu_page_header_cache, sp);
a889ea54
BG
64}
65
c0e64238
BG
66/*
67 * This is called through call_rcu in order to free TDP page table memory
68 * safely with respect to other kernel threads that may be operating on
69 * the memory.
70 * By only accessing TDP MMU page table memory in an RCU read critical
71 * section, and freeing it after a grace period, lockless access to that
72 * memory won't use it after it is freed.
73 */
74static void tdp_mmu_free_sp_rcu_callback(struct rcu_head *head)
a889ea54 75{
c0e64238
BG
76 struct kvm_mmu_page *sp = container_of(head, struct kvm_mmu_page,
77 rcu_head);
a889ea54 78
c0e64238
BG
79 tdp_mmu_free_sp(sp);
80}
a889ea54 81
6103bc07
BG
82void kvm_tdp_mmu_put_root(struct kvm *kvm, struct kvm_mmu_page *root,
83 bool shared)
2bdb3d84 84{
6103bc07 85 kvm_lockdep_assert_mmu_lock_held(kvm, shared);
a889ea54 86
11cccf5c 87 if (!refcount_dec_and_test(&root->tdp_mmu_root_count))
2bdb3d84
BG
88 return;
89
90 WARN_ON(!root->tdp_mmu_page);
91
c0e64238
BG
92 spin_lock(&kvm->arch.tdp_mmu_pages_lock);
93 list_del_rcu(&root->link);
94 spin_unlock(&kvm->arch.tdp_mmu_pages_lock);
2bdb3d84 95
524a1e4e 96 zap_gfn_range(kvm, root, 0, -1ull, false, false, shared);
2bdb3d84 97
c0e64238 98 call_rcu(&root->rcu_head, tdp_mmu_free_sp_rcu_callback);
a889ea54
BG
99}
100
cfc10997
BG
101/*
102 * Finds the next valid root after root (or the first valid root if root
103 * is NULL), takes a reference on it, and returns that next root. If root
104 * is not NULL, this thread should have already taken a reference on it, and
105 * that reference will be dropped. If no valid root is found, this
106 * function will return NULL.
107 */
108static struct kvm_mmu_page *tdp_mmu_next_root(struct kvm *kvm,
6103bc07
BG
109 struct kvm_mmu_page *prev_root,
110 bool shared)
a889ea54
BG
111{
112 struct kvm_mmu_page *next_root;
113
c0e64238
BG
114 rcu_read_lock();
115
cfc10997 116 if (prev_root)
c0e64238
BG
117 next_root = list_next_or_null_rcu(&kvm->arch.tdp_mmu_roots,
118 &prev_root->link,
119 typeof(*prev_root), link);
cfc10997 120 else
c0e64238
BG
121 next_root = list_first_or_null_rcu(&kvm->arch.tdp_mmu_roots,
122 typeof(*next_root), link);
a889ea54 123
c0e64238
BG
124 while (next_root && !kvm_tdp_mmu_get_root(kvm, next_root))
125 next_root = list_next_or_null_rcu(&kvm->arch.tdp_mmu_roots,
126 &next_root->link, typeof(*next_root), link);
fb101293 127
c0e64238 128 rcu_read_unlock();
a889ea54 129
cfc10997 130 if (prev_root)
6103bc07 131 kvm_tdp_mmu_put_root(kvm, prev_root, shared);
a889ea54 132
a889ea54
BG
133 return next_root;
134}
135
136/*
137 * Note: this iterator gets and puts references to the roots it iterates over.
138 * This makes it safe to release the MMU lock and yield within the loop, but
139 * if exiting the loop early, the caller must drop the reference to the most
140 * recent root. (Unless keeping a live reference is desirable.)
6103bc07
BG
141 *
142 * If shared is set, this function is operating under the MMU lock in read
143 * mode. In the unlikely event that this thread must free a root, the lock
144 * will be temporarily dropped and reacquired in write mode.
a889ea54 145 */
6103bc07
BG
146#define for_each_tdp_mmu_root_yield_safe(_kvm, _root, _as_id, _shared) \
147 for (_root = tdp_mmu_next_root(_kvm, NULL, _shared); \
148 _root; \
149 _root = tdp_mmu_next_root(_kvm, _root, _shared)) \
150 if (kvm_mmu_page_as_id(_root) != _as_id) { \
a3f15bda 151 } else
a889ea54 152
c0e64238
BG
153#define for_each_tdp_mmu_root(_kvm, _root, _as_id) \
154 list_for_each_entry_rcu(_root, &_kvm->arch.tdp_mmu_roots, link, \
155 lockdep_is_held_type(&kvm->mmu_lock, 0) || \
156 lockdep_is_held(&kvm->arch.tdp_mmu_pages_lock)) \
a3f15bda
SC
157 if (kvm_mmu_page_as_id(_root) != _as_id) { \
158 } else
02c00b3a
BG
159
160static union kvm_mmu_page_role page_role_for_level(struct kvm_vcpu *vcpu,
161 int level)
162{
163 union kvm_mmu_page_role role;
164
165 role = vcpu->arch.mmu->mmu_role.base;
166 role.level = level;
167 role.direct = true;
168 role.gpte_is_8_bytes = true;
169 role.access = ACC_ALL;
170
171 return role;
172}
173
174static struct kvm_mmu_page *alloc_tdp_mmu_page(struct kvm_vcpu *vcpu, gfn_t gfn,
175 int level)
176{
177 struct kvm_mmu_page *sp;
178
179 sp = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
180 sp->spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_shadow_page_cache);
181 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
182
183 sp->role.word = page_role_for_level(vcpu, level).word;
184 sp->gfn = gfn;
185 sp->tdp_mmu_page = true;
186
33dd3574
BG
187 trace_kvm_mmu_get_page(sp, true);
188
02c00b3a
BG
189 return sp;
190}
191
6e6ec584 192hpa_t kvm_tdp_mmu_get_vcpu_root_hpa(struct kvm_vcpu *vcpu)
02c00b3a
BG
193{
194 union kvm_mmu_page_role role;
195 struct kvm *kvm = vcpu->kvm;
196 struct kvm_mmu_page *root;
197
6e6ec584 198 lockdep_assert_held_write(&kvm->mmu_lock);
02c00b3a 199
6e6ec584 200 role = page_role_for_level(vcpu, vcpu->arch.mmu->shadow_root_level);
02c00b3a
BG
201
202 /* Check for an existing root before allocating a new one. */
a3f15bda 203 for_each_tdp_mmu_root(kvm, root, kvm_mmu_role_as_id(role)) {
fb101293
BG
204 if (root->role.word == role.word &&
205 kvm_tdp_mmu_get_root(kvm, root))
6e6ec584 206 goto out;
02c00b3a
BG
207 }
208
209 root = alloc_tdp_mmu_page(vcpu, 0, vcpu->arch.mmu->shadow_root_level);
11cccf5c 210 refcount_set(&root->tdp_mmu_root_count, 1);
02c00b3a 211
c0e64238
BG
212 spin_lock(&kvm->arch.tdp_mmu_pages_lock);
213 list_add_rcu(&root->link, &kvm->arch.tdp_mmu_roots);
214 spin_unlock(&kvm->arch.tdp_mmu_pages_lock);
02c00b3a 215
6e6ec584 216out:
02c00b3a 217 return __pa(root->spt);
fe5db27d 218}
2f2fad08
BG
219
220static void handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
9a77daac
BG
221 u64 old_spte, u64 new_spte, int level,
222 bool shared);
2f2fad08 223
f8e14497
BG
224static void handle_changed_spte_acc_track(u64 old_spte, u64 new_spte, int level)
225{
f8e14497
BG
226 if (!is_shadow_present_pte(old_spte) || !is_last_spte(old_spte, level))
227 return;
228
229 if (is_accessed_spte(old_spte) &&
64bb2769
SC
230 (!is_shadow_present_pte(new_spte) || !is_accessed_spte(new_spte) ||
231 spte_to_pfn(old_spte) != spte_to_pfn(new_spte)))
f8e14497
BG
232 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
233}
234
a6a0b05d
BG
235static void handle_changed_spte_dirty_log(struct kvm *kvm, int as_id, gfn_t gfn,
236 u64 old_spte, u64 new_spte, int level)
237{
238 bool pfn_changed;
239 struct kvm_memory_slot *slot;
240
241 if (level > PG_LEVEL_4K)
242 return;
243
244 pfn_changed = spte_to_pfn(old_spte) != spte_to_pfn(new_spte);
245
246 if ((!is_writable_pte(old_spte) || pfn_changed) &&
247 is_writable_pte(new_spte)) {
248 slot = __gfn_to_memslot(__kvm_memslots(kvm, as_id), gfn);
fb04a1ed 249 mark_page_dirty_in_slot(kvm, slot, gfn);
a6a0b05d
BG
250 }
251}
252
a9442f59
BG
253/**
254 * tdp_mmu_link_page - Add a new page to the list of pages used by the TDP MMU
255 *
256 * @kvm: kvm instance
257 * @sp: the new page
258 * @account_nx: This page replaces a NX large page and should be marked for
259 * eventual reclaim.
260 */
261static void tdp_mmu_link_page(struct kvm *kvm, struct kvm_mmu_page *sp,
9653f2da 262 bool account_nx)
a9442f59 263{
9653f2da 264 spin_lock(&kvm->arch.tdp_mmu_pages_lock);
a9442f59
BG
265 list_add(&sp->link, &kvm->arch.tdp_mmu_pages);
266 if (account_nx)
267 account_huge_nx_page(kvm, sp);
9653f2da 268 spin_unlock(&kvm->arch.tdp_mmu_pages_lock);
a9442f59
BG
269}
270
271/**
272 * tdp_mmu_unlink_page - Remove page from the list of pages used by the TDP MMU
273 *
274 * @kvm: kvm instance
275 * @sp: the page to be removed
9a77daac
BG
276 * @shared: This operation may not be running under the exclusive use of
277 * the MMU lock and the operation must synchronize with other
278 * threads that might be adding or removing pages.
a9442f59 279 */
9a77daac
BG
280static void tdp_mmu_unlink_page(struct kvm *kvm, struct kvm_mmu_page *sp,
281 bool shared)
a9442f59 282{
9a77daac
BG
283 if (shared)
284 spin_lock(&kvm->arch.tdp_mmu_pages_lock);
285 else
286 lockdep_assert_held_write(&kvm->mmu_lock);
a9442f59
BG
287
288 list_del(&sp->link);
289 if (sp->lpage_disallowed)
290 unaccount_huge_nx_page(kvm, sp);
9a77daac
BG
291
292 if (shared)
293 spin_unlock(&kvm->arch.tdp_mmu_pages_lock);
a9442f59
BG
294}
295
a066e61f
BG
296/**
297 * handle_removed_tdp_mmu_page - handle a pt removed from the TDP structure
298 *
299 * @kvm: kvm instance
300 * @pt: the page removed from the paging structure
9a77daac
BG
301 * @shared: This operation may not be running under the exclusive use
302 * of the MMU lock and the operation must synchronize with other
303 * threads that might be modifying SPTEs.
a066e61f
BG
304 *
305 * Given a page table that has been removed from the TDP paging structure,
306 * iterates through the page table to clear SPTEs and free child page tables.
70fb3e41
BG
307 *
308 * Note that pt is passed in as a tdp_ptep_t, but it does not need RCU
309 * protection. Since this thread removed it from the paging structure,
310 * this thread will be responsible for ensuring the page is freed. Hence the
311 * early rcu_dereferences in the function.
a066e61f 312 */
70fb3e41 313static void handle_removed_tdp_mmu_page(struct kvm *kvm, tdp_ptep_t pt,
9a77daac 314 bool shared)
a066e61f 315{
70fb3e41 316 struct kvm_mmu_page *sp = sptep_to_sp(rcu_dereference(pt));
a066e61f 317 int level = sp->role.level;
e25f0e0c 318 gfn_t base_gfn = sp->gfn;
a066e61f 319 u64 old_child_spte;
9a77daac 320 u64 *sptep;
e25f0e0c 321 gfn_t gfn;
a066e61f
BG
322 int i;
323
324 trace_kvm_mmu_prepare_zap_page(sp);
325
9a77daac 326 tdp_mmu_unlink_page(kvm, sp, shared);
a066e61f
BG
327
328 for (i = 0; i < PT64_ENT_PER_PAGE; i++) {
70fb3e41 329 sptep = rcu_dereference(pt) + i;
f1b83255 330 gfn = base_gfn + i * KVM_PAGES_PER_HPAGE(level);
9a77daac
BG
331
332 if (shared) {
e25f0e0c
BG
333 /*
334 * Set the SPTE to a nonpresent value that other
335 * threads will not overwrite. If the SPTE was
336 * already marked as removed then another thread
337 * handling a page fault could overwrite it, so
338 * set the SPTE until it is set from some other
339 * value to the removed SPTE value.
340 */
341 for (;;) {
342 old_child_spte = xchg(sptep, REMOVED_SPTE);
343 if (!is_removed_spte(old_child_spte))
344 break;
345 cpu_relax();
346 }
9a77daac 347 } else {
8df9f1af
SC
348 /*
349 * If the SPTE is not MMU-present, there is no backing
350 * page associated with the SPTE and so no side effects
351 * that need to be recorded, and exclusive ownership of
352 * mmu_lock ensures the SPTE can't be made present.
353 * Note, zapping MMIO SPTEs is also unnecessary as they
354 * are guarded by the memslots generation, not by being
355 * unreachable.
356 */
9a77daac 357 old_child_spte = READ_ONCE(*sptep);
8df9f1af
SC
358 if (!is_shadow_present_pte(old_child_spte))
359 continue;
e25f0e0c
BG
360
361 /*
362 * Marking the SPTE as a removed SPTE is not
363 * strictly necessary here as the MMU lock will
364 * stop other threads from concurrently modifying
365 * this SPTE. Using the removed SPTE value keeps
366 * the two branches consistent and simplifies
367 * the function.
368 */
369 WRITE_ONCE(*sptep, REMOVED_SPTE);
9a77daac 370 }
e25f0e0c 371 handle_changed_spte(kvm, kvm_mmu_page_as_id(sp), gfn,
f1b83255 372 old_child_spte, REMOVED_SPTE, level,
e25f0e0c 373 shared);
a066e61f
BG
374 }
375
376 kvm_flush_remote_tlbs_with_address(kvm, gfn,
f1b83255 377 KVM_PAGES_PER_HPAGE(level + 1));
a066e61f 378
7cca2d0b 379 call_rcu(&sp->rcu_head, tdp_mmu_free_sp_rcu_callback);
a066e61f
BG
380}
381
2f2fad08 382/**
7f6231a3 383 * __handle_changed_spte - handle bookkeeping associated with an SPTE change
2f2fad08
BG
384 * @kvm: kvm instance
385 * @as_id: the address space of the paging structure the SPTE was a part of
386 * @gfn: the base GFN that was mapped by the SPTE
387 * @old_spte: The value of the SPTE before the change
388 * @new_spte: The value of the SPTE after the change
389 * @level: the level of the PT the SPTE is part of in the paging structure
9a77daac
BG
390 * @shared: This operation may not be running under the exclusive use of
391 * the MMU lock and the operation must synchronize with other
392 * threads that might be modifying SPTEs.
2f2fad08
BG
393 *
394 * Handle bookkeeping that might result from the modification of a SPTE.
395 * This function must be called for all TDP SPTE modifications.
396 */
397static void __handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
9a77daac
BG
398 u64 old_spte, u64 new_spte, int level,
399 bool shared)
2f2fad08
BG
400{
401 bool was_present = is_shadow_present_pte(old_spte);
402 bool is_present = is_shadow_present_pte(new_spte);
403 bool was_leaf = was_present && is_last_spte(old_spte, level);
404 bool is_leaf = is_present && is_last_spte(new_spte, level);
405 bool pfn_changed = spte_to_pfn(old_spte) != spte_to_pfn(new_spte);
2f2fad08
BG
406
407 WARN_ON(level > PT64_ROOT_MAX_LEVEL);
408 WARN_ON(level < PG_LEVEL_4K);
764388ce 409 WARN_ON(gfn & (KVM_PAGES_PER_HPAGE(level) - 1));
2f2fad08
BG
410
411 /*
412 * If this warning were to trigger it would indicate that there was a
413 * missing MMU notifier or a race with some notifier handler.
414 * A present, leaf SPTE should never be directly replaced with another
d9f6e12f 415 * present leaf SPTE pointing to a different PFN. A notifier handler
2f2fad08
BG
416 * should be zapping the SPTE before the main MM's page table is
417 * changed, or the SPTE should be zeroed, and the TLBs flushed by the
418 * thread before replacement.
419 */
420 if (was_leaf && is_leaf && pfn_changed) {
421 pr_err("Invalid SPTE change: cannot replace a present leaf\n"
422 "SPTE with another present leaf SPTE mapping a\n"
423 "different PFN!\n"
424 "as_id: %d gfn: %llx old_spte: %llx new_spte: %llx level: %d",
425 as_id, gfn, old_spte, new_spte, level);
426
427 /*
428 * Crash the host to prevent error propagation and guest data
d9f6e12f 429 * corruption.
2f2fad08
BG
430 */
431 BUG();
432 }
433
434 if (old_spte == new_spte)
435 return;
436
b9a98c34
BG
437 trace_kvm_tdp_mmu_spte_changed(as_id, gfn, level, old_spte, new_spte);
438
2f2fad08
BG
439 /*
440 * The only times a SPTE should be changed from a non-present to
441 * non-present state is when an MMIO entry is installed/modified/
442 * removed. In that case, there is nothing to do here.
443 */
444 if (!was_present && !is_present) {
445 /*
08f07c80
BG
446 * If this change does not involve a MMIO SPTE or removed SPTE,
447 * it is unexpected. Log the change, though it should not
448 * impact the guest since both the former and current SPTEs
449 * are nonpresent.
2f2fad08 450 */
08f07c80
BG
451 if (WARN_ON(!is_mmio_spte(old_spte) &&
452 !is_mmio_spte(new_spte) &&
453 !is_removed_spte(new_spte)))
2f2fad08
BG
454 pr_err("Unexpected SPTE change! Nonpresent SPTEs\n"
455 "should not be replaced with another,\n"
456 "different nonpresent SPTE, unless one or both\n"
08f07c80
BG
457 "are MMIO SPTEs, or the new SPTE is\n"
458 "a temporary removed SPTE.\n"
2f2fad08
BG
459 "as_id: %d gfn: %llx old_spte: %llx new_spte: %llx level: %d",
460 as_id, gfn, old_spte, new_spte, level);
461 return;
462 }
463
71f51d2c
MZ
464 if (is_leaf != was_leaf)
465 kvm_update_page_stats(kvm, level, is_leaf ? 1 : -1);
2f2fad08
BG
466
467 if (was_leaf && is_dirty_spte(old_spte) &&
64bb2769 468 (!is_present || !is_dirty_spte(new_spte) || pfn_changed))
2f2fad08
BG
469 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
470
471 /*
472 * Recursively handle child PTs if the change removed a subtree from
473 * the paging structure.
474 */
a066e61f
BG
475 if (was_present && !was_leaf && (pfn_changed || !is_present))
476 handle_removed_tdp_mmu_page(kvm,
9a77daac 477 spte_to_child_pt(old_spte, level), shared);
2f2fad08
BG
478}
479
480static void handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
9a77daac
BG
481 u64 old_spte, u64 new_spte, int level,
482 bool shared)
2f2fad08 483{
9a77daac
BG
484 __handle_changed_spte(kvm, as_id, gfn, old_spte, new_spte, level,
485 shared);
f8e14497 486 handle_changed_spte_acc_track(old_spte, new_spte, level);
a6a0b05d
BG
487 handle_changed_spte_dirty_log(kvm, as_id, gfn, old_spte,
488 new_spte, level);
2f2fad08 489}
faaf05b0 490
9a77daac 491/*
24ae4cfa
BG
492 * tdp_mmu_set_spte_atomic_no_dirty_log - Set a TDP MMU SPTE atomically
493 * and handle the associated bookkeeping, but do not mark the page dirty
494 * in KVM's dirty bitmaps.
9a77daac
BG
495 *
496 * @kvm: kvm instance
497 * @iter: a tdp_iter instance currently on the SPTE that should be set
498 * @new_spte: The value the SPTE should be set to
499 * Returns: true if the SPTE was set, false if it was not. If false is returned,
500 * this function will have no side-effects.
501 */
24ae4cfa
BG
502static inline bool tdp_mmu_set_spte_atomic_no_dirty_log(struct kvm *kvm,
503 struct tdp_iter *iter,
504 u64 new_spte)
9a77daac 505{
9a77daac
BG
506 lockdep_assert_held_read(&kvm->mmu_lock);
507
08f07c80
BG
508 /*
509 * Do not change removed SPTEs. Only the thread that froze the SPTE
510 * may modify it.
511 */
7a51393a 512 if (is_removed_spte(iter->old_spte))
08f07c80
BG
513 return false;
514
6e8eb206
DM
515 /*
516 * Note, fast_pf_fix_direct_spte() can also modify TDP MMU SPTEs and
517 * does not hold the mmu_lock.
518 */
9a77daac
BG
519 if (cmpxchg64(rcu_dereference(iter->sptep), iter->old_spte,
520 new_spte) != iter->old_spte)
521 return false;
522
24ae4cfa
BG
523 __handle_changed_spte(kvm, iter->as_id, iter->gfn, iter->old_spte,
524 new_spte, iter->level, true);
525 handle_changed_spte_acc_track(iter->old_spte, new_spte, iter->level);
9a77daac
BG
526
527 return true;
528}
529
081de470
DM
530/*
531 * tdp_mmu_map_set_spte_atomic - Set a leaf TDP MMU SPTE atomically to resolve a
532 * TDP page fault.
533 *
534 * @vcpu: The vcpu instance that took the TDP page fault.
535 * @iter: a tdp_iter instance currently on the SPTE that should be set
536 * @new_spte: The value the SPTE should be set to
537 *
538 * Returns: true if the SPTE was set, false if it was not. If false is returned,
539 * this function will have no side-effects.
540 */
541static inline bool tdp_mmu_map_set_spte_atomic(struct kvm_vcpu *vcpu,
542 struct tdp_iter *iter,
543 u64 new_spte)
24ae4cfa 544{
081de470
DM
545 struct kvm *kvm = vcpu->kvm;
546
24ae4cfa
BG
547 if (!tdp_mmu_set_spte_atomic_no_dirty_log(kvm, iter, new_spte))
548 return false;
549
081de470
DM
550 /*
551 * Use kvm_vcpu_gfn_to_memslot() instead of going through
552 * handle_changed_spte_dirty_log() to leverage vcpu->last_used_slot.
553 */
554 if (is_writable_pte(new_spte)) {
555 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, iter->gfn);
556
557 if (slot && kvm_slot_dirty_track_enabled(slot)) {
558 /* Enforced by kvm_mmu_hugepage_adjust. */
559 WARN_ON_ONCE(iter->level > PG_LEVEL_4K);
560 mark_page_dirty_in_slot(kvm, slot, iter->gfn);
561 }
562 }
563
24ae4cfa
BG
564 return true;
565}
566
08f07c80
BG
567static inline bool tdp_mmu_zap_spte_atomic(struct kvm *kvm,
568 struct tdp_iter *iter)
569{
570 /*
571 * Freeze the SPTE by setting it to a special,
572 * non-present value. This will stop other threads from
573 * immediately installing a present entry in its place
574 * before the TLBs are flushed.
575 */
081de470 576 if (!tdp_mmu_set_spte_atomic_no_dirty_log(kvm, iter, REMOVED_SPTE))
08f07c80
BG
577 return false;
578
579 kvm_flush_remote_tlbs_with_address(kvm, iter->gfn,
580 KVM_PAGES_PER_HPAGE(iter->level));
581
582 /*
583 * No other thread can overwrite the removed SPTE as they
584 * must either wait on the MMU lock or use
d9f6e12f 585 * tdp_mmu_set_spte_atomic which will not overwrite the
08f07c80
BG
586 * special removed SPTE value. No bookkeeping is needed
587 * here since the SPTE is going from non-present
588 * to non-present.
589 */
14f6fec2 590 WRITE_ONCE(*rcu_dereference(iter->sptep), 0);
08f07c80
BG
591
592 return true;
593}
594
9a77daac 595
fe43fa2f
BG
596/*
597 * __tdp_mmu_set_spte - Set a TDP MMU SPTE and handle the associated bookkeeping
598 * @kvm: kvm instance
599 * @iter: a tdp_iter instance currently on the SPTE that should be set
600 * @new_spte: The value the SPTE should be set to
601 * @record_acc_track: Notify the MM subsystem of changes to the accessed state
602 * of the page. Should be set unless handling an MMU
603 * notifier for access tracking. Leaving record_acc_track
604 * unset in that case prevents page accesses from being
605 * double counted.
606 * @record_dirty_log: Record the page as dirty in the dirty bitmap if
607 * appropriate for the change being made. Should be set
608 * unless performing certain dirty logging operations.
609 * Leaving record_dirty_log unset in that case prevents page
610 * writes from being double counted.
611 */
f8e14497 612static inline void __tdp_mmu_set_spte(struct kvm *kvm, struct tdp_iter *iter,
a6a0b05d
BG
613 u64 new_spte, bool record_acc_track,
614 bool record_dirty_log)
faaf05b0 615{
531810ca 616 lockdep_assert_held_write(&kvm->mmu_lock);
3a9a4aa5 617
08f07c80
BG
618 /*
619 * No thread should be using this function to set SPTEs to the
620 * temporary removed SPTE value.
621 * If operating under the MMU lock in read mode, tdp_mmu_set_spte_atomic
622 * should be used. If operating under the MMU lock in write mode, the
623 * use of the removed SPTE should not be necessary.
624 */
7a51393a 625 WARN_ON(is_removed_spte(iter->old_spte));
08f07c80 626
7cca2d0b 627 WRITE_ONCE(*rcu_dereference(iter->sptep), new_spte);
f8e14497 628
08889894
SC
629 __handle_changed_spte(kvm, iter->as_id, iter->gfn, iter->old_spte,
630 new_spte, iter->level, false);
f8e14497
BG
631 if (record_acc_track)
632 handle_changed_spte_acc_track(iter->old_spte, new_spte,
633 iter->level);
a6a0b05d 634 if (record_dirty_log)
08889894 635 handle_changed_spte_dirty_log(kvm, iter->as_id, iter->gfn,
a6a0b05d
BG
636 iter->old_spte, new_spte,
637 iter->level);
f8e14497
BG
638}
639
640static inline void tdp_mmu_set_spte(struct kvm *kvm, struct tdp_iter *iter,
641 u64 new_spte)
642{
a6a0b05d 643 __tdp_mmu_set_spte(kvm, iter, new_spte, true, true);
f8e14497 644}
faaf05b0 645
f8e14497
BG
646static inline void tdp_mmu_set_spte_no_acc_track(struct kvm *kvm,
647 struct tdp_iter *iter,
648 u64 new_spte)
649{
a6a0b05d
BG
650 __tdp_mmu_set_spte(kvm, iter, new_spte, false, true);
651}
652
653static inline void tdp_mmu_set_spte_no_dirty_log(struct kvm *kvm,
654 struct tdp_iter *iter,
655 u64 new_spte)
656{
657 __tdp_mmu_set_spte(kvm, iter, new_spte, true, false);
faaf05b0
BG
658}
659
660#define tdp_root_for_each_pte(_iter, _root, _start, _end) \
661 for_each_tdp_pte(_iter, _root->spt, _root->role.level, _start, _end)
662
f8e14497
BG
663#define tdp_root_for_each_leaf_pte(_iter, _root, _start, _end) \
664 tdp_root_for_each_pte(_iter, _root, _start, _end) \
665 if (!is_shadow_present_pte(_iter.old_spte) || \
666 !is_last_spte(_iter.old_spte, _iter.level)) \
667 continue; \
668 else
669
bb18842e
BG
670#define tdp_mmu_for_each_pte(_iter, _mmu, _start, _end) \
671 for_each_tdp_pte(_iter, __va(_mmu->root_hpa), \
672 _mmu->shadow_root_level, _start, _end)
673
e28a436c
BG
674/*
675 * Yield if the MMU lock is contended or this thread needs to return control
676 * to the scheduler.
677 *
e139a34e
BG
678 * If this function should yield and flush is set, it will perform a remote
679 * TLB flush before yielding.
680 *
e28a436c 681 * If this function yields, it will also reset the tdp_iter's walk over the
ed5e484b
BG
682 * paging structure and the calling function should skip to the next
683 * iteration to allow the iterator to continue its traversal from the
684 * paging structure root.
e28a436c
BG
685 *
686 * Return true if this function yielded and the iterator's traversal was reset.
687 * Return false if a yield was not needed.
688 */
e139a34e 689static inline bool tdp_mmu_iter_cond_resched(struct kvm *kvm,
6103bc07
BG
690 struct tdp_iter *iter, bool flush,
691 bool shared)
a6a0b05d 692{
ed5e484b
BG
693 /* Ensure forward progress has been made before yielding. */
694 if (iter->next_last_level_gfn == iter->yielded_gfn)
695 return false;
696
531810ca 697 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7cca2d0b
BG
698 rcu_read_unlock();
699
e139a34e
BG
700 if (flush)
701 kvm_flush_remote_tlbs(kvm);
702
6103bc07
BG
703 if (shared)
704 cond_resched_rwlock_read(&kvm->mmu_lock);
705 else
706 cond_resched_rwlock_write(&kvm->mmu_lock);
707
7cca2d0b 708 rcu_read_lock();
ed5e484b
BG
709
710 WARN_ON(iter->gfn > iter->next_last_level_gfn);
711
b601c3bc 712 tdp_iter_restart(iter);
ed5e484b 713
e28a436c 714 return true;
a6a0b05d 715 }
e28a436c
BG
716
717 return false;
a6a0b05d
BG
718}
719
faaf05b0
BG
720/*
721 * Tears down the mappings for the range of gfns, [start, end), and frees the
722 * non-root pages mapping GFNs strictly within that range. Returns true if
723 * SPTEs have been cleared and a TLB flush is needed before releasing the
724 * MMU lock.
6103bc07 725 *
063afacd
BG
726 * If can_yield is true, will release the MMU lock and reschedule if the
727 * scheduler needs the CPU or there is contention on the MMU lock. If this
728 * function cannot yield, it will not release the MMU lock or reschedule and
729 * the caller must ensure it does not supply too large a GFN range, or the
6103bc07
BG
730 * operation can cause a soft lockup.
731 *
732 * If shared is true, this thread holds the MMU lock in read mode and must
733 * account for the possibility that other threads are modifying the paging
734 * structures concurrently. If shared is false, this thread should hold the
735 * MMU lock in write mode.
faaf05b0
BG
736 */
737static bool zap_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root,
6103bc07
BG
738 gfn_t start, gfn_t end, bool can_yield, bool flush,
739 bool shared)
faaf05b0 740{
524a1e4e
SC
741 gfn_t max_gfn_host = 1ULL << (shadow_phys_bits - PAGE_SHIFT);
742 bool zap_all = (start == 0 && end >= max_gfn_host);
faaf05b0 743 struct tdp_iter iter;
faaf05b0 744
0103098f
SC
745 /*
746 * No need to try to step down in the iterator when zapping all SPTEs,
747 * zapping the top-level non-leaf SPTEs will recurse on their children.
748 */
749 int min_level = zap_all ? root->role.level : PG_LEVEL_4K;
750
524a1e4e
SC
751 /*
752 * Bound the walk at host.MAXPHYADDR, guest accesses beyond that will
753 * hit a #PF(RSVD) and never get to an EPT Violation/Misconfig / #NPF,
754 * and so KVM will never install a SPTE for such addresses.
755 */
756 end = min(end, max_gfn_host);
757
6103bc07
BG
758 kvm_lockdep_assert_mmu_lock_held(kvm, shared);
759
7cca2d0b
BG
760 rcu_read_lock();
761
0103098f
SC
762 for_each_tdp_pte_min_level(iter, root->spt, root->role.level,
763 min_level, start, end) {
6103bc07 764retry:
1af4a960 765 if (can_yield &&
6103bc07 766 tdp_mmu_iter_cond_resched(kvm, &iter, flush, shared)) {
a835429c 767 flush = false;
1af4a960
BG
768 continue;
769 }
770
faaf05b0
BG
771 if (!is_shadow_present_pte(iter.old_spte))
772 continue;
773
774 /*
775 * If this is a non-last-level SPTE that covers a larger range
776 * than should be zapped, continue, and zap the mappings at a
524a1e4e 777 * lower level, except when zapping all SPTEs.
faaf05b0 778 */
524a1e4e
SC
779 if (!zap_all &&
780 (iter.gfn < start ||
faaf05b0
BG
781 iter.gfn + KVM_PAGES_PER_HPAGE(iter.level) > end) &&
782 !is_last_spte(iter.old_spte, iter.level))
783 continue;
784
6103bc07
BG
785 if (!shared) {
786 tdp_mmu_set_spte(kvm, &iter, 0);
787 flush = true;
788 } else if (!tdp_mmu_zap_spte_atomic(kvm, &iter)) {
789 /*
790 * The iter must explicitly re-read the SPTE because
791 * the atomic cmpxchg failed.
792 */
793 iter.old_spte = READ_ONCE(*rcu_dereference(iter.sptep));
794 goto retry;
795 }
faaf05b0 796 }
7cca2d0b
BG
797
798 rcu_read_unlock();
a835429c 799 return flush;
faaf05b0
BG
800}
801
802/*
803 * Tears down the mappings for the range of gfns, [start, end), and frees the
804 * non-root pages mapping GFNs strictly within that range. Returns true if
805 * SPTEs have been cleared and a TLB flush is needed before releasing the
806 * MMU lock.
807 */
2b9663d8 808bool __kvm_tdp_mmu_zap_gfn_range(struct kvm *kvm, int as_id, gfn_t start,
5a324c24 809 gfn_t end, bool can_yield, bool flush)
faaf05b0
BG
810{
811 struct kvm_mmu_page *root;
faaf05b0 812
5a324c24 813 for_each_tdp_mmu_root_yield_safe(kvm, root, as_id, false)
6103bc07 814 flush = zap_gfn_range(kvm, root, start, end, can_yield, flush,
5a324c24 815 false);
faaf05b0 816
faaf05b0
BG
817 return flush;
818}
819
820void kvm_tdp_mmu_zap_all(struct kvm *kvm)
821{
2b9663d8
SC
822 bool flush = false;
823 int i;
824
825 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
5a324c24 826 flush = kvm_tdp_mmu_zap_gfn_range(kvm, i, 0, -1ull, flush);
faaf05b0 827
faaf05b0
BG
828 if (flush)
829 kvm_flush_remote_tlbs(kvm);
830}
bb18842e 831
4c6654bd
BG
832static struct kvm_mmu_page *next_invalidated_root(struct kvm *kvm,
833 struct kvm_mmu_page *prev_root)
834{
835 struct kvm_mmu_page *next_root;
836
837 if (prev_root)
838 next_root = list_next_or_null_rcu(&kvm->arch.tdp_mmu_roots,
839 &prev_root->link,
840 typeof(*prev_root), link);
841 else
842 next_root = list_first_or_null_rcu(&kvm->arch.tdp_mmu_roots,
843 typeof(*next_root), link);
844
845 while (next_root && !(next_root->role.invalid &&
846 refcount_read(&next_root->tdp_mmu_root_count)))
847 next_root = list_next_or_null_rcu(&kvm->arch.tdp_mmu_roots,
848 &next_root->link,
849 typeof(*next_root), link);
850
851 return next_root;
852}
853
854/*
855 * Since kvm_tdp_mmu_zap_all_fast has acquired a reference to each
856 * invalidated root, they will not be freed until this function drops the
857 * reference. Before dropping that reference, tear down the paging
858 * structure so that whichever thread does drop the last reference
859 * only has to do a trivial amount of work. Since the roots are invalid,
860 * no new SPTEs should be created under them.
861 */
862void kvm_tdp_mmu_zap_invalidated_roots(struct kvm *kvm)
863{
4c6654bd
BG
864 struct kvm_mmu_page *next_root;
865 struct kvm_mmu_page *root;
866 bool flush = false;
867
868 lockdep_assert_held_read(&kvm->mmu_lock);
869
870 rcu_read_lock();
871
872 root = next_invalidated_root(kvm, NULL);
873
874 while (root) {
875 next_root = next_invalidated_root(kvm, root);
876
877 rcu_read_unlock();
878
524a1e4e 879 flush = zap_gfn_range(kvm, root, 0, -1ull, true, flush, true);
4c6654bd
BG
880
881 /*
882 * Put the reference acquired in
883 * kvm_tdp_mmu_invalidate_roots
884 */
885 kvm_tdp_mmu_put_root(kvm, root, true);
886
887 root = next_root;
888
889 rcu_read_lock();
890 }
891
892 rcu_read_unlock();
faaf05b0 893
faaf05b0
BG
894 if (flush)
895 kvm_flush_remote_tlbs(kvm);
896}
bb18842e 897
b7cccd39
BG
898/*
899 * Mark each TDP MMU root as invalid so that other threads
900 * will drop their references and allow the root count to
901 * go to 0.
902 *
4c6654bd
BG
903 * Also take a reference on all roots so that this thread
904 * can do the bulk of the work required to free the roots
905 * once they are invalidated. Without this reference, a
906 * vCPU thread might drop the last reference to a root and
907 * get stuck with tearing down the entire paging structure.
908 *
909 * Roots which have a zero refcount should be skipped as
910 * they're already being torn down.
911 * Already invalid roots should be referenced again so that
912 * they aren't freed before kvm_tdp_mmu_zap_all_fast is
913 * done with them.
914 *
b7cccd39
BG
915 * This has essentially the same effect for the TDP MMU
916 * as updating mmu_valid_gen does for the shadow MMU.
917 */
918void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm)
919{
920 struct kvm_mmu_page *root;
921
922 lockdep_assert_held_write(&kvm->mmu_lock);
923 list_for_each_entry(root, &kvm->arch.tdp_mmu_roots, link)
4c6654bd
BG
924 if (refcount_inc_not_zero(&root->tdp_mmu_root_count))
925 root->role.invalid = true;
b7cccd39
BG
926}
927
bb18842e
BG
928/*
929 * Installs a last-level SPTE to handle a TDP page fault.
930 * (NPT/EPT violation/misconfiguration)
931 */
cdc47767
PB
932static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu,
933 struct kvm_page_fault *fault,
934 struct tdp_iter *iter)
bb18842e
BG
935{
936 u64 new_spte;
57a3e96d 937 int ret = RET_PF_FIXED;
bb18842e
BG
938 int make_spte_ret = 0;
939
cdc47767 940 if (unlikely(is_noslot_pfn(fault->pfn)))
bb18842e 941 new_spte = make_mmio_spte(vcpu, iter->gfn, ACC_ALL);
9a77daac 942 else
bb18842e 943 make_spte_ret = make_spte(vcpu, ACC_ALL, iter->level, iter->gfn,
cdc47767
PB
944 fault->pfn, iter->old_spte, fault->prefault, true,
945 fault->map_writable, !shadow_accessed_mask,
bb18842e
BG
946 &new_spte);
947
948 if (new_spte == iter->old_spte)
949 ret = RET_PF_SPURIOUS;
081de470 950 else if (!tdp_mmu_map_set_spte_atomic(vcpu, iter, new_spte))
9a77daac 951 return RET_PF_RETRY;
bb18842e
BG
952
953 /*
954 * If the page fault was caused by a write but the page is write
955 * protected, emulation is needed. If the emulation was skipped,
956 * the vCPU would have the same fault again.
957 */
958 if (make_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
cdc47767 959 if (fault->write)
bb18842e 960 ret = RET_PF_EMULATE;
bb18842e
BG
961 }
962
963 /* If a MMIO SPTE is installed, the MMIO will need to be emulated. */
9a77daac
BG
964 if (unlikely(is_mmio_spte(new_spte))) {
965 trace_mark_mmio_spte(rcu_dereference(iter->sptep), iter->gfn,
966 new_spte);
bb18842e 967 ret = RET_PF_EMULATE;
3849e092 968 } else {
9a77daac
BG
969 trace_kvm_mmu_set_spte(iter->level, iter->gfn,
970 rcu_dereference(iter->sptep));
3849e092 971 }
bb18842e 972
857f8474
KH
973 /*
974 * Increase pf_fixed in both RET_PF_EMULATE and RET_PF_FIXED to be
975 * consistent with legacy MMU behavior.
976 */
977 if (ret != RET_PF_SPURIOUS)
bb18842e
BG
978 vcpu->stat.pf_fixed++;
979
980 return ret;
981}
982
983/*
984 * Handle a TDP page fault (NPT/EPT violation/misconfiguration) by installing
985 * page tables and SPTEs to translate the faulting guest physical address.
986 */
2f6305dd 987int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
bb18842e 988{
bb18842e
BG
989 struct kvm_mmu *mmu = vcpu->arch.mmu;
990 struct tdp_iter iter;
89c0fd49 991 struct kvm_mmu_page *sp;
bb18842e
BG
992 u64 *child_pt;
993 u64 new_spte;
994 int ret;
bb18842e 995
73a3c659 996 kvm_mmu_hugepage_adjust(vcpu, fault);
bb18842e 997
73a3c659 998 trace_kvm_mmu_spte_requested(fault->addr, fault->goal_level, fault->pfn);
7cca2d0b
BG
999
1000 rcu_read_lock();
1001
2f6305dd 1002 tdp_mmu_for_each_pte(iter, mmu, fault->gfn, fault->gfn + 1) {
73a3c659 1003 if (fault->nx_huge_page_workaround_enabled)
2f6305dd 1004 disallowed_hugepage_adjust(iter.old_spte, fault->gfn,
73a3c659 1005 iter.level, &fault->pfn, &fault->goal_level);
bb18842e 1006
73a3c659 1007 if (iter.level == fault->goal_level)
bb18842e
BG
1008 break;
1009
1010 /*
1011 * If there is an SPTE mapping a large page at a higher level
1012 * than the target, that SPTE must be cleared and replaced
1013 * with a non-leaf SPTE.
1014 */
1015 if (is_shadow_present_pte(iter.old_spte) &&
1016 is_large_pte(iter.old_spte)) {
08f07c80 1017 if (!tdp_mmu_zap_spte_atomic(vcpu->kvm, &iter))
9a77daac 1018 break;
bb18842e 1019
bb18842e
BG
1020 /*
1021 * The iter must explicitly re-read the spte here
1022 * because the new value informs the !present
1023 * path below.
1024 */
7cca2d0b 1025 iter.old_spte = READ_ONCE(*rcu_dereference(iter.sptep));
bb18842e
BG
1026 }
1027
1028 if (!is_shadow_present_pte(iter.old_spte)) {
ff76d506 1029 /*
c4342633 1030 * If SPTE has been frozen by another thread, just
ff76d506
KH
1031 * give up and retry, avoiding unnecessary page table
1032 * allocation and free.
1033 */
1034 if (is_removed_spte(iter.old_spte))
1035 break;
1036
f1b83255 1037 sp = alloc_tdp_mmu_page(vcpu, iter.gfn, iter.level - 1);
89c0fd49 1038 child_pt = sp->spt;
a9442f59 1039
bb18842e
BG
1040 new_spte = make_nonleaf_spte(child_pt,
1041 !shadow_accessed_mask);
1042
081de470 1043 if (tdp_mmu_set_spte_atomic_no_dirty_log(vcpu->kvm, &iter, new_spte)) {
9653f2da 1044 tdp_mmu_link_page(vcpu->kvm, sp,
73a3c659
PB
1045 fault->huge_page_disallowed &&
1046 fault->req_level >= iter.level);
9a77daac
BG
1047
1048 trace_kvm_mmu_get_page(sp, true);
1049 } else {
1050 tdp_mmu_free_sp(sp);
1051 break;
1052 }
bb18842e
BG
1053 }
1054 }
1055
73a3c659 1056 if (iter.level != fault->goal_level) {
7cca2d0b 1057 rcu_read_unlock();
bb18842e 1058 return RET_PF_RETRY;
7cca2d0b 1059 }
bb18842e 1060
cdc47767 1061 ret = tdp_mmu_map_handle_target_level(vcpu, fault, &iter);
7cca2d0b 1062 rcu_read_unlock();
bb18842e
BG
1063
1064 return ret;
1065}
063afacd 1066
3039bcc7
SC
1067bool kvm_tdp_mmu_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range,
1068 bool flush)
063afacd 1069{
063afacd 1070 struct kvm_mmu_page *root;
063afacd 1071
3039bcc7
SC
1072 for_each_tdp_mmu_root(kvm, root, range->slot->as_id)
1073 flush |= zap_gfn_range(kvm, root, range->start, range->end,
6103bc07 1074 range->may_block, flush, false);
063afacd 1075
3039bcc7 1076 return flush;
063afacd
BG
1077}
1078
3039bcc7
SC
1079typedef bool (*tdp_handler_t)(struct kvm *kvm, struct tdp_iter *iter,
1080 struct kvm_gfn_range *range);
063afacd 1081
3039bcc7
SC
1082static __always_inline bool kvm_tdp_mmu_handle_gfn(struct kvm *kvm,
1083 struct kvm_gfn_range *range,
1084 tdp_handler_t handler)
063afacd 1085{
3039bcc7
SC
1086 struct kvm_mmu_page *root;
1087 struct tdp_iter iter;
1088 bool ret = false;
1089
1090 rcu_read_lock();
1091
e1eed584
SC
1092 /*
1093 * Don't support rescheduling, none of the MMU notifiers that funnel
1094 * into this helper allow blocking; it'd be dead, wasteful code.
1095 */
3039bcc7
SC
1096 for_each_tdp_mmu_root(kvm, root, range->slot->as_id) {
1097 tdp_root_for_each_leaf_pte(iter, root, range->start, range->end)
1098 ret |= handler(kvm, &iter, range);
1099 }
1100
1101 rcu_read_unlock();
1102
1103 return ret;
063afacd 1104}
f8e14497
BG
1105
1106/*
1107 * Mark the SPTEs range of GFNs [start, end) unaccessed and return non-zero
1108 * if any of the GFNs in the range have been accessed.
1109 */
3039bcc7
SC
1110static bool age_gfn_range(struct kvm *kvm, struct tdp_iter *iter,
1111 struct kvm_gfn_range *range)
f8e14497 1112{
f8e14497
BG
1113 u64 new_spte = 0;
1114
3039bcc7
SC
1115 /* If we have a non-accessed entry we don't need to change the pte. */
1116 if (!is_accessed_spte(iter->old_spte))
1117 return false;
7cca2d0b 1118
3039bcc7
SC
1119 new_spte = iter->old_spte;
1120
1121 if (spte_ad_enabled(new_spte)) {
1122 new_spte &= ~shadow_accessed_mask;
1123 } else {
f8e14497 1124 /*
3039bcc7
SC
1125 * Capture the dirty status of the page, so that it doesn't get
1126 * lost when the SPTE is marked for access tracking.
f8e14497 1127 */
3039bcc7
SC
1128 if (is_writable_pte(new_spte))
1129 kvm_set_pfn_dirty(spte_to_pfn(new_spte));
f8e14497 1130
3039bcc7 1131 new_spte = mark_spte_for_access_track(new_spte);
f8e14497
BG
1132 }
1133
3039bcc7 1134 tdp_mmu_set_spte_no_acc_track(kvm, iter, new_spte);
7cca2d0b 1135
3039bcc7 1136 return true;
f8e14497
BG
1137}
1138
3039bcc7 1139bool kvm_tdp_mmu_age_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
f8e14497 1140{
3039bcc7 1141 return kvm_tdp_mmu_handle_gfn(kvm, range, age_gfn_range);
f8e14497
BG
1142}
1143
3039bcc7
SC
1144static bool test_age_gfn(struct kvm *kvm, struct tdp_iter *iter,
1145 struct kvm_gfn_range *range)
f8e14497 1146{
3039bcc7 1147 return is_accessed_spte(iter->old_spte);
f8e14497
BG
1148}
1149
3039bcc7 1150bool kvm_tdp_mmu_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
f8e14497 1151{
3039bcc7 1152 return kvm_tdp_mmu_handle_gfn(kvm, range, test_age_gfn);
f8e14497 1153}
1d8dd6b3 1154
3039bcc7
SC
1155static bool set_spte_gfn(struct kvm *kvm, struct tdp_iter *iter,
1156 struct kvm_gfn_range *range)
1d8dd6b3 1157{
1d8dd6b3 1158 u64 new_spte;
7cca2d0b 1159
3039bcc7
SC
1160 /* Huge pages aren't expected to be modified without first being zapped. */
1161 WARN_ON(pte_huge(range->pte) || range->start + 1 != range->end);
1d8dd6b3 1162
3039bcc7
SC
1163 if (iter->level != PG_LEVEL_4K ||
1164 !is_shadow_present_pte(iter->old_spte))
1165 return false;
1d8dd6b3 1166
3039bcc7
SC
1167 /*
1168 * Note, when changing a read-only SPTE, it's not strictly necessary to
1169 * zero the SPTE before setting the new PFN, but doing so preserves the
1170 * invariant that the PFN of a present * leaf SPTE can never change.
1171 * See __handle_changed_spte().
1172 */
1173 tdp_mmu_set_spte(kvm, iter, 0);
1d8dd6b3 1174
3039bcc7
SC
1175 if (!pte_write(range->pte)) {
1176 new_spte = kvm_mmu_changed_pte_notifier_make_spte(iter->old_spte,
1177 pte_pfn(range->pte));
1d8dd6b3 1178
3039bcc7 1179 tdp_mmu_set_spte(kvm, iter, new_spte);
1d8dd6b3
BG
1180 }
1181
3039bcc7 1182 return true;
1d8dd6b3
BG
1183}
1184
3039bcc7
SC
1185/*
1186 * Handle the changed_pte MMU notifier for the TDP MMU.
1187 * data is a pointer to the new pte_t mapping the HVA specified by the MMU
1188 * notifier.
1189 * Returns non-zero if a flush is needed before releasing the MMU lock.
1190 */
1191bool kvm_tdp_mmu_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1d8dd6b3 1192{
3039bcc7
SC
1193 bool flush = kvm_tdp_mmu_handle_gfn(kvm, range, set_spte_gfn);
1194
1195 /* FIXME: return 'flush' instead of flushing here. */
1196 if (flush)
1197 kvm_flush_remote_tlbs_with_address(kvm, range->start, 1);
1198
1199 return false;
1d8dd6b3
BG
1200}
1201
a6a0b05d 1202/*
bedd9195
DM
1203 * Remove write access from all SPTEs at or above min_level that map GFNs
1204 * [start, end). Returns true if an SPTE has been changed and the TLBs need to
1205 * be flushed.
a6a0b05d
BG
1206 */
1207static bool wrprot_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root,
1208 gfn_t start, gfn_t end, int min_level)
1209{
1210 struct tdp_iter iter;
1211 u64 new_spte;
1212 bool spte_set = false;
1213
7cca2d0b
BG
1214 rcu_read_lock();
1215
a6a0b05d
BG
1216 BUG_ON(min_level > KVM_MAX_HUGEPAGE_LEVEL);
1217
1218 for_each_tdp_pte_min_level(iter, root->spt, root->role.level,
1219 min_level, start, end) {
24ae4cfa
BG
1220retry:
1221 if (tdp_mmu_iter_cond_resched(kvm, &iter, false, true))
1af4a960
BG
1222 continue;
1223
a6a0b05d 1224 if (!is_shadow_present_pte(iter.old_spte) ||
0f99ee2c
BG
1225 !is_last_spte(iter.old_spte, iter.level) ||
1226 !(iter.old_spte & PT_WRITABLE_MASK))
a6a0b05d
BG
1227 continue;
1228
1229 new_spte = iter.old_spte & ~PT_WRITABLE_MASK;
1230
24ae4cfa
BG
1231 if (!tdp_mmu_set_spte_atomic_no_dirty_log(kvm, &iter,
1232 new_spte)) {
1233 /*
1234 * The iter must explicitly re-read the SPTE because
1235 * the atomic cmpxchg failed.
1236 */
1237 iter.old_spte = READ_ONCE(*rcu_dereference(iter.sptep));
1238 goto retry;
1239 }
a6a0b05d 1240 spte_set = true;
a6a0b05d 1241 }
7cca2d0b
BG
1242
1243 rcu_read_unlock();
a6a0b05d
BG
1244 return spte_set;
1245}
1246
1247/*
1248 * Remove write access from all the SPTEs mapping GFNs in the memslot. Will
1249 * only affect leaf SPTEs down to min_level.
1250 * Returns true if an SPTE has been changed and the TLBs need to be flushed.
1251 */
269e9552
HM
1252bool kvm_tdp_mmu_wrprot_slot(struct kvm *kvm,
1253 const struct kvm_memory_slot *slot, int min_level)
a6a0b05d
BG
1254{
1255 struct kvm_mmu_page *root;
a6a0b05d
BG
1256 bool spte_set = false;
1257
24ae4cfa 1258 lockdep_assert_held_read(&kvm->mmu_lock);
a6a0b05d 1259
24ae4cfa 1260 for_each_tdp_mmu_root_yield_safe(kvm, root, slot->as_id, true)
a6a0b05d
BG
1261 spte_set |= wrprot_gfn_range(kvm, root, slot->base_gfn,
1262 slot->base_gfn + slot->npages, min_level);
a6a0b05d
BG
1263
1264 return spte_set;
1265}
1266
1267/*
1268 * Clear the dirty status of all the SPTEs mapping GFNs in the memslot. If
1269 * AD bits are enabled, this will involve clearing the dirty bit on each SPTE.
1270 * If AD bits are not enabled, this will require clearing the writable bit on
1271 * each SPTE. Returns true if an SPTE has been changed and the TLBs need to
1272 * be flushed.
1273 */
1274static bool clear_dirty_gfn_range(struct kvm *kvm, struct kvm_mmu_page *root,
1275 gfn_t start, gfn_t end)
1276{
1277 struct tdp_iter iter;
1278 u64 new_spte;
1279 bool spte_set = false;
1280
7cca2d0b
BG
1281 rcu_read_lock();
1282
a6a0b05d 1283 tdp_root_for_each_leaf_pte(iter, root, start, end) {
24ae4cfa
BG
1284retry:
1285 if (tdp_mmu_iter_cond_resched(kvm, &iter, false, true))
1af4a960
BG
1286 continue;
1287
a6a0b05d
BG
1288 if (spte_ad_need_write_protect(iter.old_spte)) {
1289 if (is_writable_pte(iter.old_spte))
1290 new_spte = iter.old_spte & ~PT_WRITABLE_MASK;
1291 else
1292 continue;
1293 } else {
1294 if (iter.old_spte & shadow_dirty_mask)
1295 new_spte = iter.old_spte & ~shadow_dirty_mask;
1296 else
1297 continue;
1298 }
1299
24ae4cfa
BG
1300 if (!tdp_mmu_set_spte_atomic_no_dirty_log(kvm, &iter,
1301 new_spte)) {
1302 /*
1303 * The iter must explicitly re-read the SPTE because
1304 * the atomic cmpxchg failed.
1305 */
1306 iter.old_spte = READ_ONCE(*rcu_dereference(iter.sptep));
1307 goto retry;
1308 }
a6a0b05d 1309 spte_set = true;
a6a0b05d 1310 }
7cca2d0b
BG
1311
1312 rcu_read_unlock();
a6a0b05d
BG
1313 return spte_set;
1314}
1315
1316/*
1317 * Clear the dirty status of all the SPTEs mapping GFNs in the memslot. If
1318 * AD bits are enabled, this will involve clearing the dirty bit on each SPTE.
1319 * If AD bits are not enabled, this will require clearing the writable bit on
1320 * each SPTE. Returns true if an SPTE has been changed and the TLBs need to
1321 * be flushed.
1322 */
269e9552
HM
1323bool kvm_tdp_mmu_clear_dirty_slot(struct kvm *kvm,
1324 const struct kvm_memory_slot *slot)
a6a0b05d
BG
1325{
1326 struct kvm_mmu_page *root;
a6a0b05d
BG
1327 bool spte_set = false;
1328
24ae4cfa 1329 lockdep_assert_held_read(&kvm->mmu_lock);
a6a0b05d 1330
24ae4cfa 1331 for_each_tdp_mmu_root_yield_safe(kvm, root, slot->as_id, true)
a6a0b05d
BG
1332 spte_set |= clear_dirty_gfn_range(kvm, root, slot->base_gfn,
1333 slot->base_gfn + slot->npages);
a6a0b05d
BG
1334
1335 return spte_set;
1336}
1337
1338/*
1339 * Clears the dirty status of all the 4k SPTEs mapping GFNs for which a bit is
1340 * set in mask, starting at gfn. The given memslot is expected to contain all
1341 * the GFNs represented by set bits in the mask. If AD bits are enabled,
1342 * clearing the dirty status will involve clearing the dirty bit on each SPTE
1343 * or, if AD bits are not enabled, clearing the writable bit on each SPTE.
1344 */
1345static void clear_dirty_pt_masked(struct kvm *kvm, struct kvm_mmu_page *root,
1346 gfn_t gfn, unsigned long mask, bool wrprot)
1347{
1348 struct tdp_iter iter;
1349 u64 new_spte;
1350
7cca2d0b
BG
1351 rcu_read_lock();
1352
a6a0b05d
BG
1353 tdp_root_for_each_leaf_pte(iter, root, gfn + __ffs(mask),
1354 gfn + BITS_PER_LONG) {
1355 if (!mask)
1356 break;
1357
1358 if (iter.level > PG_LEVEL_4K ||
1359 !(mask & (1UL << (iter.gfn - gfn))))
1360 continue;
1361
f1b3b06a
BG
1362 mask &= ~(1UL << (iter.gfn - gfn));
1363
a6a0b05d
BG
1364 if (wrprot || spte_ad_need_write_protect(iter.old_spte)) {
1365 if (is_writable_pte(iter.old_spte))
1366 new_spte = iter.old_spte & ~PT_WRITABLE_MASK;
1367 else
1368 continue;
1369 } else {
1370 if (iter.old_spte & shadow_dirty_mask)
1371 new_spte = iter.old_spte & ~shadow_dirty_mask;
1372 else
1373 continue;
1374 }
1375
1376 tdp_mmu_set_spte_no_dirty_log(kvm, &iter, new_spte);
a6a0b05d 1377 }
7cca2d0b
BG
1378
1379 rcu_read_unlock();
a6a0b05d
BG
1380}
1381
1382/*
1383 * Clears the dirty status of all the 4k SPTEs mapping GFNs for which a bit is
1384 * set in mask, starting at gfn. The given memslot is expected to contain all
1385 * the GFNs represented by set bits in the mask. If AD bits are enabled,
1386 * clearing the dirty status will involve clearing the dirty bit on each SPTE
1387 * or, if AD bits are not enabled, clearing the writable bit on each SPTE.
1388 */
1389void kvm_tdp_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1390 struct kvm_memory_slot *slot,
1391 gfn_t gfn, unsigned long mask,
1392 bool wrprot)
1393{
1394 struct kvm_mmu_page *root;
a6a0b05d 1395
531810ca 1396 lockdep_assert_held_write(&kvm->mmu_lock);
a3f15bda 1397 for_each_tdp_mmu_root(kvm, root, slot->as_id)
a6a0b05d 1398 clear_dirty_pt_masked(kvm, root, gfn, mask, wrprot);
a6a0b05d
BG
1399}
1400
14881998 1401/*
87aa9ec9
BG
1402 * Clear leaf entries which could be replaced by large mappings, for
1403 * GFNs within the slot.
14881998 1404 */
af95b53e 1405static bool zap_collapsible_spte_range(struct kvm *kvm,
14881998 1406 struct kvm_mmu_page *root,
8ca6f063 1407 const struct kvm_memory_slot *slot,
af95b53e 1408 bool flush)
14881998 1409{
9eba50f8
SC
1410 gfn_t start = slot->base_gfn;
1411 gfn_t end = start + slot->npages;
14881998
BG
1412 struct tdp_iter iter;
1413 kvm_pfn_t pfn;
14881998 1414
7cca2d0b
BG
1415 rcu_read_lock();
1416
14881998 1417 tdp_root_for_each_pte(iter, root, start, end) {
2db6f772
BG
1418retry:
1419 if (tdp_mmu_iter_cond_resched(kvm, &iter, flush, true)) {
af95b53e 1420 flush = false;
1af4a960
BG
1421 continue;
1422 }
1423
14881998 1424 if (!is_shadow_present_pte(iter.old_spte) ||
87aa9ec9 1425 !is_last_spte(iter.old_spte, iter.level))
14881998
BG
1426 continue;
1427
1428 pfn = spte_to_pfn(iter.old_spte);
1429 if (kvm_is_reserved_pfn(pfn) ||
9eba50f8
SC
1430 iter.level >= kvm_mmu_max_mapping_level(kvm, slot, iter.gfn,
1431 pfn, PG_LEVEL_NUM))
14881998
BG
1432 continue;
1433
2db6f772
BG
1434 if (!tdp_mmu_zap_spte_atomic(kvm, &iter)) {
1435 /*
1436 * The iter must explicitly re-read the SPTE because
1437 * the atomic cmpxchg failed.
1438 */
1439 iter.old_spte = READ_ONCE(*rcu_dereference(iter.sptep));
1440 goto retry;
1441 }
af95b53e 1442 flush = true;
14881998
BG
1443 }
1444
7cca2d0b 1445 rcu_read_unlock();
af95b53e
SC
1446
1447 return flush;
14881998
BG
1448}
1449
1450/*
1451 * Clear non-leaf entries (and free associated page tables) which could
1452 * be replaced by large mappings, for GFNs within the slot.
1453 */
142ccde1 1454bool kvm_tdp_mmu_zap_collapsible_sptes(struct kvm *kvm,
8ca6f063
BG
1455 const struct kvm_memory_slot *slot,
1456 bool flush)
14881998
BG
1457{
1458 struct kvm_mmu_page *root;
14881998 1459
2db6f772 1460 lockdep_assert_held_read(&kvm->mmu_lock);
14881998 1461
2db6f772 1462 for_each_tdp_mmu_root_yield_safe(kvm, root, slot->as_id, true)
af95b53e 1463 flush = zap_collapsible_spte_range(kvm, root, slot, flush);
af95b53e 1464
142ccde1 1465 return flush;
14881998 1466}
46044f72
BG
1467
1468/*
1469 * Removes write access on the last level SPTE mapping this GFN and unsets the
5fc3424f 1470 * MMU-writable bit to ensure future writes continue to be intercepted.
46044f72
BG
1471 * Returns true if an SPTE was set and a TLB flush is needed.
1472 */
1473static bool write_protect_gfn(struct kvm *kvm, struct kvm_mmu_page *root,
3ad93562 1474 gfn_t gfn, int min_level)
46044f72
BG
1475{
1476 struct tdp_iter iter;
1477 u64 new_spte;
1478 bool spte_set = false;
1479
3ad93562
KZ
1480 BUG_ON(min_level > KVM_MAX_HUGEPAGE_LEVEL);
1481
7cca2d0b
BG
1482 rcu_read_lock();
1483
3ad93562
KZ
1484 for_each_tdp_pte_min_level(iter, root->spt, root->role.level,
1485 min_level, gfn, gfn + 1) {
1486 if (!is_shadow_present_pte(iter.old_spte) ||
1487 !is_last_spte(iter.old_spte, iter.level))
1488 continue;
1489
46044f72
BG
1490 if (!is_writable_pte(iter.old_spte))
1491 break;
1492
1493 new_spte = iter.old_spte &
5fc3424f 1494 ~(PT_WRITABLE_MASK | shadow_mmu_writable_mask);
46044f72
BG
1495
1496 tdp_mmu_set_spte(kvm, &iter, new_spte);
1497 spte_set = true;
1498 }
1499
7cca2d0b
BG
1500 rcu_read_unlock();
1501
46044f72
BG
1502 return spte_set;
1503}
1504
1505/*
1506 * Removes write access on the last level SPTE mapping this GFN and unsets the
5fc3424f 1507 * MMU-writable bit to ensure future writes continue to be intercepted.
46044f72
BG
1508 * Returns true if an SPTE was set and a TLB flush is needed.
1509 */
1510bool kvm_tdp_mmu_write_protect_gfn(struct kvm *kvm,
3ad93562
KZ
1511 struct kvm_memory_slot *slot, gfn_t gfn,
1512 int min_level)
46044f72
BG
1513{
1514 struct kvm_mmu_page *root;
46044f72
BG
1515 bool spte_set = false;
1516
531810ca 1517 lockdep_assert_held_write(&kvm->mmu_lock);
a3f15bda 1518 for_each_tdp_mmu_root(kvm, root, slot->as_id)
3ad93562 1519 spte_set |= write_protect_gfn(kvm, root, gfn, min_level);
a3f15bda 1520
46044f72
BG
1521 return spte_set;
1522}
1523
95fb5b02
BG
1524/*
1525 * Return the level of the lowest level SPTE added to sptes.
1526 * That SPTE may be non-present.
c5c8c7c5
DM
1527 *
1528 * Must be called between kvm_tdp_mmu_walk_lockless_{begin,end}.
95fb5b02 1529 */
39b4d43e
SC
1530int kvm_tdp_mmu_get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes,
1531 int *root_level)
95fb5b02
BG
1532{
1533 struct tdp_iter iter;
1534 struct kvm_mmu *mmu = vcpu->arch.mmu;
95fb5b02 1535 gfn_t gfn = addr >> PAGE_SHIFT;
2aa07893 1536 int leaf = -1;
95fb5b02 1537
39b4d43e 1538 *root_level = vcpu->arch.mmu->shadow_root_level;
95fb5b02
BG
1539
1540 tdp_mmu_for_each_pte(iter, mmu, gfn, gfn + 1) {
1541 leaf = iter.level;
dde81f94 1542 sptes[leaf] = iter.old_spte;
95fb5b02
BG
1543 }
1544
1545 return leaf;
1546}
6e8eb206
DM
1547
1548/*
1549 * Returns the last level spte pointer of the shadow page walk for the given
1550 * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
1551 * walk could be performed, returns NULL and *spte does not contain valid data.
1552 *
1553 * Contract:
1554 * - Must be called between kvm_tdp_mmu_walk_lockless_{begin,end}.
1555 * - The returned sptep must not be used after kvm_tdp_mmu_walk_lockless_end.
1556 *
1557 * WARNING: This function is only intended to be called during fast_page_fault.
1558 */
1559u64 *kvm_tdp_mmu_fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, u64 addr,
1560 u64 *spte)
1561{
1562 struct tdp_iter iter;
1563 struct kvm_mmu *mmu = vcpu->arch.mmu;
1564 gfn_t gfn = addr >> PAGE_SHIFT;
1565 tdp_ptep_t sptep = NULL;
1566
1567 tdp_mmu_for_each_pte(iter, mmu, gfn, gfn + 1) {
1568 *spte = iter.old_spte;
1569 sptep = iter.sptep;
1570 }
1571
1572 /*
1573 * Perform the rcu_dereference to get the raw spte pointer value since
1574 * we are passing it up to fast_page_fault, which is shared with the
1575 * legacy MMU and thus does not retain the TDP MMU-specific __rcu
1576 * annotation.
1577 *
1578 * This is safe since fast_page_fault obeys the contracts of this
1579 * function as well as all TDP MMU contracts around modifying SPTEs
1580 * outside of mmu_lock.
1581 */
1582 return rcu_dereference(sptep);
1583}