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