xref: /linux/arch/arm64/kvm/hyp/pgtable.c (revision 55d0969c451159cff86949b38c39171cab962069)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Stand-alone page-table allocator for hyp stage-1 and guest stage-2.
4  * No bombay mix was harmed in the writing of this file.
5  *
6  * Copyright (C) 2020 Google LLC
7  * Author: Will Deacon <will@kernel.org>
8  */
9 
10 #include <linux/bitfield.h>
11 #include <asm/kvm_pgtable.h>
12 #include <asm/stage2_pgtable.h>
13 
14 
15 #define KVM_PTE_TYPE			BIT(1)
16 #define KVM_PTE_TYPE_BLOCK		0
17 #define KVM_PTE_TYPE_PAGE		1
18 #define KVM_PTE_TYPE_TABLE		1
19 
20 struct kvm_pgtable_walk_data {
21 	struct kvm_pgtable_walker	*walker;
22 
23 	const u64			start;
24 	u64				addr;
25 	const u64			end;
26 };
27 
28 static bool kvm_pgtable_walk_skip_bbm_tlbi(const struct kvm_pgtable_visit_ctx *ctx)
29 {
30 	return unlikely(ctx->flags & KVM_PGTABLE_WALK_SKIP_BBM_TLBI);
31 }
32 
33 static bool kvm_pgtable_walk_skip_cmo(const struct kvm_pgtable_visit_ctx *ctx)
34 {
35 	return unlikely(ctx->flags & KVM_PGTABLE_WALK_SKIP_CMO);
36 }
37 
38 static bool kvm_phys_is_valid(u64 phys)
39 {
40 	u64 parange_max = kvm_get_parange_max();
41 	u8 shift = id_aa64mmfr0_parange_to_phys_shift(parange_max);
42 
43 	return phys < BIT(shift);
44 }
45 
46 static bool kvm_block_mapping_supported(const struct kvm_pgtable_visit_ctx *ctx, u64 phys)
47 {
48 	u64 granule = kvm_granule_size(ctx->level);
49 
50 	if (!kvm_level_supports_block_mapping(ctx->level))
51 		return false;
52 
53 	if (granule > (ctx->end - ctx->addr))
54 		return false;
55 
56 	if (kvm_phys_is_valid(phys) && !IS_ALIGNED(phys, granule))
57 		return false;
58 
59 	return IS_ALIGNED(ctx->addr, granule);
60 }
61 
62 static u32 kvm_pgtable_idx(struct kvm_pgtable_walk_data *data, s8 level)
63 {
64 	u64 shift = kvm_granule_shift(level);
65 	u64 mask = BIT(PAGE_SHIFT - 3) - 1;
66 
67 	return (data->addr >> shift) & mask;
68 }
69 
70 static u32 kvm_pgd_page_idx(struct kvm_pgtable *pgt, u64 addr)
71 {
72 	u64 shift = kvm_granule_shift(pgt->start_level - 1); /* May underflow */
73 	u64 mask = BIT(pgt->ia_bits) - 1;
74 
75 	return (addr & mask) >> shift;
76 }
77 
78 static u32 kvm_pgd_pages(u32 ia_bits, s8 start_level)
79 {
80 	struct kvm_pgtable pgt = {
81 		.ia_bits	= ia_bits,
82 		.start_level	= start_level,
83 	};
84 
85 	return kvm_pgd_page_idx(&pgt, -1ULL) + 1;
86 }
87 
88 static bool kvm_pte_table(kvm_pte_t pte, s8 level)
89 {
90 	if (level == KVM_PGTABLE_LAST_LEVEL)
91 		return false;
92 
93 	if (!kvm_pte_valid(pte))
94 		return false;
95 
96 	return FIELD_GET(KVM_PTE_TYPE, pte) == KVM_PTE_TYPE_TABLE;
97 }
98 
99 static kvm_pte_t *kvm_pte_follow(kvm_pte_t pte, struct kvm_pgtable_mm_ops *mm_ops)
100 {
101 	return mm_ops->phys_to_virt(kvm_pte_to_phys(pte));
102 }
103 
104 static void kvm_clear_pte(kvm_pte_t *ptep)
105 {
106 	WRITE_ONCE(*ptep, 0);
107 }
108 
109 static kvm_pte_t kvm_init_table_pte(kvm_pte_t *childp, struct kvm_pgtable_mm_ops *mm_ops)
110 {
111 	kvm_pte_t pte = kvm_phys_to_pte(mm_ops->virt_to_phys(childp));
112 
113 	pte |= FIELD_PREP(KVM_PTE_TYPE, KVM_PTE_TYPE_TABLE);
114 	pte |= KVM_PTE_VALID;
115 	return pte;
116 }
117 
118 static kvm_pte_t kvm_init_valid_leaf_pte(u64 pa, kvm_pte_t attr, s8 level)
119 {
120 	kvm_pte_t pte = kvm_phys_to_pte(pa);
121 	u64 type = (level == KVM_PGTABLE_LAST_LEVEL) ? KVM_PTE_TYPE_PAGE :
122 						       KVM_PTE_TYPE_BLOCK;
123 
124 	pte |= attr & (KVM_PTE_LEAF_ATTR_LO | KVM_PTE_LEAF_ATTR_HI);
125 	pte |= FIELD_PREP(KVM_PTE_TYPE, type);
126 	pte |= KVM_PTE_VALID;
127 
128 	return pte;
129 }
130 
131 static kvm_pte_t kvm_init_invalid_leaf_owner(u8 owner_id)
132 {
133 	return FIELD_PREP(KVM_INVALID_PTE_OWNER_MASK, owner_id);
134 }
135 
136 static int kvm_pgtable_visitor_cb(struct kvm_pgtable_walk_data *data,
137 				  const struct kvm_pgtable_visit_ctx *ctx,
138 				  enum kvm_pgtable_walk_flags visit)
139 {
140 	struct kvm_pgtable_walker *walker = data->walker;
141 
142 	/* Ensure the appropriate lock is held (e.g. RCU lock for stage-2 MMU) */
143 	WARN_ON_ONCE(kvm_pgtable_walk_shared(ctx) && !kvm_pgtable_walk_lock_held());
144 	return walker->cb(ctx, visit);
145 }
146 
147 static bool kvm_pgtable_walk_continue(const struct kvm_pgtable_walker *walker,
148 				      int r)
149 {
150 	/*
151 	 * Visitor callbacks return EAGAIN when the conditions that led to a
152 	 * fault are no longer reflected in the page tables due to a race to
153 	 * update a PTE. In the context of a fault handler this is interpreted
154 	 * as a signal to retry guest execution.
155 	 *
156 	 * Ignore the return code altogether for walkers outside a fault handler
157 	 * (e.g. write protecting a range of memory) and chug along with the
158 	 * page table walk.
159 	 */
160 	if (r == -EAGAIN)
161 		return !(walker->flags & KVM_PGTABLE_WALK_HANDLE_FAULT);
162 
163 	return !r;
164 }
165 
166 static int __kvm_pgtable_walk(struct kvm_pgtable_walk_data *data,
167 			      struct kvm_pgtable_mm_ops *mm_ops, kvm_pteref_t pgtable, s8 level);
168 
169 static inline int __kvm_pgtable_visit(struct kvm_pgtable_walk_data *data,
170 				      struct kvm_pgtable_mm_ops *mm_ops,
171 				      kvm_pteref_t pteref, s8 level)
172 {
173 	enum kvm_pgtable_walk_flags flags = data->walker->flags;
174 	kvm_pte_t *ptep = kvm_dereference_pteref(data->walker, pteref);
175 	struct kvm_pgtable_visit_ctx ctx = {
176 		.ptep	= ptep,
177 		.old	= READ_ONCE(*ptep),
178 		.arg	= data->walker->arg,
179 		.mm_ops	= mm_ops,
180 		.start	= data->start,
181 		.addr	= data->addr,
182 		.end	= data->end,
183 		.level	= level,
184 		.flags	= flags,
185 	};
186 	int ret = 0;
187 	bool reload = false;
188 	kvm_pteref_t childp;
189 	bool table = kvm_pte_table(ctx.old, level);
190 
191 	if (table && (ctx.flags & KVM_PGTABLE_WALK_TABLE_PRE)) {
192 		ret = kvm_pgtable_visitor_cb(data, &ctx, KVM_PGTABLE_WALK_TABLE_PRE);
193 		reload = true;
194 	}
195 
196 	if (!table && (ctx.flags & KVM_PGTABLE_WALK_LEAF)) {
197 		ret = kvm_pgtable_visitor_cb(data, &ctx, KVM_PGTABLE_WALK_LEAF);
198 		reload = true;
199 	}
200 
201 	/*
202 	 * Reload the page table after invoking the walker callback for leaf
203 	 * entries or after pre-order traversal, to allow the walker to descend
204 	 * into a newly installed or replaced table.
205 	 */
206 	if (reload) {
207 		ctx.old = READ_ONCE(*ptep);
208 		table = kvm_pte_table(ctx.old, level);
209 	}
210 
211 	if (!kvm_pgtable_walk_continue(data->walker, ret))
212 		goto out;
213 
214 	if (!table) {
215 		data->addr = ALIGN_DOWN(data->addr, kvm_granule_size(level));
216 		data->addr += kvm_granule_size(level);
217 		goto out;
218 	}
219 
220 	childp = (kvm_pteref_t)kvm_pte_follow(ctx.old, mm_ops);
221 	ret = __kvm_pgtable_walk(data, mm_ops, childp, level + 1);
222 	if (!kvm_pgtable_walk_continue(data->walker, ret))
223 		goto out;
224 
225 	if (ctx.flags & KVM_PGTABLE_WALK_TABLE_POST)
226 		ret = kvm_pgtable_visitor_cb(data, &ctx, KVM_PGTABLE_WALK_TABLE_POST);
227 
228 out:
229 	if (kvm_pgtable_walk_continue(data->walker, ret))
230 		return 0;
231 
232 	return ret;
233 }
234 
235 static int __kvm_pgtable_walk(struct kvm_pgtable_walk_data *data,
236 			      struct kvm_pgtable_mm_ops *mm_ops, kvm_pteref_t pgtable, s8 level)
237 {
238 	u32 idx;
239 	int ret = 0;
240 
241 	if (WARN_ON_ONCE(level < KVM_PGTABLE_FIRST_LEVEL ||
242 			 level > KVM_PGTABLE_LAST_LEVEL))
243 		return -EINVAL;
244 
245 	for (idx = kvm_pgtable_idx(data, level); idx < PTRS_PER_PTE; ++idx) {
246 		kvm_pteref_t pteref = &pgtable[idx];
247 
248 		if (data->addr >= data->end)
249 			break;
250 
251 		ret = __kvm_pgtable_visit(data, mm_ops, pteref, level);
252 		if (ret)
253 			break;
254 	}
255 
256 	return ret;
257 }
258 
259 static int _kvm_pgtable_walk(struct kvm_pgtable *pgt, struct kvm_pgtable_walk_data *data)
260 {
261 	u32 idx;
262 	int ret = 0;
263 	u64 limit = BIT(pgt->ia_bits);
264 
265 	if (data->addr > limit || data->end > limit)
266 		return -ERANGE;
267 
268 	if (!pgt->pgd)
269 		return -EINVAL;
270 
271 	for (idx = kvm_pgd_page_idx(pgt, data->addr); data->addr < data->end; ++idx) {
272 		kvm_pteref_t pteref = &pgt->pgd[idx * PTRS_PER_PTE];
273 
274 		ret = __kvm_pgtable_walk(data, pgt->mm_ops, pteref, pgt->start_level);
275 		if (ret)
276 			break;
277 	}
278 
279 	return ret;
280 }
281 
282 int kvm_pgtable_walk(struct kvm_pgtable *pgt, u64 addr, u64 size,
283 		     struct kvm_pgtable_walker *walker)
284 {
285 	struct kvm_pgtable_walk_data walk_data = {
286 		.start	= ALIGN_DOWN(addr, PAGE_SIZE),
287 		.addr	= ALIGN_DOWN(addr, PAGE_SIZE),
288 		.end	= PAGE_ALIGN(walk_data.addr + size),
289 		.walker	= walker,
290 	};
291 	int r;
292 
293 	r = kvm_pgtable_walk_begin(walker);
294 	if (r)
295 		return r;
296 
297 	r = _kvm_pgtable_walk(pgt, &walk_data);
298 	kvm_pgtable_walk_end(walker);
299 
300 	return r;
301 }
302 
303 struct leaf_walk_data {
304 	kvm_pte_t	pte;
305 	s8		level;
306 };
307 
308 static int leaf_walker(const struct kvm_pgtable_visit_ctx *ctx,
309 		       enum kvm_pgtable_walk_flags visit)
310 {
311 	struct leaf_walk_data *data = ctx->arg;
312 
313 	data->pte   = ctx->old;
314 	data->level = ctx->level;
315 
316 	return 0;
317 }
318 
319 int kvm_pgtable_get_leaf(struct kvm_pgtable *pgt, u64 addr,
320 			 kvm_pte_t *ptep, s8 *level)
321 {
322 	struct leaf_walk_data data;
323 	struct kvm_pgtable_walker walker = {
324 		.cb	= leaf_walker,
325 		.flags	= KVM_PGTABLE_WALK_LEAF,
326 		.arg	= &data,
327 	};
328 	int ret;
329 
330 	ret = kvm_pgtable_walk(pgt, ALIGN_DOWN(addr, PAGE_SIZE),
331 			       PAGE_SIZE, &walker);
332 	if (!ret) {
333 		if (ptep)
334 			*ptep  = data.pte;
335 		if (level)
336 			*level = data.level;
337 	}
338 
339 	return ret;
340 }
341 
342 struct hyp_map_data {
343 	const u64			phys;
344 	kvm_pte_t			attr;
345 };
346 
347 static int hyp_set_prot_attr(enum kvm_pgtable_prot prot, kvm_pte_t *ptep)
348 {
349 	bool device = prot & KVM_PGTABLE_PROT_DEVICE;
350 	u32 mtype = device ? MT_DEVICE_nGnRE : MT_NORMAL;
351 	kvm_pte_t attr = FIELD_PREP(KVM_PTE_LEAF_ATTR_LO_S1_ATTRIDX, mtype);
352 	u32 sh = KVM_PTE_LEAF_ATTR_LO_S1_SH_IS;
353 	u32 ap = (prot & KVM_PGTABLE_PROT_W) ? KVM_PTE_LEAF_ATTR_LO_S1_AP_RW :
354 					       KVM_PTE_LEAF_ATTR_LO_S1_AP_RO;
355 
356 	if (!(prot & KVM_PGTABLE_PROT_R))
357 		return -EINVAL;
358 
359 	if (prot & KVM_PGTABLE_PROT_X) {
360 		if (prot & KVM_PGTABLE_PROT_W)
361 			return -EINVAL;
362 
363 		if (device)
364 			return -EINVAL;
365 
366 		if (system_supports_bti_kernel())
367 			attr |= KVM_PTE_LEAF_ATTR_HI_S1_GP;
368 	} else {
369 		attr |= KVM_PTE_LEAF_ATTR_HI_S1_XN;
370 	}
371 
372 	attr |= FIELD_PREP(KVM_PTE_LEAF_ATTR_LO_S1_AP, ap);
373 	if (!kvm_lpa2_is_enabled())
374 		attr |= FIELD_PREP(KVM_PTE_LEAF_ATTR_LO_S1_SH, sh);
375 	attr |= KVM_PTE_LEAF_ATTR_LO_S1_AF;
376 	attr |= prot & KVM_PTE_LEAF_ATTR_HI_SW;
377 	*ptep = attr;
378 
379 	return 0;
380 }
381 
382 enum kvm_pgtable_prot kvm_pgtable_hyp_pte_prot(kvm_pte_t pte)
383 {
384 	enum kvm_pgtable_prot prot = pte & KVM_PTE_LEAF_ATTR_HI_SW;
385 	u32 ap;
386 
387 	if (!kvm_pte_valid(pte))
388 		return prot;
389 
390 	if (!(pte & KVM_PTE_LEAF_ATTR_HI_S1_XN))
391 		prot |= KVM_PGTABLE_PROT_X;
392 
393 	ap = FIELD_GET(KVM_PTE_LEAF_ATTR_LO_S1_AP, pte);
394 	if (ap == KVM_PTE_LEAF_ATTR_LO_S1_AP_RO)
395 		prot |= KVM_PGTABLE_PROT_R;
396 	else if (ap == KVM_PTE_LEAF_ATTR_LO_S1_AP_RW)
397 		prot |= KVM_PGTABLE_PROT_RW;
398 
399 	return prot;
400 }
401 
402 static bool hyp_map_walker_try_leaf(const struct kvm_pgtable_visit_ctx *ctx,
403 				    struct hyp_map_data *data)
404 {
405 	u64 phys = data->phys + (ctx->addr - ctx->start);
406 	kvm_pte_t new;
407 
408 	if (!kvm_block_mapping_supported(ctx, phys))
409 		return false;
410 
411 	new = kvm_init_valid_leaf_pte(phys, data->attr, ctx->level);
412 	if (ctx->old == new)
413 		return true;
414 	if (!kvm_pte_valid(ctx->old))
415 		ctx->mm_ops->get_page(ctx->ptep);
416 	else if (WARN_ON((ctx->old ^ new) & ~KVM_PTE_LEAF_ATTR_HI_SW))
417 		return false;
418 
419 	smp_store_release(ctx->ptep, new);
420 	return true;
421 }
422 
423 static int hyp_map_walker(const struct kvm_pgtable_visit_ctx *ctx,
424 			  enum kvm_pgtable_walk_flags visit)
425 {
426 	kvm_pte_t *childp, new;
427 	struct hyp_map_data *data = ctx->arg;
428 	struct kvm_pgtable_mm_ops *mm_ops = ctx->mm_ops;
429 
430 	if (hyp_map_walker_try_leaf(ctx, data))
431 		return 0;
432 
433 	if (WARN_ON(ctx->level == KVM_PGTABLE_LAST_LEVEL))
434 		return -EINVAL;
435 
436 	childp = (kvm_pte_t *)mm_ops->zalloc_page(NULL);
437 	if (!childp)
438 		return -ENOMEM;
439 
440 	new = kvm_init_table_pte(childp, mm_ops);
441 	mm_ops->get_page(ctx->ptep);
442 	smp_store_release(ctx->ptep, new);
443 
444 	return 0;
445 }
446 
447 int kvm_pgtable_hyp_map(struct kvm_pgtable *pgt, u64 addr, u64 size, u64 phys,
448 			enum kvm_pgtable_prot prot)
449 {
450 	int ret;
451 	struct hyp_map_data map_data = {
452 		.phys	= ALIGN_DOWN(phys, PAGE_SIZE),
453 	};
454 	struct kvm_pgtable_walker walker = {
455 		.cb	= hyp_map_walker,
456 		.flags	= KVM_PGTABLE_WALK_LEAF,
457 		.arg	= &map_data,
458 	};
459 
460 	ret = hyp_set_prot_attr(prot, &map_data.attr);
461 	if (ret)
462 		return ret;
463 
464 	ret = kvm_pgtable_walk(pgt, addr, size, &walker);
465 	dsb(ishst);
466 	isb();
467 	return ret;
468 }
469 
470 static int hyp_unmap_walker(const struct kvm_pgtable_visit_ctx *ctx,
471 			    enum kvm_pgtable_walk_flags visit)
472 {
473 	kvm_pte_t *childp = NULL;
474 	u64 granule = kvm_granule_size(ctx->level);
475 	u64 *unmapped = ctx->arg;
476 	struct kvm_pgtable_mm_ops *mm_ops = ctx->mm_ops;
477 
478 	if (!kvm_pte_valid(ctx->old))
479 		return -EINVAL;
480 
481 	if (kvm_pte_table(ctx->old, ctx->level)) {
482 		childp = kvm_pte_follow(ctx->old, mm_ops);
483 
484 		if (mm_ops->page_count(childp) != 1)
485 			return 0;
486 
487 		kvm_clear_pte(ctx->ptep);
488 		dsb(ishst);
489 		__tlbi_level(vae2is, __TLBI_VADDR(ctx->addr, 0), TLBI_TTL_UNKNOWN);
490 	} else {
491 		if (ctx->end - ctx->addr < granule)
492 			return -EINVAL;
493 
494 		kvm_clear_pte(ctx->ptep);
495 		dsb(ishst);
496 		__tlbi_level(vale2is, __TLBI_VADDR(ctx->addr, 0), ctx->level);
497 		*unmapped += granule;
498 	}
499 
500 	dsb(ish);
501 	isb();
502 	mm_ops->put_page(ctx->ptep);
503 
504 	if (childp)
505 		mm_ops->put_page(childp);
506 
507 	return 0;
508 }
509 
510 u64 kvm_pgtable_hyp_unmap(struct kvm_pgtable *pgt, u64 addr, u64 size)
511 {
512 	u64 unmapped = 0;
513 	struct kvm_pgtable_walker walker = {
514 		.cb	= hyp_unmap_walker,
515 		.arg	= &unmapped,
516 		.flags	= KVM_PGTABLE_WALK_LEAF | KVM_PGTABLE_WALK_TABLE_POST,
517 	};
518 
519 	if (!pgt->mm_ops->page_count)
520 		return 0;
521 
522 	kvm_pgtable_walk(pgt, addr, size, &walker);
523 	return unmapped;
524 }
525 
526 int kvm_pgtable_hyp_init(struct kvm_pgtable *pgt, u32 va_bits,
527 			 struct kvm_pgtable_mm_ops *mm_ops)
528 {
529 	s8 start_level = KVM_PGTABLE_LAST_LEVEL + 1 -
530 			 ARM64_HW_PGTABLE_LEVELS(va_bits);
531 
532 	if (start_level < KVM_PGTABLE_FIRST_LEVEL ||
533 	    start_level > KVM_PGTABLE_LAST_LEVEL)
534 		return -EINVAL;
535 
536 	pgt->pgd = (kvm_pteref_t)mm_ops->zalloc_page(NULL);
537 	if (!pgt->pgd)
538 		return -ENOMEM;
539 
540 	pgt->ia_bits		= va_bits;
541 	pgt->start_level	= start_level;
542 	pgt->mm_ops		= mm_ops;
543 	pgt->mmu		= NULL;
544 	pgt->force_pte_cb	= NULL;
545 
546 	return 0;
547 }
548 
549 static int hyp_free_walker(const struct kvm_pgtable_visit_ctx *ctx,
550 			   enum kvm_pgtable_walk_flags visit)
551 {
552 	struct kvm_pgtable_mm_ops *mm_ops = ctx->mm_ops;
553 
554 	if (!kvm_pte_valid(ctx->old))
555 		return 0;
556 
557 	mm_ops->put_page(ctx->ptep);
558 
559 	if (kvm_pte_table(ctx->old, ctx->level))
560 		mm_ops->put_page(kvm_pte_follow(ctx->old, mm_ops));
561 
562 	return 0;
563 }
564 
565 void kvm_pgtable_hyp_destroy(struct kvm_pgtable *pgt)
566 {
567 	struct kvm_pgtable_walker walker = {
568 		.cb	= hyp_free_walker,
569 		.flags	= KVM_PGTABLE_WALK_LEAF | KVM_PGTABLE_WALK_TABLE_POST,
570 	};
571 
572 	WARN_ON(kvm_pgtable_walk(pgt, 0, BIT(pgt->ia_bits), &walker));
573 	pgt->mm_ops->put_page(kvm_dereference_pteref(&walker, pgt->pgd));
574 	pgt->pgd = NULL;
575 }
576 
577 struct stage2_map_data {
578 	const u64			phys;
579 	kvm_pte_t			attr;
580 	u8				owner_id;
581 
582 	kvm_pte_t			*anchor;
583 	kvm_pte_t			*childp;
584 
585 	struct kvm_s2_mmu		*mmu;
586 	void				*memcache;
587 
588 	/* Force mappings to page granularity */
589 	bool				force_pte;
590 };
591 
592 u64 kvm_get_vtcr(u64 mmfr0, u64 mmfr1, u32 phys_shift)
593 {
594 	u64 vtcr = VTCR_EL2_FLAGS;
595 	s8 lvls;
596 
597 	vtcr |= kvm_get_parange(mmfr0) << VTCR_EL2_PS_SHIFT;
598 	vtcr |= VTCR_EL2_T0SZ(phys_shift);
599 	/*
600 	 * Use a minimum 2 level page table to prevent splitting
601 	 * host PMD huge pages at stage2.
602 	 */
603 	lvls = stage2_pgtable_levels(phys_shift);
604 	if (lvls < 2)
605 		lvls = 2;
606 
607 	/*
608 	 * When LPA2 is enabled, the HW supports an extra level of translation
609 	 * (for 5 in total) when using 4K pages. It also introduces VTCR_EL2.SL2
610 	 * to as an addition to SL0 to enable encoding this extra start level.
611 	 * However, since we always use concatenated pages for the first level
612 	 * lookup, we will never need this extra level and therefore do not need
613 	 * to touch SL2.
614 	 */
615 	vtcr |= VTCR_EL2_LVLS_TO_SL0(lvls);
616 
617 #ifdef CONFIG_ARM64_HW_AFDBM
618 	/*
619 	 * Enable the Hardware Access Flag management, unconditionally
620 	 * on all CPUs. In systems that have asymmetric support for the feature
621 	 * this allows KVM to leverage hardware support on the subset of cores
622 	 * that implement the feature.
623 	 *
624 	 * The architecture requires VTCR_EL2.HA to be RES0 (thus ignored by
625 	 * hardware) on implementations that do not advertise support for the
626 	 * feature. As such, setting HA unconditionally is safe, unless you
627 	 * happen to be running on a design that has unadvertised support for
628 	 * HAFDBS. Here be dragons.
629 	 */
630 	if (!cpus_have_final_cap(ARM64_WORKAROUND_AMPERE_AC03_CPU_38))
631 		vtcr |= VTCR_EL2_HA;
632 #endif /* CONFIG_ARM64_HW_AFDBM */
633 
634 	if (kvm_lpa2_is_enabled())
635 		vtcr |= VTCR_EL2_DS;
636 
637 	/* Set the vmid bits */
638 	vtcr |= (get_vmid_bits(mmfr1) == 16) ?
639 		VTCR_EL2_VS_16BIT :
640 		VTCR_EL2_VS_8BIT;
641 
642 	return vtcr;
643 }
644 
645 static bool stage2_has_fwb(struct kvm_pgtable *pgt)
646 {
647 	if (!cpus_have_final_cap(ARM64_HAS_STAGE2_FWB))
648 		return false;
649 
650 	return !(pgt->flags & KVM_PGTABLE_S2_NOFWB);
651 }
652 
653 void kvm_tlb_flush_vmid_range(struct kvm_s2_mmu *mmu,
654 				phys_addr_t addr, size_t size)
655 {
656 	unsigned long pages, inval_pages;
657 
658 	if (!system_supports_tlb_range()) {
659 		kvm_call_hyp(__kvm_tlb_flush_vmid, mmu);
660 		return;
661 	}
662 
663 	pages = size >> PAGE_SHIFT;
664 	while (pages > 0) {
665 		inval_pages = min(pages, MAX_TLBI_RANGE_PAGES);
666 		kvm_call_hyp(__kvm_tlb_flush_vmid_range, mmu, addr, inval_pages);
667 
668 		addr += inval_pages << PAGE_SHIFT;
669 		pages -= inval_pages;
670 	}
671 }
672 
673 #define KVM_S2_MEMATTR(pgt, attr) PAGE_S2_MEMATTR(attr, stage2_has_fwb(pgt))
674 
675 static int stage2_set_prot_attr(struct kvm_pgtable *pgt, enum kvm_pgtable_prot prot,
676 				kvm_pte_t *ptep)
677 {
678 	kvm_pte_t attr;
679 	u32 sh = KVM_PTE_LEAF_ATTR_LO_S2_SH_IS;
680 
681 	switch (prot & (KVM_PGTABLE_PROT_DEVICE |
682 			KVM_PGTABLE_PROT_NORMAL_NC)) {
683 	case KVM_PGTABLE_PROT_DEVICE | KVM_PGTABLE_PROT_NORMAL_NC:
684 		return -EINVAL;
685 	case KVM_PGTABLE_PROT_DEVICE:
686 		if (prot & KVM_PGTABLE_PROT_X)
687 			return -EINVAL;
688 		attr = KVM_S2_MEMATTR(pgt, DEVICE_nGnRE);
689 		break;
690 	case KVM_PGTABLE_PROT_NORMAL_NC:
691 		if (prot & KVM_PGTABLE_PROT_X)
692 			return -EINVAL;
693 		attr = KVM_S2_MEMATTR(pgt, NORMAL_NC);
694 		break;
695 	default:
696 		attr = KVM_S2_MEMATTR(pgt, NORMAL);
697 	}
698 
699 	if (!(prot & KVM_PGTABLE_PROT_X))
700 		attr |= KVM_PTE_LEAF_ATTR_HI_S2_XN;
701 
702 	if (prot & KVM_PGTABLE_PROT_R)
703 		attr |= KVM_PTE_LEAF_ATTR_LO_S2_S2AP_R;
704 
705 	if (prot & KVM_PGTABLE_PROT_W)
706 		attr |= KVM_PTE_LEAF_ATTR_LO_S2_S2AP_W;
707 
708 	if (!kvm_lpa2_is_enabled())
709 		attr |= FIELD_PREP(KVM_PTE_LEAF_ATTR_LO_S2_SH, sh);
710 
711 	attr |= KVM_PTE_LEAF_ATTR_LO_S2_AF;
712 	attr |= prot & KVM_PTE_LEAF_ATTR_HI_SW;
713 	*ptep = attr;
714 
715 	return 0;
716 }
717 
718 enum kvm_pgtable_prot kvm_pgtable_stage2_pte_prot(kvm_pte_t pte)
719 {
720 	enum kvm_pgtable_prot prot = pte & KVM_PTE_LEAF_ATTR_HI_SW;
721 
722 	if (!kvm_pte_valid(pte))
723 		return prot;
724 
725 	if (pte & KVM_PTE_LEAF_ATTR_LO_S2_S2AP_R)
726 		prot |= KVM_PGTABLE_PROT_R;
727 	if (pte & KVM_PTE_LEAF_ATTR_LO_S2_S2AP_W)
728 		prot |= KVM_PGTABLE_PROT_W;
729 	if (!(pte & KVM_PTE_LEAF_ATTR_HI_S2_XN))
730 		prot |= KVM_PGTABLE_PROT_X;
731 
732 	return prot;
733 }
734 
735 static bool stage2_pte_needs_update(kvm_pte_t old, kvm_pte_t new)
736 {
737 	if (!kvm_pte_valid(old) || !kvm_pte_valid(new))
738 		return true;
739 
740 	return ((old ^ new) & (~KVM_PTE_LEAF_ATTR_S2_PERMS));
741 }
742 
743 static bool stage2_pte_is_counted(kvm_pte_t pte)
744 {
745 	/*
746 	 * The refcount tracks valid entries as well as invalid entries if they
747 	 * encode ownership of a page to another entity than the page-table
748 	 * owner, whose id is 0.
749 	 */
750 	return !!pte;
751 }
752 
753 static bool stage2_pte_is_locked(kvm_pte_t pte)
754 {
755 	return !kvm_pte_valid(pte) && (pte & KVM_INVALID_PTE_LOCKED);
756 }
757 
758 static bool stage2_try_set_pte(const struct kvm_pgtable_visit_ctx *ctx, kvm_pte_t new)
759 {
760 	if (!kvm_pgtable_walk_shared(ctx)) {
761 		WRITE_ONCE(*ctx->ptep, new);
762 		return true;
763 	}
764 
765 	return cmpxchg(ctx->ptep, ctx->old, new) == ctx->old;
766 }
767 
768 /**
769  * stage2_try_break_pte() - Invalidates a pte according to the
770  *			    'break-before-make' requirements of the
771  *			    architecture.
772  *
773  * @ctx: context of the visited pte.
774  * @mmu: stage-2 mmu
775  *
776  * Returns: true if the pte was successfully broken.
777  *
778  * If the removed pte was valid, performs the necessary serialization and TLB
779  * invalidation for the old value. For counted ptes, drops the reference count
780  * on the containing table page.
781  */
782 static bool stage2_try_break_pte(const struct kvm_pgtable_visit_ctx *ctx,
783 				 struct kvm_s2_mmu *mmu)
784 {
785 	struct kvm_pgtable_mm_ops *mm_ops = ctx->mm_ops;
786 
787 	if (stage2_pte_is_locked(ctx->old)) {
788 		/*
789 		 * Should never occur if this walker has exclusive access to the
790 		 * page tables.
791 		 */
792 		WARN_ON(!kvm_pgtable_walk_shared(ctx));
793 		return false;
794 	}
795 
796 	if (!stage2_try_set_pte(ctx, KVM_INVALID_PTE_LOCKED))
797 		return false;
798 
799 	if (!kvm_pgtable_walk_skip_bbm_tlbi(ctx)) {
800 		/*
801 		 * Perform the appropriate TLB invalidation based on the
802 		 * evicted pte value (if any).
803 		 */
804 		if (kvm_pte_table(ctx->old, ctx->level)) {
805 			u64 size = kvm_granule_size(ctx->level);
806 			u64 addr = ALIGN_DOWN(ctx->addr, size);
807 
808 			kvm_tlb_flush_vmid_range(mmu, addr, size);
809 		} else if (kvm_pte_valid(ctx->old)) {
810 			kvm_call_hyp(__kvm_tlb_flush_vmid_ipa, mmu,
811 				     ctx->addr, ctx->level);
812 		}
813 	}
814 
815 	if (stage2_pte_is_counted(ctx->old))
816 		mm_ops->put_page(ctx->ptep);
817 
818 	return true;
819 }
820 
821 static void stage2_make_pte(const struct kvm_pgtable_visit_ctx *ctx, kvm_pte_t new)
822 {
823 	struct kvm_pgtable_mm_ops *mm_ops = ctx->mm_ops;
824 
825 	WARN_ON(!stage2_pte_is_locked(*ctx->ptep));
826 
827 	if (stage2_pte_is_counted(new))
828 		mm_ops->get_page(ctx->ptep);
829 
830 	smp_store_release(ctx->ptep, new);
831 }
832 
833 static bool stage2_unmap_defer_tlb_flush(struct kvm_pgtable *pgt)
834 {
835 	/*
836 	 * If FEAT_TLBIRANGE is implemented, defer the individual
837 	 * TLB invalidations until the entire walk is finished, and
838 	 * then use the range-based TLBI instructions to do the
839 	 * invalidations. Condition deferred TLB invalidation on the
840 	 * system supporting FWB as the optimization is entirely
841 	 * pointless when the unmap walker needs to perform CMOs.
842 	 */
843 	return system_supports_tlb_range() && stage2_has_fwb(pgt);
844 }
845 
846 static void stage2_unmap_put_pte(const struct kvm_pgtable_visit_ctx *ctx,
847 				struct kvm_s2_mmu *mmu,
848 				struct kvm_pgtable_mm_ops *mm_ops)
849 {
850 	struct kvm_pgtable *pgt = ctx->arg;
851 
852 	/*
853 	 * Clear the existing PTE, and perform break-before-make if it was
854 	 * valid. Depending on the system support, defer the TLB maintenance
855 	 * for the same until the entire unmap walk is completed.
856 	 */
857 	if (kvm_pte_valid(ctx->old)) {
858 		kvm_clear_pte(ctx->ptep);
859 
860 		if (kvm_pte_table(ctx->old, ctx->level)) {
861 			kvm_call_hyp(__kvm_tlb_flush_vmid_ipa, mmu, ctx->addr,
862 				     TLBI_TTL_UNKNOWN);
863 		} else if (!stage2_unmap_defer_tlb_flush(pgt)) {
864 			kvm_call_hyp(__kvm_tlb_flush_vmid_ipa, mmu, ctx->addr,
865 				     ctx->level);
866 		}
867 	}
868 
869 	mm_ops->put_page(ctx->ptep);
870 }
871 
872 static bool stage2_pte_cacheable(struct kvm_pgtable *pgt, kvm_pte_t pte)
873 {
874 	u64 memattr = pte & KVM_PTE_LEAF_ATTR_LO_S2_MEMATTR;
875 	return kvm_pte_valid(pte) && memattr == KVM_S2_MEMATTR(pgt, NORMAL);
876 }
877 
878 static bool stage2_pte_executable(kvm_pte_t pte)
879 {
880 	return kvm_pte_valid(pte) && !(pte & KVM_PTE_LEAF_ATTR_HI_S2_XN);
881 }
882 
883 static u64 stage2_map_walker_phys_addr(const struct kvm_pgtable_visit_ctx *ctx,
884 				       const struct stage2_map_data *data)
885 {
886 	u64 phys = data->phys;
887 
888 	/*
889 	 * Stage-2 walks to update ownership data are communicated to the map
890 	 * walker using an invalid PA. Avoid offsetting an already invalid PA,
891 	 * which could overflow and make the address valid again.
892 	 */
893 	if (!kvm_phys_is_valid(phys))
894 		return phys;
895 
896 	/*
897 	 * Otherwise, work out the correct PA based on how far the walk has
898 	 * gotten.
899 	 */
900 	return phys + (ctx->addr - ctx->start);
901 }
902 
903 static bool stage2_leaf_mapping_allowed(const struct kvm_pgtable_visit_ctx *ctx,
904 					struct stage2_map_data *data)
905 {
906 	u64 phys = stage2_map_walker_phys_addr(ctx, data);
907 
908 	if (data->force_pte && ctx->level < KVM_PGTABLE_LAST_LEVEL)
909 		return false;
910 
911 	return kvm_block_mapping_supported(ctx, phys);
912 }
913 
914 static int stage2_map_walker_try_leaf(const struct kvm_pgtable_visit_ctx *ctx,
915 				      struct stage2_map_data *data)
916 {
917 	kvm_pte_t new;
918 	u64 phys = stage2_map_walker_phys_addr(ctx, data);
919 	u64 granule = kvm_granule_size(ctx->level);
920 	struct kvm_pgtable *pgt = data->mmu->pgt;
921 	struct kvm_pgtable_mm_ops *mm_ops = ctx->mm_ops;
922 
923 	if (!stage2_leaf_mapping_allowed(ctx, data))
924 		return -E2BIG;
925 
926 	if (kvm_phys_is_valid(phys))
927 		new = kvm_init_valid_leaf_pte(phys, data->attr, ctx->level);
928 	else
929 		new = kvm_init_invalid_leaf_owner(data->owner_id);
930 
931 	/*
932 	 * Skip updating the PTE if we are trying to recreate the exact
933 	 * same mapping or only change the access permissions. Instead,
934 	 * the vCPU will exit one more time from guest if still needed
935 	 * and then go through the path of relaxing permissions.
936 	 */
937 	if (!stage2_pte_needs_update(ctx->old, new))
938 		return -EAGAIN;
939 
940 	/* If we're only changing software bits, then store them and go! */
941 	if (!kvm_pgtable_walk_shared(ctx) &&
942 	    !((ctx->old ^ new) & ~KVM_PTE_LEAF_ATTR_HI_SW)) {
943 		bool old_is_counted = stage2_pte_is_counted(ctx->old);
944 
945 		if (old_is_counted != stage2_pte_is_counted(new)) {
946 			if (old_is_counted)
947 				mm_ops->put_page(ctx->ptep);
948 			else
949 				mm_ops->get_page(ctx->ptep);
950 		}
951 		WARN_ON_ONCE(!stage2_try_set_pte(ctx, new));
952 		return 0;
953 	}
954 
955 	if (!stage2_try_break_pte(ctx, data->mmu))
956 		return -EAGAIN;
957 
958 	/* Perform CMOs before installation of the guest stage-2 PTE */
959 	if (!kvm_pgtable_walk_skip_cmo(ctx) && mm_ops->dcache_clean_inval_poc &&
960 	    stage2_pte_cacheable(pgt, new))
961 		mm_ops->dcache_clean_inval_poc(kvm_pte_follow(new, mm_ops),
962 					       granule);
963 
964 	if (!kvm_pgtable_walk_skip_cmo(ctx) && mm_ops->icache_inval_pou &&
965 	    stage2_pte_executable(new))
966 		mm_ops->icache_inval_pou(kvm_pte_follow(new, mm_ops), granule);
967 
968 	stage2_make_pte(ctx, new);
969 
970 	return 0;
971 }
972 
973 static int stage2_map_walk_table_pre(const struct kvm_pgtable_visit_ctx *ctx,
974 				     struct stage2_map_data *data)
975 {
976 	struct kvm_pgtable_mm_ops *mm_ops = ctx->mm_ops;
977 	kvm_pte_t *childp = kvm_pte_follow(ctx->old, mm_ops);
978 	int ret;
979 
980 	if (!stage2_leaf_mapping_allowed(ctx, data))
981 		return 0;
982 
983 	ret = stage2_map_walker_try_leaf(ctx, data);
984 	if (ret)
985 		return ret;
986 
987 	mm_ops->free_unlinked_table(childp, ctx->level);
988 	return 0;
989 }
990 
991 static int stage2_map_walk_leaf(const struct kvm_pgtable_visit_ctx *ctx,
992 				struct stage2_map_data *data)
993 {
994 	struct kvm_pgtable_mm_ops *mm_ops = ctx->mm_ops;
995 	kvm_pte_t *childp, new;
996 	int ret;
997 
998 	ret = stage2_map_walker_try_leaf(ctx, data);
999 	if (ret != -E2BIG)
1000 		return ret;
1001 
1002 	if (WARN_ON(ctx->level == KVM_PGTABLE_LAST_LEVEL))
1003 		return -EINVAL;
1004 
1005 	if (!data->memcache)
1006 		return -ENOMEM;
1007 
1008 	childp = mm_ops->zalloc_page(data->memcache);
1009 	if (!childp)
1010 		return -ENOMEM;
1011 
1012 	if (!stage2_try_break_pte(ctx, data->mmu)) {
1013 		mm_ops->put_page(childp);
1014 		return -EAGAIN;
1015 	}
1016 
1017 	/*
1018 	 * If we've run into an existing block mapping then replace it with
1019 	 * a table. Accesses beyond 'end' that fall within the new table
1020 	 * will be mapped lazily.
1021 	 */
1022 	new = kvm_init_table_pte(childp, mm_ops);
1023 	stage2_make_pte(ctx, new);
1024 
1025 	return 0;
1026 }
1027 
1028 /*
1029  * The TABLE_PRE callback runs for table entries on the way down, looking
1030  * for table entries which we could conceivably replace with a block entry
1031  * for this mapping. If it finds one it replaces the entry and calls
1032  * kvm_pgtable_mm_ops::free_unlinked_table() to tear down the detached table.
1033  *
1034  * Otherwise, the LEAF callback performs the mapping at the existing leaves
1035  * instead.
1036  */
1037 static int stage2_map_walker(const struct kvm_pgtable_visit_ctx *ctx,
1038 			     enum kvm_pgtable_walk_flags visit)
1039 {
1040 	struct stage2_map_data *data = ctx->arg;
1041 
1042 	switch (visit) {
1043 	case KVM_PGTABLE_WALK_TABLE_PRE:
1044 		return stage2_map_walk_table_pre(ctx, data);
1045 	case KVM_PGTABLE_WALK_LEAF:
1046 		return stage2_map_walk_leaf(ctx, data);
1047 	default:
1048 		return -EINVAL;
1049 	}
1050 }
1051 
1052 int kvm_pgtable_stage2_map(struct kvm_pgtable *pgt, u64 addr, u64 size,
1053 			   u64 phys, enum kvm_pgtable_prot prot,
1054 			   void *mc, enum kvm_pgtable_walk_flags flags)
1055 {
1056 	int ret;
1057 	struct stage2_map_data map_data = {
1058 		.phys		= ALIGN_DOWN(phys, PAGE_SIZE),
1059 		.mmu		= pgt->mmu,
1060 		.memcache	= mc,
1061 		.force_pte	= pgt->force_pte_cb && pgt->force_pte_cb(addr, addr + size, prot),
1062 	};
1063 	struct kvm_pgtable_walker walker = {
1064 		.cb		= stage2_map_walker,
1065 		.flags		= flags |
1066 				  KVM_PGTABLE_WALK_TABLE_PRE |
1067 				  KVM_PGTABLE_WALK_LEAF,
1068 		.arg		= &map_data,
1069 	};
1070 
1071 	if (WARN_ON((pgt->flags & KVM_PGTABLE_S2_IDMAP) && (addr != phys)))
1072 		return -EINVAL;
1073 
1074 	ret = stage2_set_prot_attr(pgt, prot, &map_data.attr);
1075 	if (ret)
1076 		return ret;
1077 
1078 	ret = kvm_pgtable_walk(pgt, addr, size, &walker);
1079 	dsb(ishst);
1080 	return ret;
1081 }
1082 
1083 int kvm_pgtable_stage2_set_owner(struct kvm_pgtable *pgt, u64 addr, u64 size,
1084 				 void *mc, u8 owner_id)
1085 {
1086 	int ret;
1087 	struct stage2_map_data map_data = {
1088 		.phys		= KVM_PHYS_INVALID,
1089 		.mmu		= pgt->mmu,
1090 		.memcache	= mc,
1091 		.owner_id	= owner_id,
1092 		.force_pte	= true,
1093 	};
1094 	struct kvm_pgtable_walker walker = {
1095 		.cb		= stage2_map_walker,
1096 		.flags		= KVM_PGTABLE_WALK_TABLE_PRE |
1097 				  KVM_PGTABLE_WALK_LEAF,
1098 		.arg		= &map_data,
1099 	};
1100 
1101 	if (owner_id > KVM_MAX_OWNER_ID)
1102 		return -EINVAL;
1103 
1104 	ret = kvm_pgtable_walk(pgt, addr, size, &walker);
1105 	return ret;
1106 }
1107 
1108 static int stage2_unmap_walker(const struct kvm_pgtable_visit_ctx *ctx,
1109 			       enum kvm_pgtable_walk_flags visit)
1110 {
1111 	struct kvm_pgtable *pgt = ctx->arg;
1112 	struct kvm_s2_mmu *mmu = pgt->mmu;
1113 	struct kvm_pgtable_mm_ops *mm_ops = ctx->mm_ops;
1114 	kvm_pte_t *childp = NULL;
1115 	bool need_flush = false;
1116 
1117 	if (!kvm_pte_valid(ctx->old)) {
1118 		if (stage2_pte_is_counted(ctx->old)) {
1119 			kvm_clear_pte(ctx->ptep);
1120 			mm_ops->put_page(ctx->ptep);
1121 		}
1122 		return 0;
1123 	}
1124 
1125 	if (kvm_pte_table(ctx->old, ctx->level)) {
1126 		childp = kvm_pte_follow(ctx->old, mm_ops);
1127 
1128 		if (mm_ops->page_count(childp) != 1)
1129 			return 0;
1130 	} else if (stage2_pte_cacheable(pgt, ctx->old)) {
1131 		need_flush = !stage2_has_fwb(pgt);
1132 	}
1133 
1134 	/*
1135 	 * This is similar to the map() path in that we unmap the entire
1136 	 * block entry and rely on the remaining portions being faulted
1137 	 * back lazily.
1138 	 */
1139 	stage2_unmap_put_pte(ctx, mmu, mm_ops);
1140 
1141 	if (need_flush && mm_ops->dcache_clean_inval_poc)
1142 		mm_ops->dcache_clean_inval_poc(kvm_pte_follow(ctx->old, mm_ops),
1143 					       kvm_granule_size(ctx->level));
1144 
1145 	if (childp)
1146 		mm_ops->put_page(childp);
1147 
1148 	return 0;
1149 }
1150 
1151 int kvm_pgtable_stage2_unmap(struct kvm_pgtable *pgt, u64 addr, u64 size)
1152 {
1153 	int ret;
1154 	struct kvm_pgtable_walker walker = {
1155 		.cb	= stage2_unmap_walker,
1156 		.arg	= pgt,
1157 		.flags	= KVM_PGTABLE_WALK_LEAF | KVM_PGTABLE_WALK_TABLE_POST,
1158 	};
1159 
1160 	ret = kvm_pgtable_walk(pgt, addr, size, &walker);
1161 	if (stage2_unmap_defer_tlb_flush(pgt))
1162 		/* Perform the deferred TLB invalidations */
1163 		kvm_tlb_flush_vmid_range(pgt->mmu, addr, size);
1164 
1165 	return ret;
1166 }
1167 
1168 struct stage2_attr_data {
1169 	kvm_pte_t			attr_set;
1170 	kvm_pte_t			attr_clr;
1171 	kvm_pte_t			pte;
1172 	s8				level;
1173 };
1174 
1175 static int stage2_attr_walker(const struct kvm_pgtable_visit_ctx *ctx,
1176 			      enum kvm_pgtable_walk_flags visit)
1177 {
1178 	kvm_pte_t pte = ctx->old;
1179 	struct stage2_attr_data *data = ctx->arg;
1180 	struct kvm_pgtable_mm_ops *mm_ops = ctx->mm_ops;
1181 
1182 	if (!kvm_pte_valid(ctx->old))
1183 		return -EAGAIN;
1184 
1185 	data->level = ctx->level;
1186 	data->pte = pte;
1187 	pte &= ~data->attr_clr;
1188 	pte |= data->attr_set;
1189 
1190 	/*
1191 	 * We may race with the CPU trying to set the access flag here,
1192 	 * but worst-case the access flag update gets lost and will be
1193 	 * set on the next access instead.
1194 	 */
1195 	if (data->pte != pte) {
1196 		/*
1197 		 * Invalidate instruction cache before updating the guest
1198 		 * stage-2 PTE if we are going to add executable permission.
1199 		 */
1200 		if (mm_ops->icache_inval_pou &&
1201 		    stage2_pte_executable(pte) && !stage2_pte_executable(ctx->old))
1202 			mm_ops->icache_inval_pou(kvm_pte_follow(pte, mm_ops),
1203 						  kvm_granule_size(ctx->level));
1204 
1205 		if (!stage2_try_set_pte(ctx, pte))
1206 			return -EAGAIN;
1207 	}
1208 
1209 	return 0;
1210 }
1211 
1212 static int stage2_update_leaf_attrs(struct kvm_pgtable *pgt, u64 addr,
1213 				    u64 size, kvm_pte_t attr_set,
1214 				    kvm_pte_t attr_clr, kvm_pte_t *orig_pte,
1215 				    s8 *level, enum kvm_pgtable_walk_flags flags)
1216 {
1217 	int ret;
1218 	kvm_pte_t attr_mask = KVM_PTE_LEAF_ATTR_LO | KVM_PTE_LEAF_ATTR_HI;
1219 	struct stage2_attr_data data = {
1220 		.attr_set	= attr_set & attr_mask,
1221 		.attr_clr	= attr_clr & attr_mask,
1222 	};
1223 	struct kvm_pgtable_walker walker = {
1224 		.cb		= stage2_attr_walker,
1225 		.arg		= &data,
1226 		.flags		= flags | KVM_PGTABLE_WALK_LEAF,
1227 	};
1228 
1229 	ret = kvm_pgtable_walk(pgt, addr, size, &walker);
1230 	if (ret)
1231 		return ret;
1232 
1233 	if (orig_pte)
1234 		*orig_pte = data.pte;
1235 
1236 	if (level)
1237 		*level = data.level;
1238 	return 0;
1239 }
1240 
1241 int kvm_pgtable_stage2_wrprotect(struct kvm_pgtable *pgt, u64 addr, u64 size)
1242 {
1243 	return stage2_update_leaf_attrs(pgt, addr, size, 0,
1244 					KVM_PTE_LEAF_ATTR_LO_S2_S2AP_W,
1245 					NULL, NULL, 0);
1246 }
1247 
1248 kvm_pte_t kvm_pgtable_stage2_mkyoung(struct kvm_pgtable *pgt, u64 addr)
1249 {
1250 	kvm_pte_t pte = 0;
1251 	int ret;
1252 
1253 	ret = stage2_update_leaf_attrs(pgt, addr, 1, KVM_PTE_LEAF_ATTR_LO_S2_AF, 0,
1254 				       &pte, NULL,
1255 				       KVM_PGTABLE_WALK_HANDLE_FAULT |
1256 				       KVM_PGTABLE_WALK_SHARED);
1257 	if (!ret)
1258 		dsb(ishst);
1259 
1260 	return pte;
1261 }
1262 
1263 struct stage2_age_data {
1264 	bool	mkold;
1265 	bool	young;
1266 };
1267 
1268 static int stage2_age_walker(const struct kvm_pgtable_visit_ctx *ctx,
1269 			     enum kvm_pgtable_walk_flags visit)
1270 {
1271 	kvm_pte_t new = ctx->old & ~KVM_PTE_LEAF_ATTR_LO_S2_AF;
1272 	struct stage2_age_data *data = ctx->arg;
1273 
1274 	if (!kvm_pte_valid(ctx->old) || new == ctx->old)
1275 		return 0;
1276 
1277 	data->young = true;
1278 
1279 	/*
1280 	 * stage2_age_walker() is always called while holding the MMU lock for
1281 	 * write, so this will always succeed. Nonetheless, this deliberately
1282 	 * follows the race detection pattern of the other stage-2 walkers in
1283 	 * case the locking mechanics of the MMU notifiers is ever changed.
1284 	 */
1285 	if (data->mkold && !stage2_try_set_pte(ctx, new))
1286 		return -EAGAIN;
1287 
1288 	/*
1289 	 * "But where's the TLBI?!", you scream.
1290 	 * "Over in the core code", I sigh.
1291 	 *
1292 	 * See the '->clear_flush_young()' callback on the KVM mmu notifier.
1293 	 */
1294 	return 0;
1295 }
1296 
1297 bool kvm_pgtable_stage2_test_clear_young(struct kvm_pgtable *pgt, u64 addr,
1298 					 u64 size, bool mkold)
1299 {
1300 	struct stage2_age_data data = {
1301 		.mkold		= mkold,
1302 	};
1303 	struct kvm_pgtable_walker walker = {
1304 		.cb		= stage2_age_walker,
1305 		.arg		= &data,
1306 		.flags		= KVM_PGTABLE_WALK_LEAF,
1307 	};
1308 
1309 	WARN_ON(kvm_pgtable_walk(pgt, addr, size, &walker));
1310 	return data.young;
1311 }
1312 
1313 int kvm_pgtable_stage2_relax_perms(struct kvm_pgtable *pgt, u64 addr,
1314 				   enum kvm_pgtable_prot prot)
1315 {
1316 	int ret;
1317 	s8 level;
1318 	kvm_pte_t set = 0, clr = 0;
1319 
1320 	if (prot & KVM_PTE_LEAF_ATTR_HI_SW)
1321 		return -EINVAL;
1322 
1323 	if (prot & KVM_PGTABLE_PROT_R)
1324 		set |= KVM_PTE_LEAF_ATTR_LO_S2_S2AP_R;
1325 
1326 	if (prot & KVM_PGTABLE_PROT_W)
1327 		set |= KVM_PTE_LEAF_ATTR_LO_S2_S2AP_W;
1328 
1329 	if (prot & KVM_PGTABLE_PROT_X)
1330 		clr |= KVM_PTE_LEAF_ATTR_HI_S2_XN;
1331 
1332 	ret = stage2_update_leaf_attrs(pgt, addr, 1, set, clr, NULL, &level,
1333 				       KVM_PGTABLE_WALK_HANDLE_FAULT |
1334 				       KVM_PGTABLE_WALK_SHARED);
1335 	if (!ret || ret == -EAGAIN)
1336 		kvm_call_hyp(__kvm_tlb_flush_vmid_ipa_nsh, pgt->mmu, addr, level);
1337 	return ret;
1338 }
1339 
1340 static int stage2_flush_walker(const struct kvm_pgtable_visit_ctx *ctx,
1341 			       enum kvm_pgtable_walk_flags visit)
1342 {
1343 	struct kvm_pgtable *pgt = ctx->arg;
1344 	struct kvm_pgtable_mm_ops *mm_ops = pgt->mm_ops;
1345 
1346 	if (!stage2_pte_cacheable(pgt, ctx->old))
1347 		return 0;
1348 
1349 	if (mm_ops->dcache_clean_inval_poc)
1350 		mm_ops->dcache_clean_inval_poc(kvm_pte_follow(ctx->old, mm_ops),
1351 					       kvm_granule_size(ctx->level));
1352 	return 0;
1353 }
1354 
1355 int kvm_pgtable_stage2_flush(struct kvm_pgtable *pgt, u64 addr, u64 size)
1356 {
1357 	struct kvm_pgtable_walker walker = {
1358 		.cb	= stage2_flush_walker,
1359 		.flags	= KVM_PGTABLE_WALK_LEAF,
1360 		.arg	= pgt,
1361 	};
1362 
1363 	if (stage2_has_fwb(pgt))
1364 		return 0;
1365 
1366 	return kvm_pgtable_walk(pgt, addr, size, &walker);
1367 }
1368 
1369 kvm_pte_t *kvm_pgtable_stage2_create_unlinked(struct kvm_pgtable *pgt,
1370 					      u64 phys, s8 level,
1371 					      enum kvm_pgtable_prot prot,
1372 					      void *mc, bool force_pte)
1373 {
1374 	struct stage2_map_data map_data = {
1375 		.phys		= phys,
1376 		.mmu		= pgt->mmu,
1377 		.memcache	= mc,
1378 		.force_pte	= force_pte,
1379 	};
1380 	struct kvm_pgtable_walker walker = {
1381 		.cb		= stage2_map_walker,
1382 		.flags		= KVM_PGTABLE_WALK_LEAF |
1383 				  KVM_PGTABLE_WALK_SKIP_BBM_TLBI |
1384 				  KVM_PGTABLE_WALK_SKIP_CMO,
1385 		.arg		= &map_data,
1386 	};
1387 	/*
1388 	 * The input address (.addr) is irrelevant for walking an
1389 	 * unlinked table. Construct an ambiguous IA range to map
1390 	 * kvm_granule_size(level) worth of memory.
1391 	 */
1392 	struct kvm_pgtable_walk_data data = {
1393 		.walker	= &walker,
1394 		.addr	= 0,
1395 		.end	= kvm_granule_size(level),
1396 	};
1397 	struct kvm_pgtable_mm_ops *mm_ops = pgt->mm_ops;
1398 	kvm_pte_t *pgtable;
1399 	int ret;
1400 
1401 	if (!IS_ALIGNED(phys, kvm_granule_size(level)))
1402 		return ERR_PTR(-EINVAL);
1403 
1404 	ret = stage2_set_prot_attr(pgt, prot, &map_data.attr);
1405 	if (ret)
1406 		return ERR_PTR(ret);
1407 
1408 	pgtable = mm_ops->zalloc_page(mc);
1409 	if (!pgtable)
1410 		return ERR_PTR(-ENOMEM);
1411 
1412 	ret = __kvm_pgtable_walk(&data, mm_ops, (kvm_pteref_t)pgtable,
1413 				 level + 1);
1414 	if (ret) {
1415 		kvm_pgtable_stage2_free_unlinked(mm_ops, pgtable, level);
1416 		return ERR_PTR(ret);
1417 	}
1418 
1419 	return pgtable;
1420 }
1421 
1422 /*
1423  * Get the number of page-tables needed to replace a block with a
1424  * fully populated tree up to the PTE entries. Note that @level is
1425  * interpreted as in "level @level entry".
1426  */
1427 static int stage2_block_get_nr_page_tables(s8 level)
1428 {
1429 	switch (level) {
1430 	case 1:
1431 		return PTRS_PER_PTE + 1;
1432 	case 2:
1433 		return 1;
1434 	case 3:
1435 		return 0;
1436 	default:
1437 		WARN_ON_ONCE(level < KVM_PGTABLE_MIN_BLOCK_LEVEL ||
1438 			     level > KVM_PGTABLE_LAST_LEVEL);
1439 		return -EINVAL;
1440 	};
1441 }
1442 
1443 static int stage2_split_walker(const struct kvm_pgtable_visit_ctx *ctx,
1444 			       enum kvm_pgtable_walk_flags visit)
1445 {
1446 	struct kvm_pgtable_mm_ops *mm_ops = ctx->mm_ops;
1447 	struct kvm_mmu_memory_cache *mc = ctx->arg;
1448 	struct kvm_s2_mmu *mmu;
1449 	kvm_pte_t pte = ctx->old, new, *childp;
1450 	enum kvm_pgtable_prot prot;
1451 	s8 level = ctx->level;
1452 	bool force_pte;
1453 	int nr_pages;
1454 	u64 phys;
1455 
1456 	/* No huge-pages exist at the last level */
1457 	if (level == KVM_PGTABLE_LAST_LEVEL)
1458 		return 0;
1459 
1460 	/* We only split valid block mappings */
1461 	if (!kvm_pte_valid(pte))
1462 		return 0;
1463 
1464 	nr_pages = stage2_block_get_nr_page_tables(level);
1465 	if (nr_pages < 0)
1466 		return nr_pages;
1467 
1468 	if (mc->nobjs >= nr_pages) {
1469 		/* Build a tree mapped down to the PTE granularity. */
1470 		force_pte = true;
1471 	} else {
1472 		/*
1473 		 * Don't force PTEs, so create_unlinked() below does
1474 		 * not populate the tree up to the PTE level. The
1475 		 * consequence is that the call will require a single
1476 		 * page of level 2 entries at level 1, or a single
1477 		 * page of PTEs at level 2. If we are at level 1, the
1478 		 * PTEs will be created recursively.
1479 		 */
1480 		force_pte = false;
1481 		nr_pages = 1;
1482 	}
1483 
1484 	if (mc->nobjs < nr_pages)
1485 		return -ENOMEM;
1486 
1487 	mmu = container_of(mc, struct kvm_s2_mmu, split_page_cache);
1488 	phys = kvm_pte_to_phys(pte);
1489 	prot = kvm_pgtable_stage2_pte_prot(pte);
1490 
1491 	childp = kvm_pgtable_stage2_create_unlinked(mmu->pgt, phys,
1492 						    level, prot, mc, force_pte);
1493 	if (IS_ERR(childp))
1494 		return PTR_ERR(childp);
1495 
1496 	if (!stage2_try_break_pte(ctx, mmu)) {
1497 		kvm_pgtable_stage2_free_unlinked(mm_ops, childp, level);
1498 		return -EAGAIN;
1499 	}
1500 
1501 	/*
1502 	 * Note, the contents of the page table are guaranteed to be made
1503 	 * visible before the new PTE is assigned because stage2_make_pte()
1504 	 * writes the PTE using smp_store_release().
1505 	 */
1506 	new = kvm_init_table_pte(childp, mm_ops);
1507 	stage2_make_pte(ctx, new);
1508 	return 0;
1509 }
1510 
1511 int kvm_pgtable_stage2_split(struct kvm_pgtable *pgt, u64 addr, u64 size,
1512 			     struct kvm_mmu_memory_cache *mc)
1513 {
1514 	struct kvm_pgtable_walker walker = {
1515 		.cb	= stage2_split_walker,
1516 		.flags	= KVM_PGTABLE_WALK_LEAF,
1517 		.arg	= mc,
1518 	};
1519 	int ret;
1520 
1521 	ret = kvm_pgtable_walk(pgt, addr, size, &walker);
1522 	dsb(ishst);
1523 	return ret;
1524 }
1525 
1526 int __kvm_pgtable_stage2_init(struct kvm_pgtable *pgt, struct kvm_s2_mmu *mmu,
1527 			      struct kvm_pgtable_mm_ops *mm_ops,
1528 			      enum kvm_pgtable_stage2_flags flags,
1529 			      kvm_pgtable_force_pte_cb_t force_pte_cb)
1530 {
1531 	size_t pgd_sz;
1532 	u64 vtcr = mmu->vtcr;
1533 	u32 ia_bits = VTCR_EL2_IPA(vtcr);
1534 	u32 sl0 = FIELD_GET(VTCR_EL2_SL0_MASK, vtcr);
1535 	s8 start_level = VTCR_EL2_TGRAN_SL0_BASE - sl0;
1536 
1537 	pgd_sz = kvm_pgd_pages(ia_bits, start_level) * PAGE_SIZE;
1538 	pgt->pgd = (kvm_pteref_t)mm_ops->zalloc_pages_exact(pgd_sz);
1539 	if (!pgt->pgd)
1540 		return -ENOMEM;
1541 
1542 	pgt->ia_bits		= ia_bits;
1543 	pgt->start_level	= start_level;
1544 	pgt->mm_ops		= mm_ops;
1545 	pgt->mmu		= mmu;
1546 	pgt->flags		= flags;
1547 	pgt->force_pte_cb	= force_pte_cb;
1548 
1549 	/* Ensure zeroed PGD pages are visible to the hardware walker */
1550 	dsb(ishst);
1551 	return 0;
1552 }
1553 
1554 size_t kvm_pgtable_stage2_pgd_size(u64 vtcr)
1555 {
1556 	u32 ia_bits = VTCR_EL2_IPA(vtcr);
1557 	u32 sl0 = FIELD_GET(VTCR_EL2_SL0_MASK, vtcr);
1558 	s8 start_level = VTCR_EL2_TGRAN_SL0_BASE - sl0;
1559 
1560 	return kvm_pgd_pages(ia_bits, start_level) * PAGE_SIZE;
1561 }
1562 
1563 static int stage2_free_walker(const struct kvm_pgtable_visit_ctx *ctx,
1564 			      enum kvm_pgtable_walk_flags visit)
1565 {
1566 	struct kvm_pgtable_mm_ops *mm_ops = ctx->mm_ops;
1567 
1568 	if (!stage2_pte_is_counted(ctx->old))
1569 		return 0;
1570 
1571 	mm_ops->put_page(ctx->ptep);
1572 
1573 	if (kvm_pte_table(ctx->old, ctx->level))
1574 		mm_ops->put_page(kvm_pte_follow(ctx->old, mm_ops));
1575 
1576 	return 0;
1577 }
1578 
1579 void kvm_pgtable_stage2_destroy(struct kvm_pgtable *pgt)
1580 {
1581 	size_t pgd_sz;
1582 	struct kvm_pgtable_walker walker = {
1583 		.cb	= stage2_free_walker,
1584 		.flags	= KVM_PGTABLE_WALK_LEAF |
1585 			  KVM_PGTABLE_WALK_TABLE_POST,
1586 	};
1587 
1588 	WARN_ON(kvm_pgtable_walk(pgt, 0, BIT(pgt->ia_bits), &walker));
1589 	pgd_sz = kvm_pgd_pages(pgt->ia_bits, pgt->start_level) * PAGE_SIZE;
1590 	pgt->mm_ops->free_pages_exact(kvm_dereference_pteref(&walker, pgt->pgd), pgd_sz);
1591 	pgt->pgd = NULL;
1592 }
1593 
1594 void kvm_pgtable_stage2_free_unlinked(struct kvm_pgtable_mm_ops *mm_ops, void *pgtable, s8 level)
1595 {
1596 	kvm_pteref_t ptep = (kvm_pteref_t)pgtable;
1597 	struct kvm_pgtable_walker walker = {
1598 		.cb	= stage2_free_walker,
1599 		.flags	= KVM_PGTABLE_WALK_LEAF |
1600 			  KVM_PGTABLE_WALK_TABLE_POST,
1601 	};
1602 	struct kvm_pgtable_walk_data data = {
1603 		.walker	= &walker,
1604 
1605 		/*
1606 		 * At this point the IPA really doesn't matter, as the page
1607 		 * table being traversed has already been removed from the stage
1608 		 * 2. Set an appropriate range to cover the entire page table.
1609 		 */
1610 		.addr	= 0,
1611 		.end	= kvm_granule_size(level),
1612 	};
1613 
1614 	WARN_ON(__kvm_pgtable_walk(&data, mm_ops, ptep, level + 1));
1615 
1616 	WARN_ON(mm_ops->page_count(pgtable) != 1);
1617 	mm_ops->put_page(pgtable);
1618 }
1619