xref: /linux/arch/s390/kvm/gmap/gmap.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Guest memory management for KVM/s390
4  *
5  * Copyright IBM Corp. 2008, 2020, 2024
6  *
7  *    Author(s): Claudio Imbrenda <imbrenda@linux.ibm.com>
8  *               Martin Schwidefsky <schwidefsky@de.ibm.com>
9  *               David Hildenbrand <david@redhat.com>
10  *               Janosch Frank <frankja@linux.ibm.com>
11  */
12 
13 #include <linux/compiler.h>
14 #include <linux/kvm.h>
15 #include <linux/kvm_host.h>
16 #include <linux/pgtable.h>
17 #include <linux/pagemap.h>
18 #include <asm/lowcore.h>
19 #include <asm/uv.h>
20 #include <asm/gmap_helpers.h>
21 
22 #include "dat.h"
23 #include "gmap.h"
24 #include "s390.h"
25 #include "faultin.h"
26 
27 static int gmap_limit_to_type(gfn_t limit)
28 {
29 	if (!limit)
30 		return TABLE_TYPE_REGION1;
31 	if (limit <= _REGION3_SIZE >> PAGE_SHIFT)
32 		return TABLE_TYPE_SEGMENT;
33 	if (limit <= _REGION2_SIZE >> PAGE_SHIFT)
34 		return TABLE_TYPE_REGION3;
35 	if (limit <= _REGION1_SIZE >> PAGE_SHIFT)
36 		return TABLE_TYPE_REGION2;
37 	return TABLE_TYPE_REGION1;
38 }
39 
40 /**
41  * gmap_new() - Allocate and initialize a guest address space.
42  * @kvm: The kvm owning the guest.
43  * @limit: Maximum address of the gmap address space.
44  *
45  * Return: A guest address space structure.
46  */
47 struct gmap *gmap_new(struct kvm *kvm, gfn_t limit)
48 {
49 	struct crst_table *table;
50 	struct gmap *gmap;
51 	int type;
52 
53 	type = gmap_limit_to_type(limit);
54 
55 	gmap = kzalloc_obj(*gmap, GFP_KERNEL_ACCOUNT);
56 	if (!gmap)
57 		return NULL;
58 	INIT_LIST_HEAD(&gmap->children);
59 	INIT_LIST_HEAD(&gmap->list);
60 	INIT_LIST_HEAD(&gmap->scb_users);
61 	INIT_RADIX_TREE(&gmap->host_to_rmap, GFP_KVM_S390_MMU_CACHE);
62 	spin_lock_init(&gmap->children_lock);
63 	spin_lock_init(&gmap->host_to_rmap_lock);
64 	refcount_set(&gmap->refcount, 1);
65 
66 	table = dat_alloc_crst_sleepable(_CRSTE_EMPTY(type).val);
67 	if (!table) {
68 		kfree(gmap);
69 		return NULL;
70 	}
71 
72 	gmap->asce.val = __pa(table);
73 	gmap->asce.dt = type;
74 	gmap->asce.tl = _ASCE_TABLE_LENGTH;
75 	gmap->asce.x = 1;
76 	gmap->asce.p = 1;
77 	gmap->asce.s = 1;
78 	gmap->kvm = kvm;
79 	set_bit(GMAP_FLAG_OWNS_PAGETABLES, &gmap->flags);
80 
81 	return gmap;
82 }
83 
84 static void gmap_add_child(struct gmap *parent, struct gmap *child)
85 {
86 	KVM_BUG_ON(is_ucontrol(parent) && parent->parent, parent->kvm);
87 	KVM_BUG_ON(is_ucontrol(parent) && !owns_page_tables(parent), parent->kvm);
88 	KVM_BUG_ON(!refcount_read(&child->refcount), parent->kvm);
89 	lockdep_assert_held(&parent->children_lock);
90 
91 	child->parent = parent;
92 
93 	if (is_ucontrol(parent))
94 		set_bit(GMAP_FLAG_IS_UCONTROL, &child->flags);
95 	else
96 		clear_bit(GMAP_FLAG_IS_UCONTROL, &child->flags);
97 
98 	if (test_bit(GMAP_FLAG_ALLOW_HPAGE_1M, &parent->flags))
99 		set_bit(GMAP_FLAG_ALLOW_HPAGE_1M, &child->flags);
100 	else
101 		clear_bit(GMAP_FLAG_ALLOW_HPAGE_1M, &child->flags);
102 
103 	if (test_bit(GMAP_FLAG_ALLOW_HPAGE_2G, &parent->flags))
104 		set_bit(GMAP_FLAG_ALLOW_HPAGE_2G, &child->flags);
105 	else
106 		clear_bit(GMAP_FLAG_ALLOW_HPAGE_2G, &child->flags);
107 
108 	if (kvm_is_ucontrol(parent->kvm))
109 		clear_bit(GMAP_FLAG_OWNS_PAGETABLES, &child->flags);
110 	list_add(&child->list, &parent->children);
111 }
112 
113 struct gmap *gmap_new_child(struct gmap *parent, gfn_t limit)
114 {
115 	struct gmap *res;
116 
117 	lockdep_assert_not_held(&parent->children_lock);
118 	res = gmap_new(parent->kvm, limit);
119 	if (res) {
120 		scoped_guard(spinlock, &parent->children_lock)
121 			gmap_add_child(parent, res);
122 	}
123 	return res;
124 }
125 
126 int gmap_set_limit(struct gmap *gmap, gfn_t limit)
127 {
128 	struct kvm_s390_mmu_cache *mc __free(kvm_s390_mmu_cache) = NULL;
129 	int rc, type;
130 
131 	type = gmap_limit_to_type(limit);
132 
133 	mc = kvm_s390_new_mmu_cache();
134 	if (!mc)
135 		return -ENOMEM;
136 
137 	do {
138 		rc = kvm_s390_mmu_cache_topup(mc);
139 		if (rc)
140 			return rc;
141 		scoped_guard(write_lock, &gmap->kvm->mmu_lock)
142 			rc = dat_set_asce_limit(mc, &gmap->asce, type);
143 	} while (rc == -ENOMEM);
144 
145 	return 0;
146 }
147 
148 static void gmap_rmap_radix_tree_free(struct radix_tree_root *root)
149 {
150 	struct vsie_rmap *rmap, *rnext, *head;
151 	struct radix_tree_iter iter;
152 	unsigned long indices[16];
153 	unsigned long index;
154 	void __rcu **slot;
155 	int i, nr;
156 
157 	/* A radix tree is freed by deleting all of its entries */
158 	index = 0;
159 	do {
160 		nr = 0;
161 		radix_tree_for_each_slot(slot, root, &iter, index) {
162 			indices[nr] = iter.index;
163 			if (++nr == 16)
164 				break;
165 		}
166 		for (i = 0; i < nr; i++) {
167 			index = indices[i];
168 			head = radix_tree_delete(root, index);
169 			gmap_for_each_rmap_safe(rmap, rnext, head)
170 				kfree(rmap);
171 		}
172 	} while (nr > 0);
173 }
174 
175 void gmap_remove_child(struct gmap *child)
176 {
177 	if (KVM_BUG_ON(!child->parent, child->kvm))
178 		return;
179 	lockdep_assert_held(&child->parent->children_lock);
180 
181 	list_del(&child->list);
182 	child->parent = NULL;
183 	child->invalidated = true;
184 }
185 
186 /**
187  * gmap_dispose() - Remove and free a guest address space and its children.
188  * @gmap: Pointer to the guest address space structure.
189  */
190 void gmap_dispose(struct gmap *gmap)
191 {
192 	/* The gmap must have been removed from the parent beforehands */
193 	KVM_BUG_ON(gmap->parent, gmap->kvm);
194 	/* All children of this gmap must have been removed beforehands */
195 	KVM_BUG_ON(!list_empty(&gmap->children), gmap->kvm);
196 	/* No VSIE shadow block is allowed to use this gmap */
197 	KVM_BUG_ON(!list_empty(&gmap->scb_users), gmap->kvm);
198 	/* The ASCE must be valid */
199 	KVM_BUG_ON(!gmap->asce.val, gmap->kvm);
200 	/* The refcount must be 0 */
201 	KVM_BUG_ON(refcount_read(&gmap->refcount), gmap->kvm);
202 
203 	/* Flush tlb of all gmaps */
204 	asce_flush_tlb(gmap->asce);
205 
206 	/* Free all DAT tables. */
207 	dat_free_level(dereference_asce(gmap->asce), owns_page_tables(gmap));
208 
209 	/* Free additional data for a shadow gmap */
210 	if (is_shadow(gmap))
211 		gmap_rmap_radix_tree_free(&gmap->host_to_rmap);
212 
213 	kfree(gmap);
214 }
215 
216 /**
217  * s390_replace_asce() - Try to replace the current ASCE of a gmap with a copy.
218  * @gmap: The gmap whose ASCE needs to be replaced.
219  *
220  * If the ASCE is a SEGMENT type then this function will return -EINVAL,
221  * otherwise the pointers in the host_to_guest radix tree will keep pointing
222  * to the wrong pages, causing use-after-free and memory corruption.
223  * If the allocation of the new top level page table fails, the ASCE is not
224  * replaced.
225  * In any case, the old ASCE is always removed from the gmap CRST list.
226  * Therefore the caller has to make sure to save a pointer to it
227  * beforehand, unless a leak is actually intended.
228  *
229  * Return: 0 in case of success, -EINVAL if the ASCE is segment type ASCE,
230  *         -ENOMEM if runinng out of memory.
231  */
232 int s390_replace_asce(struct gmap *gmap)
233 {
234 	struct crst_table *table;
235 	union asce asce;
236 
237 	/* Replacing segment type ASCEs would cause serious issues */
238 	if (gmap->asce.dt == ASCE_TYPE_SEGMENT)
239 		return -EINVAL;
240 
241 	table = dat_alloc_crst_sleepable(0);
242 	if (!table)
243 		return -ENOMEM;
244 	memcpy(table, dereference_asce(gmap->asce), sizeof(*table));
245 
246 	/* Set new table origin while preserving existing ASCE control bits */
247 	asce = gmap->asce;
248 	asce.rsto = virt_to_pfn(table);
249 	WRITE_ONCE(gmap->asce, asce);
250 
251 	return 0;
252 }
253 
254 #if KVM_S390_MANAGES_S390_GUEST
255 static inline bool kvm_s390_is_in_sie(struct kvm_vcpu *vcpu)
256 {
257 	return vcpu->arch.sie_block->prog0c & PROG_IN_SIE;
258 }
259 
260 bool _gmap_unmap_prefix(struct gmap *gmap, gfn_t gfn, gfn_t end, bool hint)
261 {
262 	struct kvm *kvm = gmap->kvm;
263 	struct kvm_vcpu *vcpu;
264 	gfn_t prefix_gfn;
265 	unsigned long i;
266 
267 	if (is_shadow(gmap))
268 		return false;
269 	kvm_for_each_vcpu(i, vcpu, kvm) {
270 		/* Match against both prefix pages */
271 		prefix_gfn = gpa_to_gfn(kvm_s390_get_prefix(vcpu));
272 		if (prefix_gfn < end && gfn <= prefix_gfn + 1) {
273 			if (hint && kvm_s390_is_in_sie(vcpu))
274 				return false;
275 			VCPU_EVENT(vcpu, 2, "gmap notifier for %llx-%llx",
276 				   gfn_to_gpa(gfn), gfn_to_gpa(end));
277 			kvm_s390_sync_request(KVM_REQ_REFRESH_GUEST_PREFIX, vcpu);
278 		}
279 	}
280 	return true;
281 }
282 #endif /* KVM_S390_MANAGES_S390_GUEST */
283 
284 struct clear_young_pte_priv {
285 	struct gmap *gmap;
286 	bool young;
287 };
288 
289 static long gmap_clear_young_pte(union pte *ptep, gfn_t gfn, gfn_t end, struct dat_walk *walk)
290 {
291 	struct clear_young_pte_priv *p = walk->priv;
292 	union pgste pgste;
293 	union pte pte, new;
294 
295 	pte = READ_ONCE(*ptep);
296 
297 	if (!pte.s.pr || (!pte.s.y && pte.h.i))
298 		return 0;
299 
300 	pgste = pgste_get_lock(ptep);
301 	if (!pgste.prefix_notif || gmap_mkold_prefix(p->gmap, gfn, end)) {
302 		new = pte;
303 		new.h.i = 1;
304 		new.s.y = 0;
305 		if ((new.s.d || !new.h.p) && !new.s.s)
306 			folio_set_dirty(pfn_folio(pte.h.pfra));
307 		new.s.d = 0;
308 		new.h.p = 1;
309 
310 		pgste.prefix_notif = 0;
311 		pgste = __dat_ptep_xchg(ptep, pgste, new, gfn, walk->asce, uses_skeys(p->gmap));
312 	}
313 	p->young = 1;
314 	pgste_set_unlock(ptep, pgste);
315 	return 0;
316 }
317 
318 static long gmap_clear_young_crste(union crste *crstep, gfn_t gfn, gfn_t end, struct dat_walk *walk)
319 {
320 	struct clear_young_pte_priv *priv = walk->priv;
321 	union crste crste, new;
322 
323 	do {
324 		crste = READ_ONCE(*crstep);
325 
326 		if (!crste.h.fc)
327 			return 0;
328 		if (!crste.s.fc1.y && crste.h.i)
329 			return 0;
330 		if (crste_prefix(crste) && !gmap_mkold_prefix(priv->gmap, gfn, end))
331 			break;
332 
333 		new = crste;
334 		new.h.i = 1;
335 		new.s.fc1.y = 0;
336 		new.s.fc1.prefix_notif = 0;
337 		if ((new.s.fc1.d || !new.h.p) && !new.s.fc1.s)
338 			folio_set_dirty(phys_to_folio(crste_origin_large(crste)));
339 		new.s.fc1.d = 0;
340 		new.h.p = 1;
341 	} while (!dat_crstep_xchg_atomic(crstep, crste, new, gfn, walk->asce));
342 
343 	priv->young = 1;
344 	return 0;
345 }
346 
347 /**
348  * gmap_age_gfn() - Clear young.
349  * @gmap: The guest gmap.
350  * @start: The first gfn to test.
351  * @end: The gfn after the last one to test.
352  *
353  * Context: Called with the kvm mmu write lock held.
354  * Return: 1 if any page in the given range was young, otherwise 0.
355  */
356 bool gmap_age_gfn(struct gmap *gmap, gfn_t start, gfn_t end)
357 {
358 	const struct dat_walk_ops ops = {
359 		.pte_entry = gmap_clear_young_pte,
360 		.pmd_entry = gmap_clear_young_crste,
361 		.pud_entry = gmap_clear_young_crste,
362 	};
363 	struct clear_young_pte_priv priv = {
364 		.gmap = gmap,
365 		.young = false,
366 	};
367 
368 	_dat_walk_gfn_range(start, end, gmap->asce, &ops, 0, &priv);
369 
370 	return priv.young;
371 }
372 
373 struct gmap_unmap_priv {
374 	struct gmap *gmap;
375 	struct kvm_memory_slot *slot;
376 };
377 
378 static long _gmap_unmap_pte(union pte *ptep, gfn_t gfn, gfn_t next, struct dat_walk *w)
379 {
380 	struct gmap_unmap_priv *priv = w->priv;
381 	struct folio *folio = NULL;
382 	unsigned long vmaddr;
383 	union pgste pgste;
384 
385 	pgste = pgste_get_lock(ptep);
386 	if (ptep->s.pr && pgste.usage == PGSTE_GPS_USAGE_UNUSED) {
387 		vmaddr = __gfn_to_hva_memslot(priv->slot, gfn);
388 		gmap_helper_try_set_pte_unused(priv->gmap->kvm->mm, vmaddr);
389 	}
390 	if (ptep->s.pr && test_bit(GMAP_FLAG_EXPORT_ON_UNMAP, &priv->gmap->flags))
391 		folio = pfn_folio(ptep->h.pfra);
392 	pgste = gmap_ptep_xchg(priv->gmap, ptep, _PTE_EMPTY, pgste, gfn);
393 	pgste_set_unlock(ptep, pgste);
394 	if (folio)
395 		uv_convert_from_secure_folio(folio);
396 
397 	return 0;
398 }
399 
400 static long _gmap_unmap_crste(union crste *crstep, gfn_t gfn, gfn_t next, struct dat_walk *walk)
401 {
402 	struct gmap_unmap_priv *priv = walk->priv;
403 	struct folio *folio = NULL;
404 	union crste old = *crstep;
405 	bool ok;
406 
407 	if (!old.h.fc)
408 		return 0;
409 
410 	if (old.s.fc1.pr && test_bit(GMAP_FLAG_EXPORT_ON_UNMAP, &priv->gmap->flags))
411 		folio = phys_to_folio(crste_origin_large(old));
412 	/*
413 	 * No races should happen because kvm->mmu_lock is held in write mode,
414 	 * but the unmap operation could have triggered an unshadow, which
415 	 * causes gmap_crstep_xchg_atomic() to return false and clear the
416 	 * vsie_notif bit. Allow the operation to fail once, if the old crste
417 	 * had the vsie_notif bit set. A second failure is not allowed, for
418 	 * the reasons above.
419 	 */
420 	ok = gmap_crstep_xchg_atomic(priv->gmap, crstep, old, _CRSTE_EMPTY(old.h.tt), gfn);
421 	if (!ok) {
422 		KVM_BUG_ON(!old.s.fc1.vsie_notif, priv->gmap->kvm);
423 		old.s.fc1.vsie_notif = 0;
424 		ok = gmap_crstep_xchg_atomic(priv->gmap, crstep, old, _CRSTE_EMPTY(old.h.tt), gfn);
425 		KVM_BUG_ON(!ok, priv->gmap->kvm);
426 	}
427 	if (folio)
428 		uv_convert_from_secure_folio(folio);
429 
430 	return 0;
431 }
432 
433 /**
434  * gmap_unmap_gfn_range() - Unmap a range of guest addresses.
435  * @gmap: The gmap to act on.
436  * @slot: The memslot in which the range is located.
437  * @start: The first gfn to unmap.
438  * @end: The gfn after the last one to unmap.
439  *
440  * Context: Called with the kvm mmu write lock held.
441  * Return: false
442  */
443 bool gmap_unmap_gfn_range(struct gmap *gmap, struct kvm_memory_slot *slot, gfn_t start, gfn_t end)
444 {
445 	const struct dat_walk_ops ops = {
446 		.pte_entry = _gmap_unmap_pte,
447 		.pmd_entry = _gmap_unmap_crste,
448 		.pud_entry = _gmap_unmap_crste,
449 	};
450 	struct gmap_unmap_priv priv = {
451 		.gmap = gmap,
452 		.slot = slot,
453 	};
454 
455 	lockdep_assert_held_write(&gmap->kvm->mmu_lock);
456 
457 	_dat_walk_gfn_range(start, end, gmap->asce, &ops, 0, &priv);
458 	return false;
459 }
460 
461 static union pgste __pte_test_and_clear_softdirty(union pte *ptep, union pgste pgste, gfn_t gfn,
462 						  struct gmap *gmap)
463 {
464 	union pte pte = READ_ONCE(*ptep);
465 
466 	if (!pte.s.pr || (pte.h.p && !pte.s.sd))
467 		return pgste;
468 
469 	/*
470 	 * If this page contains one or more prefixes of vCPUS that are currently
471 	 * running, do not reset the protection, leave it marked as dirty.
472 	 */
473 	if (!pgste.prefix_notif || gmap_mkold_prefix(gmap, gfn, gfn + 1)) {
474 		pte.h.p = 1;
475 		pte.s.sd = 0;
476 		pgste = gmap_ptep_xchg(gmap, ptep, pte, pgste, gfn);
477 	}
478 
479 	mark_page_dirty(gmap->kvm, gfn);
480 
481 	return pgste;
482 }
483 
484 static long _pte_test_and_clear_softdirty(union pte *ptep, gfn_t gfn, gfn_t end,
485 					  struct dat_walk *walk)
486 {
487 	struct gmap *gmap = walk->priv;
488 	union pgste pgste;
489 
490 	pgste = pgste_get_lock(ptep);
491 	pgste = __pte_test_and_clear_softdirty(ptep, pgste, gfn, gmap);
492 	pgste_set_unlock(ptep, pgste);
493 	return 0;
494 }
495 
496 static long _crste_test_and_clear_softdirty(union crste *table, gfn_t gfn, gfn_t end,
497 					    struct dat_walk *walk)
498 {
499 	struct gmap *gmap = walk->priv;
500 	union crste crste, new;
501 
502 	if (fatal_signal_pending(current))
503 		return 1;
504 	do {
505 		crste = READ_ONCE(*table);
506 		if (!crste.h.fc)
507 			return 0;
508 		if (crste.h.p && !crste.s.fc1.sd)
509 			return 0;
510 
511 		/*
512 		 * If this large page contains one or more prefixes of vCPUs that are
513 		 * currently running, do not reset the protection, leave it marked as
514 		 * dirty.
515 		 */
516 		if (crste.s.fc1.prefix_notif && !gmap_mkold_prefix(gmap, gfn, end))
517 			break;
518 		new = crste;
519 		new.h.p = 1;
520 		new.s.fc1.sd = 0;
521 	} while (!gmap_crstep_xchg_atomic(gmap, table, crste, new, gfn));
522 
523 	for ( ; gfn < end; gfn++)
524 		mark_page_dirty(gmap->kvm, gfn);
525 
526 	return 0;
527 }
528 
529 void gmap_sync_dirty_log(struct gmap *gmap, gfn_t start, gfn_t end)
530 {
531 	const struct dat_walk_ops walk_ops = {
532 		.pte_entry = _pte_test_and_clear_softdirty,
533 		.pmd_entry = _crste_test_and_clear_softdirty,
534 		.pud_entry = _crste_test_and_clear_softdirty,
535 	};
536 
537 	lockdep_assert_held(&gmap->kvm->mmu_lock);
538 
539 	_dat_walk_gfn_range(start, end, gmap->asce, &walk_ops, 0, gmap);
540 }
541 
542 static int gmap_handle_minor_crste_fault(struct gmap *gmap, struct guest_fault *f)
543 {
544 	union crste newcrste, oldcrste = READ_ONCE(*f->crstep);
545 
546 	/* Somehow the crste is not large anymore, let the slow path deal with it. */
547 	if (!oldcrste.h.fc)
548 		return 1;
549 
550 	f->pfn = PHYS_PFN(large_crste_to_phys(oldcrste, f->gfn));
551 	f->writable = oldcrste.s.fc1.w;
552 
553 	f->crste_region3 = is_pud(oldcrste);
554 	/* Appropriate permissions already (race with another handler), nothing to do. */
555 	if (!oldcrste.h.i && !(f->write_attempt && oldcrste.h.p))
556 		return 0;
557 
558 	if (!f->write_attempt || oldcrste.s.fc1.w) {
559 		f->write_attempt |= oldcrste.s.fc1.w && oldcrste.s.fc1.d;
560 		newcrste = oldcrste;
561 		newcrste.h.i = 0;
562 		newcrste.s.fc1.y = 1;
563 		if (f->write_attempt) {
564 			newcrste.h.p = 0;
565 			newcrste.s.fc1.d = 1;
566 			newcrste.s.fc1.sd = 1;
567 		}
568 		/* In case of races, let the slow path deal with it. */
569 		return !gmap_crstep_xchg_atomic(gmap, f->crstep, oldcrste, newcrste, f->gfn);
570 	}
571 	/* Trying to write on a read-only page, let the slow path deal with it. */
572 	return 1;
573 }
574 
575 static int _gmap_handle_minor_pte_fault(struct gmap *gmap, union pgste *pgste,
576 					struct guest_fault *f)
577 {
578 	union pte newpte, oldpte = READ_ONCE(*f->ptep);
579 
580 	f->pfn = oldpte.h.pfra;
581 	f->writable = oldpte.s.w;
582 
583 	/* Appropriate permissions already (race with another handler), nothing to do. */
584 	if (!oldpte.h.i && !(f->write_attempt && oldpte.h.p))
585 		return 0;
586 	/* Trying to write on a read-only page, let the slow path deal with it. */
587 	if (!oldpte.s.pr || (f->write_attempt && !oldpte.s.w))
588 		return 1;
589 
590 	newpte = oldpte;
591 	newpte.h.i = 0;
592 	newpte.s.y = 1;
593 	if (f->write_attempt) {
594 		newpte.h.p = 0;
595 		newpte.s.d = 1;
596 		newpte.s.sd = 1;
597 	}
598 	*pgste = gmap_ptep_xchg(gmap, f->ptep, newpte, *pgste, f->gfn);
599 
600 	return 0;
601 }
602 
603 /**
604  * gmap_try_fixup_minor() -- Try to fixup a minor gmap fault.
605  * @gmap: The gmap whose fault needs to be resolved.
606  * @fault: Describes the fault that is being resolved.
607  *
608  * A minor fault is a fault that can be resolved quickly within gmap.
609  * The page is already mapped, the fault is only due to dirty/young tracking.
610  *
611  * Return: 0 in case of success, < 0 in case of error, > 0 if the fault could
612  *         not be resolved and needs to go through the slow path.
613  */
614 int gmap_try_fixup_minor(struct gmap *gmap, struct guest_fault *fault)
615 {
616 	union pgste pgste;
617 	int rc;
618 
619 	lockdep_assert_held(&gmap->kvm->mmu_lock);
620 
621 	rc = dat_entry_walk(NULL, fault->gfn, gmap->asce, DAT_WALK_LEAF, TABLE_TYPE_PAGE_TABLE,
622 			    &fault->crstep, &fault->ptep);
623 	/* If a PTE or a leaf CRSTE could not be reached, slow path. */
624 	if (rc)
625 		return 1;
626 
627 	if (fault->ptep) {
628 		pgste = pgste_get_lock(fault->ptep);
629 		rc = _gmap_handle_minor_pte_fault(gmap, &pgste, fault);
630 		if (!rc && fault->callback)
631 			fault->callback(fault);
632 		pgste_set_unlock(fault->ptep, pgste);
633 	} else {
634 		rc = gmap_handle_minor_crste_fault(gmap, fault);
635 		if (!rc && fault->callback)
636 			fault->callback(fault);
637 	}
638 	return rc;
639 }
640 
641 /**
642  * gmap_2g_allowed() - Check whether a 2G hugepage is allowed.
643  * @gmap: The gmap of the guest.
644  * @f: Describes the fault that is being resolved.
645  * @slot: The memslot the faulting address belongs to.
646  *
647  * The function checks whether the GMAP_FLAG_ALLOW_HPAGE_2G flag is set for
648  * @gmap, whether the offset of the address in the 2G virtual frame is the
649  * same as the offset in the physical 2G frame, and finally whether the whole
650  * 2G page would fit in the given memslot.
651  *
652  * Return: true if a 2G hugepage is allowed to back the faulting address, false
653  *         otherwise.
654  */
655 static inline bool gmap_2g_allowed(struct gmap *gmap, struct guest_fault *f,
656 				   struct kvm_memory_slot *slot)
657 {
658 	return test_bit(GMAP_FLAG_ALLOW_HPAGE_2G, &gmap->flags) &&
659 	       !((f->gfn ^ f->pfn) & ~_REGION3_FR_MASK) &&
660 	       slot->base_gfn <= ALIGN_DOWN(f->gfn, _PAGES_PER_REGION3) &&
661 	       slot->base_gfn + slot->npages >= ALIGN(f->gfn + 1, _PAGES_PER_REGION3);
662 }
663 
664 /**
665  * gmap_1m_allowed() - Check whether a 1M hugepage is allowed.
666  * @gmap: The gmap of the guest.
667  * @f: Describes the fault that is being resolved.
668  * @slot: The memslot the faulting address belongs to.
669  *
670  * The function checks whether the GMAP_FLAG_ALLOW_HPAGE_1M flag is set for
671  * @gmap, whether the offset of the address in the 1M virtual frame is the
672  * same as the offset in the physical 1M frame, and finally whether the whole
673  * 1M page would fit in the given memslot.
674  *
675  * Return: true if a 1M hugepage is allowed to back the faulting address, false
676  *         otherwise.
677  */
678 static inline bool gmap_1m_allowed(struct gmap *gmap, struct guest_fault *f,
679 				   struct kvm_memory_slot *slot)
680 {
681 	return test_bit(GMAP_FLAG_ALLOW_HPAGE_1M, &gmap->flags) &&
682 	       !((f->gfn ^ f->pfn) & ~_SEGMENT_FR_MASK) &&
683 	       slot->base_gfn <= ALIGN_DOWN(f->gfn, _PAGES_PER_SEGMENT) &&
684 	       slot->base_gfn + slot->npages >= ALIGN(f->gfn + 1, _PAGES_PER_SEGMENT);
685 }
686 
687 static int _gmap_link(struct kvm_s390_mmu_cache *mc, struct gmap *gmap, int level,
688 		      struct guest_fault *f)
689 {
690 	union crste oldval, newval;
691 	union pte newpte, oldpte;
692 	union pgste pgste;
693 	int rc = 0;
694 
695 	rc = dat_entry_walk(mc, f->gfn, gmap->asce, DAT_WALK_ALLOC_CONTINUE, level,
696 			    &f->crstep, &f->ptep);
697 	if (rc == -ENOMEM)
698 		return rc;
699 	if (KVM_BUG_ON(rc == -EINVAL, gmap->kvm))
700 		return rc;
701 	if (rc)
702 		return -EAGAIN;
703 	if (KVM_BUG_ON(get_level(f->crstep, f->ptep) > level, gmap->kvm))
704 		return -EINVAL;
705 
706 	if (f->ptep) {
707 		pgste = pgste_get_lock(f->ptep);
708 		oldpte = *f->ptep;
709 		newpte = _pte(f->pfn, f->writable, f->write_attempt | oldpte.s.d, !f->page);
710 		newpte.s.sd = oldpte.s.sd;
711 		oldpte.s.sd = 0;
712 		if (oldpte.val == _PTE_EMPTY.val || oldpte.h.pfra == f->pfn) {
713 			pgste = gmap_ptep_xchg(gmap, f->ptep, newpte, pgste, f->gfn);
714 			if (f->callback)
715 				f->callback(f);
716 		} else {
717 			rc = -EAGAIN;
718 		}
719 		pgste_set_unlock(f->ptep, pgste);
720 	} else {
721 		do {
722 			oldval = READ_ONCE(*f->crstep);
723 			newval = _crste_fc1(f->pfn, oldval.h.tt, f->writable,
724 					    f->write_attempt | oldval.s.fc1.d);
725 			newval.s.fc1.s = !f->page;
726 			newval.s.fc1.sd = oldval.s.fc1.sd;
727 			if (oldval.val != _CRSTE_EMPTY(oldval.h.tt).val &&
728 			    crste_origin_large(oldval) != crste_origin_large(newval))
729 				return -EAGAIN;
730 			f->crste_region3 = is_pud(newval);
731 		} while (!gmap_crstep_xchg_atomic(gmap, f->crstep, oldval, newval, f->gfn));
732 		if (f->callback)
733 			f->callback(f);
734 	}
735 
736 	return rc;
737 }
738 
739 int gmap_link(struct kvm_s390_mmu_cache *mc, struct gmap *gmap, struct guest_fault *f,
740 	      struct kvm_memory_slot *slot)
741 {
742 	unsigned int order;
743 	int level;
744 
745 	lockdep_assert_held(&gmap->kvm->mmu_lock);
746 
747 	level = TABLE_TYPE_PAGE_TABLE;
748 	if (f->page) {
749 		order = folio_order(page_folio(f->page));
750 		if (order >= get_order(_REGION3_SIZE) && gmap_2g_allowed(gmap, f, slot))
751 			level = TABLE_TYPE_REGION3;
752 		else if (order >= get_order(_SEGMENT_SIZE) && gmap_1m_allowed(gmap, f, slot))
753 			level = TABLE_TYPE_SEGMENT;
754 	}
755 	return _gmap_link(mc, gmap, level, f);
756 }
757 
758 static int gmap_ucas_map_one(struct kvm_s390_mmu_cache *mc, struct gmap *gmap,
759 			     gfn_t p_gfn, gfn_t c_gfn, bool force_alloc)
760 {
761 	union crste newcrste, oldcrste;
762 	struct page_table *pt;
763 	union crste *crstep;
764 	union pte *ptep;
765 	int rc;
766 
767 	if (force_alloc)
768 		rc = dat_entry_walk(mc, p_gfn, gmap->parent->asce, DAT_WALK_ALLOC,
769 				    TABLE_TYPE_PAGE_TABLE, &crstep, &ptep);
770 	else
771 		rc = dat_entry_walk(mc, p_gfn, gmap->parent->asce, DAT_WALK_ALLOC_CONTINUE,
772 				    TABLE_TYPE_SEGMENT, &crstep, &ptep);
773 	if (rc)
774 		return rc;
775 	if (!ptep) {
776 		newcrste = _crste_fc0(p_gfn, TABLE_TYPE_SEGMENT);
777 		newcrste.h.i = 1;
778 		newcrste.h.fc0.tl = 1;
779 	} else {
780 		pt = pte_table_start(ptep);
781 		dat_set_ptval(pt, PTVAL_VMADDR, p_gfn >> (_SEGMENT_SHIFT - PAGE_SHIFT));
782 		newcrste = _crste_fc0(virt_to_pfn(pt), TABLE_TYPE_SEGMENT);
783 	}
784 	rc = dat_entry_walk(mc, c_gfn, gmap->asce, DAT_WALK_ALLOC, TABLE_TYPE_SEGMENT,
785 			    &crstep, &ptep);
786 	if (rc)
787 		return rc;
788 	do {
789 		oldcrste = READ_ONCE(*crstep);
790 		if (oldcrste.val == newcrste.val)
791 			break;
792 	} while (!dat_crstep_xchg_atomic(crstep, oldcrste, newcrste, c_gfn, gmap->asce));
793 	return 0;
794 }
795 
796 static int gmap_ucas_translate_simple(struct gmap *gmap, gpa_t *gaddr, union crste **crstepp)
797 {
798 	union pte *ptep;
799 	int rc;
800 
801 	rc = dat_entry_walk(NULL, gpa_to_gfn(*gaddr), gmap->asce, DAT_WALK_CONTINUE,
802 			    TABLE_TYPE_SEGMENT, crstepp, &ptep);
803 	if (rc || (!ptep && !crste_is_ucas(**crstepp)))
804 		return -EREMOTE;
805 	if (!ptep)
806 		return 1;
807 	*gaddr &= ~_SEGMENT_MASK;
808 	*gaddr |= dat_get_ptval(pte_table_start(ptep), PTVAL_VMADDR) << _SEGMENT_SHIFT;
809 	return 0;
810 }
811 
812 /**
813  * gmap_ucas_translate() - Translate a vcpu address into a host gmap address
814  * @mc: The memory cache to be used for allocations.
815  * @gmap: The per-cpu gmap.
816  * @gaddr: Pointer to the address to be translated, will get overwritten with
817  *         the translated address in case of success.
818  * Translates the per-vCPU guest address into a fake guest address, which can
819  * then be used with the fake memslots that are identity mapping userspace.
820  * This allows ucontrol VMs to use the normal fault resolution path, like
821  * normal VMs.
822  *
823  * Return: %0 in case of success, otherwise %-EREMOTE.
824  */
825 int gmap_ucas_translate(struct kvm_s390_mmu_cache *mc, struct gmap *gmap, gpa_t *gaddr)
826 {
827 	gpa_t translated_address;
828 	union crste *crstep;
829 	gfn_t gfn;
830 	int rc;
831 
832 	gfn = gpa_to_gfn(*gaddr);
833 
834 	scoped_guard(read_lock, &gmap->kvm->mmu_lock) {
835 		rc = gmap_ucas_translate_simple(gmap, gaddr, &crstep);
836 		if (rc <= 0)
837 			return rc;
838 	}
839 	do {
840 		scoped_guard(write_lock, &gmap->kvm->mmu_lock) {
841 			rc = gmap_ucas_translate_simple(gmap, gaddr, &crstep);
842 			if (rc <= 0)
843 				return rc;
844 			translated_address = (*gaddr & ~_SEGMENT_MASK) |
845 					     (crstep->val & _SEGMENT_MASK);
846 			rc = gmap_ucas_map_one(mc, gmap, gpa_to_gfn(translated_address), gfn, true);
847 		}
848 		if (!rc) {
849 			*gaddr = translated_address;
850 			return 0;
851 		}
852 		if (rc != -ENOMEM)
853 			return -EREMOTE;
854 		rc = kvm_s390_mmu_cache_topup(mc);
855 		if (rc)
856 			return rc;
857 	} while (1);
858 	return 0;
859 }
860 
861 int gmap_ucas_map(struct gmap *gmap, gfn_t p_gfn, gfn_t c_gfn, unsigned long count)
862 {
863 	struct kvm_s390_mmu_cache *mc __free(kvm_s390_mmu_cache) = NULL;
864 	int rc = 0;
865 
866 	mc = kvm_s390_new_mmu_cache();
867 	if (!mc)
868 		return -ENOMEM;
869 
870 	while (count) {
871 		scoped_guard(write_lock, &gmap->kvm->mmu_lock)
872 			rc = gmap_ucas_map_one(mc, gmap, p_gfn, c_gfn, false);
873 		if (rc == -ENOMEM) {
874 			rc = kvm_s390_mmu_cache_topup(mc);
875 			if (rc)
876 				return rc;
877 			continue;
878 		}
879 		if (rc)
880 			return rc;
881 
882 		count--;
883 		c_gfn += _PAGE_ENTRIES;
884 		p_gfn += _PAGE_ENTRIES;
885 	}
886 	return rc;
887 }
888 
889 static void gmap_ucas_unmap_one(struct gmap *gmap, gfn_t c_gfn)
890 {
891 	union crste *crstep;
892 	union pte *ptep;
893 	int rc;
894 
895 	rc = dat_entry_walk(NULL, c_gfn, gmap->asce, 0, TABLE_TYPE_SEGMENT, &crstep, &ptep);
896 	if (rc)
897 		return;
898 	while (!dat_crstep_xchg_atomic(crstep, READ_ONCE(*crstep), _PMD_EMPTY, c_gfn, gmap->asce))
899 		;
900 }
901 
902 void gmap_ucas_unmap(struct gmap *gmap, gfn_t c_gfn, unsigned long count)
903 {
904 	guard(read_lock)(&gmap->kvm->mmu_lock);
905 
906 	for ( ; count; count--, c_gfn += _PAGE_ENTRIES)
907 		gmap_ucas_unmap_one(gmap, c_gfn);
908 }
909 
910 static long _gmap_split_crste(union crste *crstep, gfn_t gfn, gfn_t next, struct dat_walk *walk)
911 {
912 	struct gmap *gmap = walk->priv;
913 	union crste crste, newcrste;
914 
915 	crste = READ_ONCE(*crstep);
916 	newcrste = _CRSTE_EMPTY(crste.h.tt);
917 
918 	while (crste_leaf(crste)) {
919 		if (crste_prefix(crste))
920 			gmap_unmap_prefix(gmap, gfn, next);
921 		if (crste.s.fc1.vsie_notif)
922 			gmap_handle_vsie_unshadow_event(gmap, gfn);
923 		if (dat_crstep_xchg_atomic(crstep, crste, newcrste, gfn, walk->asce))
924 			break;
925 		crste = READ_ONCE(*crstep);
926 	}
927 
928 	if (need_resched())
929 		return next;
930 
931 	return 0;
932 }
933 
934 void gmap_split_huge_pages(struct gmap *gmap)
935 {
936 	const struct dat_walk_ops ops = {
937 		.pmd_entry = _gmap_split_crste,
938 		.pud_entry = _gmap_split_crste,
939 	};
940 	gfn_t start = 0;
941 
942 	do {
943 		scoped_guard(read_lock, &gmap->kvm->mmu_lock)
944 			start = _dat_walk_gfn_range(start, asce_end(gmap->asce), gmap->asce,
945 						    &ops, DAT_WALK_IGN_HOLES, gmap);
946 	} while (start);
947 }
948 
949 #if KVM_S390_MANAGES_S390_GUEST
950 
951 static int _gmap_enable_skeys(struct gmap *gmap)
952 {
953 	gfn_t start = 0;
954 	int rc;
955 
956 	if (uses_skeys(gmap))
957 		return 0;
958 
959 	set_bit(GMAP_FLAG_USES_SKEYS, &gmap->flags);
960 	rc = gmap_helper_disable_cow_sharing();
961 	if (rc) {
962 		clear_bit(GMAP_FLAG_USES_SKEYS, &gmap->flags);
963 		return rc;
964 	}
965 
966 	do {
967 		scoped_guard(write_lock, &gmap->kvm->mmu_lock)
968 			start = dat_reset_skeys(gmap->asce, start);
969 	} while (start);
970 	return 0;
971 }
972 
973 int gmap_enable_skeys(struct gmap *gmap)
974 {
975 	int rc;
976 
977 	mmap_write_lock(gmap->kvm->mm);
978 	rc = _gmap_enable_skeys(gmap);
979 	mmap_write_unlock(gmap->kvm->mm);
980 	return rc;
981 }
982 #endif /* KVM_S390_MANAGES_S390_GUEST */
983 
984 static long _destroy_pages_pte(union pte *ptep, gfn_t gfn, gfn_t next, struct dat_walk *walk)
985 {
986 	if (!ptep->s.pr)
987 		return 0;
988 	__kvm_s390_pv_destroy_page(phys_to_page(pte_origin(*ptep)));
989 	if (need_resched())
990 		return next;
991 	return 0;
992 }
993 
994 static long _destroy_pages_crste(union crste *crstep, gfn_t gfn, gfn_t next, struct dat_walk *walk)
995 {
996 	phys_addr_t origin, cur, end;
997 
998 	if (!crstep->h.fc || !crstep->s.fc1.pr)
999 		return 0;
1000 
1001 	origin = crste_origin_large(*crstep);
1002 	cur = ((max(gfn, walk->start) - gfn) << PAGE_SHIFT) + origin;
1003 	end = ((min(next, walk->end) - gfn) << PAGE_SHIFT) + origin;
1004 	for ( ; cur < end; cur += PAGE_SIZE)
1005 		__kvm_s390_pv_destroy_page(phys_to_page(cur));
1006 	if (need_resched())
1007 		return next;
1008 	return 0;
1009 }
1010 
1011 int gmap_pv_destroy_range(struct gmap *gmap, gfn_t start, gfn_t end, bool interruptible)
1012 {
1013 	const struct dat_walk_ops ops = {
1014 		.pte_entry = _destroy_pages_pte,
1015 		.pmd_entry = _destroy_pages_crste,
1016 		.pud_entry = _destroy_pages_crste,
1017 	};
1018 
1019 	do {
1020 		scoped_guard(read_lock, &gmap->kvm->mmu_lock)
1021 			start = _dat_walk_gfn_range(start, end, gmap->asce, &ops,
1022 						    DAT_WALK_IGN_HOLES, NULL);
1023 		if (interruptible && fatal_signal_pending(current))
1024 			return -EINTR;
1025 	} while (start && start < end);
1026 	return 0;
1027 }
1028 
1029 int gmap_insert_rmap(struct kvm_s390_mmu_cache *mc, struct gmap *sg, gfn_t p_gfn,
1030 		     gfn_t r_gfn, int level)
1031 {
1032 	struct vsie_rmap *rmap __free(kvfree) = NULL;
1033 	struct vsie_rmap *temp;
1034 	void __rcu **slot;
1035 	int rc = 0;
1036 
1037 	KVM_BUG_ON(!is_shadow(sg), sg->kvm);
1038 	lockdep_assert_held(&sg->host_to_rmap_lock);
1039 
1040 	rmap = kvm_s390_mmu_cache_alloc_rmap(mc);
1041 	if (!rmap)
1042 		return -ENOMEM;
1043 
1044 	rmap->r_gfn = r_gfn;
1045 	rmap->level = level;
1046 	slot = radix_tree_lookup_slot(&sg->host_to_rmap, p_gfn);
1047 	if (slot) {
1048 		rmap->next = radix_tree_deref_slot_protected(slot, &sg->host_to_rmap_lock);
1049 		for (temp = rmap->next; temp; temp = temp->next) {
1050 			if (temp->val == rmap->val)
1051 				return 0;
1052 		}
1053 		radix_tree_replace_slot(&sg->host_to_rmap, slot, rmap);
1054 	} else {
1055 		rmap->next = NULL;
1056 		rc = radix_tree_insert(&sg->host_to_rmap, p_gfn, rmap);
1057 		if (rc)
1058 			return rc;
1059 	}
1060 	rmap = NULL;
1061 
1062 	return 0;
1063 }
1064 
1065 int gmap_protect_rmap(struct kvm_s390_mmu_cache *mc, struct gmap *sg, gfn_t p_gfn, gfn_t r_gfn,
1066 		      kvm_pfn_t pfn, int level, bool wr)
1067 {
1068 	unsigned long bitmask;
1069 	union crste *crstep;
1070 	union pgste pgste;
1071 	union pte *ptep;
1072 	union pte pte;
1073 	int flags, rc;
1074 
1075 	if (KVM_BUG_ON(!is_shadow(sg) || level <= TABLE_TYPE_PAGE_TABLE, sg->kvm))
1076 		return -EINVAL;
1077 	lockdep_assert_held(&sg->parent->children_lock);
1078 
1079 	flags = DAT_WALK_SPLIT_ALLOC | (uses_skeys(sg->parent) ? DAT_WALK_USES_SKEYS : 0);
1080 	rc = dat_entry_walk(mc, p_gfn, sg->parent->asce, flags,
1081 			    TABLE_TYPE_PAGE_TABLE, &crstep, &ptep);
1082 	if (rc)
1083 		return rc;
1084 	if (level <= TABLE_TYPE_REGION1) {
1085 		bitmask = -1UL << (8 + 11 * level);
1086 		scoped_guard(spinlock, &sg->host_to_rmap_lock)
1087 			rc = gmap_insert_rmap(mc, sg, p_gfn, r_gfn & bitmask, level);
1088 	}
1089 	if (rc)
1090 		return rc;
1091 
1092 	if (!pgste_get_trylock(ptep, &pgste))
1093 		return -EAGAIN;
1094 	pte = ptep->s.pr ? *ptep : _pte(pfn, wr, false, false);
1095 	pte.h.p = 1;
1096 	pgste = _gmap_ptep_xchg(sg->parent, ptep, pte, pgste, p_gfn, false);
1097 	pgste.vsie_notif = 1;
1098 	pgste_set_unlock(ptep, pgste);
1099 
1100 	return 0;
1101 }
1102 
1103 #if KVM_S390_MANAGES_S390_GUEST
1104 static long __set_cmma_clean_pte(union pte *ptep, gfn_t gfn, gfn_t next, struct dat_walk *walk)
1105 {
1106 	union pgste pgste;
1107 
1108 	pgste = pgste_get_lock(ptep);
1109 	pgste.cmma_d = 0;
1110 	pgste_set_unlock(ptep, pgste);
1111 
1112 	if (need_resched())
1113 		return next;
1114 	return 0;
1115 }
1116 
1117 static long __set_cmma_dirty_pte(union pte *ptep, gfn_t gfn, gfn_t next, struct dat_walk *walk)
1118 {
1119 	union pgste pgste;
1120 
1121 	pgste = pgste_get_lock(ptep);
1122 	if (!pgste.cmma_d)
1123 		atomic64_inc(walk->priv);
1124 	pgste.cmma_d = 1;
1125 	pgste_set_unlock(ptep, pgste);
1126 
1127 	if (need_resched())
1128 		return next;
1129 	return 0;
1130 }
1131 
1132 void _gmap_set_cmma_all(struct gmap *gmap, bool dirty)
1133 {
1134 	const struct dat_walk_ops ops = {
1135 		.pte_entry = dirty ? __set_cmma_dirty_pte : __set_cmma_clean_pte,
1136 	};
1137 	gfn_t gfn = 0;
1138 
1139 	do {
1140 		scoped_guard(read_lock, &gmap->kvm->mmu_lock)
1141 			gfn = _dat_walk_gfn_range(gfn, asce_end(gmap->asce), gmap->asce, &ops,
1142 						  DAT_WALK_IGN_HOLES,
1143 						  &gmap->kvm->arch.cmma_dirty_pages);
1144 	} while (gfn);
1145 }
1146 #endif /* KVM_S390_MANAGES_S390_GUEST */
1147 
1148 static void gmap_unshadow_level(struct gmap *sg, gfn_t r_gfn, int level)
1149 {
1150 	unsigned long align = PAGE_SIZE;
1151 	gpa_t gaddr = gfn_to_gpa(r_gfn);
1152 	union crste *crstep;
1153 	union crste crste;
1154 	union pte *ptep;
1155 
1156 	if (level > TABLE_TYPE_PAGE_TABLE)
1157 		align = 1UL << (11 * level + _SEGMENT_SHIFT);
1158 	kvm_s390_vsie_gmap_notifier(sg, ALIGN_DOWN(gaddr, align), ALIGN(gaddr + 1, align));
1159 	sg->invalidated = true;
1160 	if (dat_entry_walk(NULL, r_gfn, sg->asce, 0, level, &crstep, &ptep))
1161 		return;
1162 	if (ptep) {
1163 		if (READ_ONCE(*ptep).val != _PTE_EMPTY.val)
1164 			dat_ptep_xchg(ptep, _PTE_EMPTY, r_gfn, sg->asce, uses_skeys(sg));
1165 		return;
1166 	}
1167 
1168 	crste = dat_crstep_clear_atomic(crstep, r_gfn, sg->asce);
1169 	if (crste_leaf(crste) || crste.h.i)
1170 		return;
1171 	if (is_pmd(crste))
1172 		dat_free_pt(dereference_pmd(crste.pmd));
1173 	else
1174 		dat_free_level(dereference_crste(crste), true);
1175 }
1176 
1177 static void gmap_unshadow(struct gmap *sg)
1178 {
1179 	struct gmap_cache *gmap_cache, *next;
1180 
1181 	KVM_BUG_ON(!is_shadow(sg), sg->kvm);
1182 	KVM_BUG_ON(!sg->parent, sg->kvm);
1183 
1184 	lockdep_assert_held(&sg->parent->children_lock);
1185 
1186 	gmap_remove_child(sg);
1187 	kvm_s390_vsie_gmap_notifier(sg, 0, -1UL);
1188 
1189 	list_for_each_entry_safe(gmap_cache, next, &sg->scb_users, list) {
1190 		gmap_cache->gmap = NULL;
1191 		list_del(&gmap_cache->list);
1192 	}
1193 
1194 	gmap_put(sg);
1195 }
1196 
1197 void _gmap_handle_vsie_unshadow_event(struct gmap *parent, gfn_t gfn)
1198 {
1199 	struct vsie_rmap *rmap, *rnext, *head;
1200 	struct gmap *sg, *next;
1201 	gfn_t start, end;
1202 
1203 	list_for_each_entry_safe(sg, next, &parent->children, list) {
1204 		start = sg->guest_asce.rsto;
1205 		end = start + sg->guest_asce.tl + 1;
1206 		if (!sg->guest_asce.r && gfn >= start && gfn < end) {
1207 			gmap_unshadow(sg);
1208 			continue;
1209 		}
1210 		scoped_guard(spinlock, &sg->host_to_rmap_lock)
1211 			head = radix_tree_delete(&sg->host_to_rmap, gfn);
1212 		gmap_for_each_rmap_safe(rmap, rnext, head) {
1213 			gmap_unshadow_level(sg, rmap->r_gfn, rmap->level);
1214 			kfree(rmap);
1215 		}
1216 	}
1217 }
1218 
1219 /**
1220  * gmap_find_shadow() - Find a specific ASCE in the list of shadow tables.
1221  * @parent: Pointer to the parent gmap.
1222  * @asce: ASCE for which the shadow table is created.
1223  * @edat_level: Edat level to be used for the shadow translation.
1224  *
1225  * Context: Called with parent->children_lock held.
1226  *
1227  * Return: The pointer to a gmap if a shadow table with the given asce is
1228  * already available, ERR_PTR(-EAGAIN) if another one is just being created,
1229  * otherwise NULL.
1230  */
1231 static struct gmap *gmap_find_shadow(struct gmap *parent, union asce asce, int edat_level)
1232 {
1233 	struct gmap *sg;
1234 
1235 	lockdep_assert_held(&parent->children_lock);
1236 	list_for_each_entry(sg, &parent->children, list) {
1237 		if (!gmap_is_shadow_valid(sg, asce, edat_level))
1238 			continue;
1239 		return sg;
1240 	}
1241 	return NULL;
1242 }
1243 
1244 #define CRST_TABLE_PAGES (_CRST_TABLE_SIZE / PAGE_SIZE)
1245 struct gmap_protect_asce_top_level {
1246 	unsigned long seq;
1247 	struct guest_fault f[CRST_TABLE_PAGES];
1248 };
1249 
1250 static inline int __gmap_protect_asce_top_level(struct kvm_s390_mmu_cache *mc, struct gmap *sg,
1251 						struct gmap_protect_asce_top_level *context)
1252 {
1253 	struct gmap *parent;
1254 	int rc, i;
1255 
1256 	guard(write_lock)(&sg->kvm->mmu_lock);
1257 
1258 	if (kvm_s390_array_needs_retry_safe(sg->kvm, context->seq, context->f))
1259 		return -EAGAIN;
1260 
1261 	parent = READ_ONCE(sg->parent);
1262 	if (!parent)
1263 		return -EAGAIN;
1264 	scoped_guard(spinlock, &parent->children_lock) {
1265 		if (READ_ONCE(sg->parent) != parent)
1266 			return -EAGAIN;
1267 		sg->invalidated = false;
1268 		for (i = 0; i < CRST_TABLE_PAGES; i++) {
1269 			if (!context->f[i].valid)
1270 				continue;
1271 			rc = gmap_protect_rmap(mc, sg, context->f[i].gfn, 0, context->f[i].pfn,
1272 					       TABLE_TYPE_REGION1 + 1, context->f[i].writable);
1273 			if (rc)
1274 				return rc;
1275 		}
1276 		gmap_add_child(sg->parent, sg);
1277 	}
1278 
1279 	kvm_s390_release_faultin_array(sg->kvm, context->f, false);
1280 	return 0;
1281 }
1282 
1283 static inline int _gmap_protect_asce_top_level(struct kvm_s390_mmu_cache *mc, struct gmap *sg,
1284 					       struct gmap_protect_asce_top_level *context)
1285 {
1286 	int rc;
1287 
1288 	if (kvm_s390_array_needs_retry_unsafe(sg->kvm, context->seq, context->f))
1289 		return -EAGAIN;
1290 	do {
1291 		rc = kvm_s390_mmu_cache_topup(mc);
1292 		if (rc)
1293 			return rc;
1294 		rc = radix_tree_preload(GFP_KERNEL);
1295 		if (rc)
1296 			return rc;
1297 		rc = __gmap_protect_asce_top_level(mc, sg, context);
1298 		radix_tree_preload_end();
1299 	} while (rc == -ENOMEM);
1300 
1301 	return rc;
1302 }
1303 
1304 static int gmap_protect_asce_top_level(struct kvm_s390_mmu_cache *mc, struct gmap *sg)
1305 {
1306 	struct gmap_protect_asce_top_level context = {};
1307 	union asce asce = sg->guest_asce;
1308 	int rc;
1309 
1310 	KVM_BUG_ON(!is_shadow(sg), sg->kvm);
1311 
1312 	context.seq = sg->kvm->mmu_invalidate_seq;
1313 	/* Pairs with the smp_wmb() in kvm_mmu_invalidate_end(). */
1314 	smp_rmb();
1315 
1316 	rc = kvm_s390_get_guest_pages(sg->kvm, context.f, asce.rsto, asce.tl + 1, false);
1317 	if (rc > 0)
1318 		rc = -EFAULT;
1319 	if (!rc)
1320 		rc = _gmap_protect_asce_top_level(mc, sg, &context);
1321 	if (rc)
1322 		kvm_s390_release_faultin_array(sg->kvm, context.f, true);
1323 	return rc;
1324 }
1325 
1326 /**
1327  * gmap_create_shadow() - Create/find a shadow guest address space.
1328  * @mc: The cache to use to allocate dat tables.
1329  * @parent: Pointer to the parent gmap.
1330  * @asce: ASCE for which the shadow table is created.
1331  * @edat_level: Edat level to be used for the shadow translation.
1332  *
1333  * The pages of the top level page table referred by the asce parameter
1334  * will be set to read-only and marked in the PGSTEs of the kvm process.
1335  * The shadow table will be removed automatically on any change to the
1336  * PTE mapping for the source table.
1337  *
1338  * The returned shadow gmap will be returned with one extra reference.
1339  *
1340  * Return: A guest address space structure, ERR_PTR(-ENOMEM) if out of memory,
1341  * ERR_PTR(-EAGAIN) if the caller has to retry and ERR_PTR(-EFAULT) if the
1342  * parent gmap table could not be protected.
1343  */
1344 struct gmap *gmap_create_shadow(struct kvm_s390_mmu_cache *mc, struct gmap *parent,
1345 				union asce asce, int edat_level)
1346 {
1347 	struct gmap *sg, *new;
1348 	int rc;
1349 
1350 	if (WARN_ON(!parent))
1351 		return ERR_PTR(-EINVAL);
1352 
1353 	scoped_guard(spinlock, &parent->children_lock) {
1354 		sg = gmap_find_shadow(parent, asce, edat_level);
1355 		if (sg) {
1356 			gmap_get(sg);
1357 			return sg;
1358 		}
1359 	}
1360 	/* Create a new shadow gmap. */
1361 	new = gmap_new(parent->kvm, asce.r ? 1UL << (64 - PAGE_SHIFT) : asce_end(asce));
1362 	if (!new)
1363 		return ERR_PTR(-ENOMEM);
1364 	new->guest_asce = asce;
1365 	new->edat_level = edat_level;
1366 	set_bit(GMAP_FLAG_SHADOW, &new->flags);
1367 
1368 	scoped_guard(spinlock, &parent->children_lock) {
1369 		/* Recheck if another CPU created the same shadow. */
1370 		sg = gmap_find_shadow(parent, asce, edat_level);
1371 		if (sg) {
1372 			gmap_put(new);
1373 			gmap_get(sg);
1374 			return sg;
1375 		}
1376 		if (asce.r) {
1377 			/* Only allow one real-space gmap shadow. */
1378 			list_for_each_entry(sg, &parent->children, list) {
1379 				if (sg->guest_asce.r) {
1380 					if (write_trylock(&parent->kvm->mmu_lock)) {
1381 						gmap_unshadow(sg);
1382 						write_unlock(&parent->kvm->mmu_lock);
1383 					} else {
1384 						gmap_put(new);
1385 						return ERR_PTR(-EAGAIN);
1386 					}
1387 					break;
1388 				}
1389 			}
1390 			gmap_add_child(parent, new);
1391 			/* Nothing to protect, return right away. */
1392 			gmap_get(new);
1393 			return new;
1394 		}
1395 	}
1396 
1397 	gmap_get(new);
1398 	new->parent = parent;
1399 	/* Protect while inserting, protects against invalidation races. */
1400 	rc = gmap_protect_asce_top_level(mc, new);
1401 	if (rc) {
1402 		new->parent = NULL;
1403 		gmap_put(new);
1404 		gmap_put(new);
1405 		return ERR_PTR(rc);
1406 	}
1407 	return new;
1408 }
1409