xref: /optee_os/core/arch/arm/mm/tee_pager.c (revision 8bbd9b374a51a1b8617796aae8a70c271543357f)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2016, Linaro Limited
4  * Copyright (c) 2014, STMicroelectronics International N.V.
5  */
6 
7 #include <arm.h>
8 #include <assert.h>
9 #include <io.h>
10 #include <keep.h>
11 #include <kernel/abort.h>
12 #include <kernel/asan.h>
13 #include <kernel/cache_helpers.h>
14 #include <kernel/panic.h>
15 #include <kernel/spinlock.h>
16 #include <kernel/tee_misc.h>
17 #include <kernel/tee_ta_manager.h>
18 #include <kernel/thread.h>
19 #include <kernel/tlb_helpers.h>
20 #include <mm/core_memprot.h>
21 #include <mm/fobj.h>
22 #include <mm/tee_mm.h>
23 #include <mm/tee_pager.h>
24 #include <stdlib.h>
25 #include <sys/queue.h>
26 #include <tee_api_defines.h>
27 #include <trace.h>
28 #include <types_ext.h>
29 #include <utee_defines.h>
30 #include <util.h>
31 
32 
33 static struct tee_pager_area_head tee_pager_area_head =
34 	TAILQ_HEAD_INITIALIZER(tee_pager_area_head);
35 
36 #define INVALID_PGIDX		UINT_MAX
37 #define PMEM_FLAG_DIRTY		BIT(0)
38 #define PMEM_FLAG_HIDDEN	BIT(1)
39 
40 /*
41  * struct tee_pager_pmem - Represents a physical page used for paging.
42  *
43  * @flags	flags defined by PMEM_FLAG_* above
44  * @fobj_pgidx	index of the page in the @fobj
45  * @fobj	File object of which a page is made visible.
46  * @va_alias	Virtual address where the physical page always is aliased.
47  *		Used during remapping of the page when the content need to
48  *		be updated before it's available at the new location.
49  */
50 struct tee_pager_pmem {
51 	unsigned int flags;
52 	unsigned int fobj_pgidx;
53 	struct fobj *fobj;
54 	void *va_alias;
55 	TAILQ_ENTRY(tee_pager_pmem) link;
56 };
57 
58 /* The list of physical pages. The first page in the list is the oldest */
59 TAILQ_HEAD(tee_pager_pmem_head, tee_pager_pmem);
60 
61 static struct tee_pager_pmem_head tee_pager_pmem_head =
62 	TAILQ_HEAD_INITIALIZER(tee_pager_pmem_head);
63 
64 static struct tee_pager_pmem_head tee_pager_lock_pmem_head =
65 	TAILQ_HEAD_INITIALIZER(tee_pager_lock_pmem_head);
66 
67 /* number of pages hidden */
68 #define TEE_PAGER_NHIDE (tee_pager_npages / 3)
69 
70 /* Number of registered physical pages, used hiding pages. */
71 static size_t tee_pager_npages;
72 
73 #ifdef CFG_WITH_STATS
74 static struct tee_pager_stats pager_stats;
75 
76 static inline void incr_ro_hits(void)
77 {
78 	pager_stats.ro_hits++;
79 }
80 
81 static inline void incr_rw_hits(void)
82 {
83 	pager_stats.rw_hits++;
84 }
85 
86 static inline void incr_hidden_hits(void)
87 {
88 	pager_stats.hidden_hits++;
89 }
90 
91 static inline void incr_zi_released(void)
92 {
93 	pager_stats.zi_released++;
94 }
95 
96 static inline void incr_npages_all(void)
97 {
98 	pager_stats.npages_all++;
99 }
100 
101 static inline void set_npages(void)
102 {
103 	pager_stats.npages = tee_pager_npages;
104 }
105 
106 void tee_pager_get_stats(struct tee_pager_stats *stats)
107 {
108 	*stats = pager_stats;
109 
110 	pager_stats.hidden_hits = 0;
111 	pager_stats.ro_hits = 0;
112 	pager_stats.rw_hits = 0;
113 	pager_stats.zi_released = 0;
114 }
115 
116 #else /* CFG_WITH_STATS */
117 static inline void incr_ro_hits(void) { }
118 static inline void incr_rw_hits(void) { }
119 static inline void incr_hidden_hits(void) { }
120 static inline void incr_zi_released(void) { }
121 static inline void incr_npages_all(void) { }
122 static inline void set_npages(void) { }
123 
124 void tee_pager_get_stats(struct tee_pager_stats *stats)
125 {
126 	memset(stats, 0, sizeof(struct tee_pager_stats));
127 }
128 #endif /* CFG_WITH_STATS */
129 
130 #define TBL_NUM_ENTRIES	(CORE_MMU_PGDIR_SIZE / SMALL_PAGE_SIZE)
131 #define TBL_LEVEL	CORE_MMU_PGDIR_LEVEL
132 #define TBL_SHIFT	SMALL_PAGE_SHIFT
133 
134 #define EFFECTIVE_VA_SIZE \
135 	(ROUNDUP(TEE_RAM_VA_START + TEE_RAM_VA_SIZE, \
136 		 CORE_MMU_PGDIR_SIZE) - \
137 	 ROUNDDOWN(TEE_RAM_VA_START, CORE_MMU_PGDIR_SIZE))
138 
139 static struct pager_table {
140 	struct pgt pgt;
141 	struct core_mmu_table_info tbl_info;
142 } pager_tables[EFFECTIVE_VA_SIZE / CORE_MMU_PGDIR_SIZE];
143 
144 static unsigned pager_spinlock = SPINLOCK_UNLOCK;
145 
146 /* Defines the range of the alias area */
147 static tee_mm_entry_t *pager_alias_area;
148 /*
149  * Physical pages are added in a stack like fashion to the alias area,
150  * @pager_alias_next_free gives the address of next free entry if
151  * @pager_alias_next_free is != 0
152  */
153 static uintptr_t pager_alias_next_free;
154 
155 #ifdef CFG_TEE_CORE_DEBUG
156 #define pager_lock(ai) pager_lock_dldetect(__func__, __LINE__, ai)
157 
158 static uint32_t pager_lock_dldetect(const char *func, const int line,
159 				    struct abort_info *ai)
160 {
161 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_ALL);
162 	unsigned int retries = 0;
163 	unsigned int reminder = 0;
164 
165 	while (!cpu_spin_trylock(&pager_spinlock)) {
166 		retries++;
167 		if (!retries) {
168 			/* wrapped, time to report */
169 			trace_printf(func, line, TRACE_ERROR, true,
170 				     "possible spinlock deadlock reminder %u",
171 				     reminder);
172 			if (reminder < UINT_MAX)
173 				reminder++;
174 			if (ai)
175 				abort_print(ai);
176 		}
177 	}
178 
179 	return exceptions;
180 }
181 #else
182 static uint32_t pager_lock(struct abort_info __unused *ai)
183 {
184 	return cpu_spin_lock_xsave(&pager_spinlock);
185 }
186 #endif
187 
188 static uint32_t pager_lock_check_stack(size_t stack_size)
189 {
190 	if (stack_size) {
191 		int8_t buf[stack_size];
192 		size_t n;
193 
194 		/*
195 		 * Make sure to touch all pages of the stack that we expect
196 		 * to use with this lock held. We need to take eventual
197 		 * page faults before the lock is taken or we'll deadlock
198 		 * the pager. The pages that are populated in this way will
199 		 * eventually be released at certain save transitions of
200 		 * the thread.
201 		 */
202 		for (n = 0; n < stack_size; n += SMALL_PAGE_SIZE)
203 			io_write8((vaddr_t)buf + n, 1);
204 		io_write8((vaddr_t)buf + stack_size - 1, 1);
205 	}
206 
207 	return pager_lock(NULL);
208 }
209 
210 static void pager_unlock(uint32_t exceptions)
211 {
212 	cpu_spin_unlock_xrestore(&pager_spinlock, exceptions);
213 }
214 
215 void *tee_pager_phys_to_virt(paddr_t pa)
216 {
217 	struct core_mmu_table_info ti;
218 	unsigned idx;
219 	uint32_t a;
220 	paddr_t p;
221 	vaddr_t v;
222 	size_t n;
223 
224 	/*
225 	 * Most addresses are mapped lineary, try that first if possible.
226 	 */
227 	if (!tee_pager_get_table_info(pa, &ti))
228 		return NULL; /* impossible pa */
229 	idx = core_mmu_va2idx(&ti, pa);
230 	core_mmu_get_entry(&ti, idx, &p, &a);
231 	if ((a & TEE_MATTR_VALID_BLOCK) && p == pa)
232 		return (void *)core_mmu_idx2va(&ti, idx);
233 
234 	n = 0;
235 	idx = core_mmu_va2idx(&pager_tables[n].tbl_info, TEE_RAM_VA_START);
236 	while (true) {
237 		while (idx < TBL_NUM_ENTRIES) {
238 			v = core_mmu_idx2va(&pager_tables[n].tbl_info, idx);
239 			if (v >= (TEE_RAM_VA_START + TEE_RAM_VA_SIZE))
240 				return NULL;
241 
242 			core_mmu_get_entry(&pager_tables[n].tbl_info,
243 					   idx, &p, &a);
244 			if ((a & TEE_MATTR_VALID_BLOCK) && p == pa)
245 				return (void *)v;
246 			idx++;
247 		}
248 
249 		n++;
250 		if (n >= ARRAY_SIZE(pager_tables))
251 			return NULL;
252 		idx = 0;
253 	}
254 
255 	return NULL;
256 }
257 
258 static bool pmem_is_hidden(struct tee_pager_pmem *pmem)
259 {
260 	return pmem->flags & PMEM_FLAG_HIDDEN;
261 }
262 
263 static bool pmem_is_dirty(struct tee_pager_pmem *pmem)
264 {
265 	return pmem->flags & PMEM_FLAG_DIRTY;
266 }
267 
268 static bool pmem_is_covered_by_area(struct tee_pager_pmem *pmem,
269 				    struct tee_pager_area *area)
270 {
271 	if (pmem->fobj != area->fobj)
272 		return false;
273 	if (pmem->fobj_pgidx < area->fobj_pgoffs)
274 		return false;
275 	if ((pmem->fobj_pgidx - area->fobj_pgoffs) >=
276 	    (area->size >> SMALL_PAGE_SHIFT))
277 		return false;
278 
279 	return true;
280 }
281 
282 static size_t pmem_get_area_tblidx(struct tee_pager_pmem *pmem,
283 				   struct tee_pager_area *area)
284 {
285 	size_t tbloffs = (area->base & CORE_MMU_PGDIR_MASK) >> SMALL_PAGE_SHIFT;
286 
287 	return pmem->fobj_pgidx - area->fobj_pgoffs + tbloffs;
288 }
289 
290 static struct pager_table *find_pager_table_may_fail(vaddr_t va)
291 {
292 	size_t n;
293 	const vaddr_t mask = CORE_MMU_PGDIR_MASK;
294 
295 	n = ((va & ~mask) - pager_tables[0].tbl_info.va_base) >>
296 	    CORE_MMU_PGDIR_SHIFT;
297 	if (n >= ARRAY_SIZE(pager_tables))
298 		return NULL;
299 
300 	assert(va >= pager_tables[n].tbl_info.va_base &&
301 	       va <= (pager_tables[n].tbl_info.va_base | mask));
302 
303 	return pager_tables + n;
304 }
305 
306 static struct pager_table *find_pager_table(vaddr_t va)
307 {
308 	struct pager_table *pt = find_pager_table_may_fail(va);
309 
310 	assert(pt);
311 	return pt;
312 }
313 
314 bool tee_pager_get_table_info(vaddr_t va, struct core_mmu_table_info *ti)
315 {
316 	struct pager_table *pt = find_pager_table_may_fail(va);
317 
318 	if (!pt)
319 		return false;
320 
321 	*ti = pt->tbl_info;
322 	return true;
323 }
324 
325 static struct core_mmu_table_info *find_table_info(vaddr_t va)
326 {
327 	return &find_pager_table(va)->tbl_info;
328 }
329 
330 static struct pgt *find_core_pgt(vaddr_t va)
331 {
332 	return &find_pager_table(va)->pgt;
333 }
334 
335 void tee_pager_set_alias_area(tee_mm_entry_t *mm)
336 {
337 	struct pager_table *pt;
338 	unsigned idx;
339 	vaddr_t smem = tee_mm_get_smem(mm);
340 	size_t nbytes = tee_mm_get_bytes(mm);
341 	vaddr_t v;
342 	uint32_t a = 0;
343 
344 	DMSG("0x%" PRIxVA " - 0x%" PRIxVA, smem, smem + nbytes);
345 
346 	assert(!pager_alias_area);
347 	pager_alias_area = mm;
348 	pager_alias_next_free = smem;
349 
350 	/* Clear all mapping in the alias area */
351 	pt = find_pager_table(smem);
352 	idx = core_mmu_va2idx(&pt->tbl_info, smem);
353 	while (pt <= (pager_tables + ARRAY_SIZE(pager_tables) - 1)) {
354 		while (idx < TBL_NUM_ENTRIES) {
355 			v = core_mmu_idx2va(&pt->tbl_info, idx);
356 			if (v >= (smem + nbytes))
357 				goto out;
358 
359 			core_mmu_get_entry(&pt->tbl_info, idx, NULL, &a);
360 			core_mmu_set_entry(&pt->tbl_info, idx, 0, 0);
361 			if (a & TEE_MATTR_VALID_BLOCK)
362 				pgt_dec_used_entries(&pt->pgt);
363 			idx++;
364 		}
365 
366 		pt++;
367 		idx = 0;
368 	}
369 
370 out:
371 	tlbi_mva_range(smem, nbytes, SMALL_PAGE_SIZE);
372 }
373 
374 static size_t tbl_usage_count(struct core_mmu_table_info *ti)
375 {
376 	size_t n;
377 	uint32_t a = 0;
378 	size_t usage = 0;
379 
380 	for (n = 0; n < ti->num_entries; n++) {
381 		core_mmu_get_entry(ti, n, NULL, &a);
382 		if (a & TEE_MATTR_VALID_BLOCK)
383 			usage++;
384 	}
385 	return usage;
386 }
387 
388 static void area_get_entry(struct tee_pager_area *area, size_t idx,
389 			   paddr_t *pa, uint32_t *attr)
390 {
391 	assert(area->pgt);
392 	assert(idx < TBL_NUM_ENTRIES);
393 	core_mmu_get_entry_primitive(area->pgt->tbl, TBL_LEVEL, idx, pa, attr);
394 }
395 
396 static void area_set_entry(struct tee_pager_area *area, size_t idx,
397 			   paddr_t pa, uint32_t attr)
398 {
399 	assert(area->pgt);
400 	assert(idx < TBL_NUM_ENTRIES);
401 	core_mmu_set_entry_primitive(area->pgt->tbl, TBL_LEVEL, idx, pa, attr);
402 }
403 
404 static size_t area_va2idx(struct tee_pager_area *area, vaddr_t va)
405 {
406 	return (va - (area->base & ~CORE_MMU_PGDIR_MASK)) >> SMALL_PAGE_SHIFT;
407 }
408 
409 static vaddr_t area_idx2va(struct tee_pager_area *area, size_t idx)
410 {
411 	return (idx << SMALL_PAGE_SHIFT) + (area->base & ~CORE_MMU_PGDIR_MASK);
412 }
413 
414 static void area_tlbi_entry(struct tee_pager_area *area, size_t idx)
415 {
416 	vaddr_t va = area_idx2va(area, idx);
417 
418 #if defined(CFG_PAGED_USER_TA)
419 	assert(area->pgt);
420 	if (area->pgt->ctx) {
421 		uint32_t asid = to_user_ta_ctx(area->pgt->ctx)->vm_info->asid;
422 
423 		tlbi_mva_asid(va, asid);
424 		return;
425 	}
426 #endif
427 	tlbi_mva_allasid(va);
428 }
429 
430 static void pmem_unmap(struct tee_pager_pmem *pmem, struct pgt *only_this_pgt)
431 {
432 	struct tee_pager_area *area = NULL;
433 	size_t tblidx = 0;
434 	uint32_t a = 0;
435 
436 	TAILQ_FOREACH(area, &pmem->fobj->areas, fobj_link) {
437 		/*
438 		 * If only_this_pgt points to a pgt then the pgt of this
439 		 * area has to match or we'll skip over it.
440 		 */
441 		if (only_this_pgt && area->pgt != only_this_pgt)
442 			continue;
443 		if (!area->pgt || !pmem_is_covered_by_area(pmem, area))
444 			continue;
445 		tblidx = pmem_get_area_tblidx(pmem, area);
446 		area_get_entry(area, tblidx, NULL, &a);
447 		if (a & TEE_MATTR_VALID_BLOCK) {
448 			area_set_entry(area, tblidx, 0, 0);
449 			pgt_dec_used_entries(area->pgt);
450 			area_tlbi_entry(area, tblidx);
451 		}
452 	}
453 }
454 
455 void tee_pager_early_init(void)
456 {
457 	size_t n;
458 
459 	/*
460 	 * Note that this depends on add_pager_vaspace() adding vaspace
461 	 * after end of memory.
462 	 */
463 	for (n = 0; n < ARRAY_SIZE(pager_tables); n++) {
464 		if (!core_mmu_find_table(NULL, TEE_RAM_VA_START +
465 					 n * CORE_MMU_PGDIR_SIZE, UINT_MAX,
466 					 &pager_tables[n].tbl_info))
467 			panic("can't find mmu tables");
468 
469 		if (pager_tables[n].tbl_info.shift != TBL_SHIFT)
470 			panic("Unsupported page size in translation table");
471 		assert(pager_tables[n].tbl_info.num_entries == TBL_NUM_ENTRIES);
472 		assert(pager_tables[n].tbl_info.level == TBL_LEVEL);
473 
474 		pager_tables[n].pgt.tbl = pager_tables[n].tbl_info.table;
475 		pgt_set_used_entries(&pager_tables[n].pgt,
476 				tbl_usage_count(&pager_tables[n].tbl_info));
477 	}
478 }
479 
480 static void *pager_add_alias_page(paddr_t pa)
481 {
482 	unsigned idx;
483 	struct core_mmu_table_info *ti;
484 	/* Alias pages mapped without write permission: runtime will care */
485 	uint32_t attr = TEE_MATTR_VALID_BLOCK |
486 			(TEE_MATTR_CACHE_CACHED << TEE_MATTR_CACHE_SHIFT) |
487 			TEE_MATTR_SECURE | TEE_MATTR_PR;
488 
489 	DMSG("0x%" PRIxPA, pa);
490 
491 	ti = find_table_info(pager_alias_next_free);
492 	idx = core_mmu_va2idx(ti, pager_alias_next_free);
493 	core_mmu_set_entry(ti, idx, pa, attr);
494 	pgt_inc_used_entries(find_core_pgt(pager_alias_next_free));
495 	pager_alias_next_free += SMALL_PAGE_SIZE;
496 	if (pager_alias_next_free >= (tee_mm_get_smem(pager_alias_area) +
497 				      tee_mm_get_bytes(pager_alias_area)))
498 		pager_alias_next_free = 0;
499 	return (void *)core_mmu_idx2va(ti, idx);
500 }
501 
502 static void area_insert_tail(struct tee_pager_area *area)
503 {
504 	uint32_t exceptions = pager_lock_check_stack(8);
505 
506 	TAILQ_INSERT_TAIL(&tee_pager_area_head, area, link);
507 	TAILQ_INSERT_TAIL(&area->fobj->areas, area, fobj_link);
508 
509 	pager_unlock(exceptions);
510 }
511 KEEP_PAGER(area_insert_tail);
512 
513 void tee_pager_add_core_area(vaddr_t base, enum tee_pager_area_type type,
514 			     struct fobj *fobj)
515 {
516 	struct tee_pager_area *area = NULL;
517 	uint32_t flags = 0;
518 	size_t fobj_pgoffs = 0;
519 	vaddr_t b = base;
520 	size_t s = fobj->num_pages * SMALL_PAGE_SIZE;
521 	size_t s2 = 0;
522 
523 	DMSG("0x%" PRIxPTR " - 0x%" PRIxPTR " : type %d", base, base + s, type);
524 
525 	if (base & SMALL_PAGE_MASK || !s) {
526 		EMSG("invalid pager area [%" PRIxVA " +0x%zx]", base, s);
527 		panic();
528 	}
529 
530 	switch (type) {
531 	case PAGER_AREA_TYPE_RO:
532 		flags = TEE_MATTR_PRX;
533 		break;
534 	case PAGER_AREA_TYPE_RW:
535 		flags = TEE_MATTR_PRW;
536 		break;
537 	case PAGER_AREA_TYPE_LOCK:
538 		flags = TEE_MATTR_PRW | TEE_MATTR_LOCKED;
539 		break;
540 	default:
541 		panic();
542 	}
543 
544 	if (!fobj)
545 		panic();
546 
547 	while (s) {
548 		s2 = MIN(CORE_MMU_PGDIR_SIZE - (b & CORE_MMU_PGDIR_MASK), s);
549 		area = calloc(1, sizeof(*area));
550 		if (!area)
551 			panic("alloc_area");
552 
553 		area->fobj = fobj_get(fobj);
554 		area->fobj_pgoffs = fobj_pgoffs;
555 		area->type = type;
556 		area->pgt = find_core_pgt(b);
557 		area->base = b;
558 		area->size = s2;
559 		area->flags = flags;
560 		area_insert_tail(area);
561 
562 		b += s2;
563 		s -= s2;
564 		fobj_pgoffs += s2 / SMALL_PAGE_SIZE;
565 	}
566 }
567 
568 static struct tee_pager_area *find_area(struct tee_pager_area_head *areas,
569 					vaddr_t va)
570 {
571 	struct tee_pager_area *area;
572 
573 	if (!areas)
574 		return NULL;
575 
576 	TAILQ_FOREACH(area, areas, link) {
577 		if (core_is_buffer_inside(va, 1, area->base, area->size))
578 			return area;
579 	}
580 	return NULL;
581 }
582 
583 #ifdef CFG_PAGED_USER_TA
584 static struct tee_pager_area *find_uta_area(vaddr_t va)
585 {
586 	struct tee_ta_ctx *ctx = thread_get_tsd()->ctx;
587 
588 	if (!is_user_ta_ctx(ctx))
589 		return NULL;
590 	return find_area(to_user_ta_ctx(ctx)->areas, va);
591 }
592 #else
593 static struct tee_pager_area *find_uta_area(vaddr_t va __unused)
594 {
595 	return NULL;
596 }
597 #endif /*CFG_PAGED_USER_TA*/
598 
599 
600 static uint32_t get_area_mattr(uint32_t area_flags)
601 {
602 	uint32_t attr = TEE_MATTR_VALID_BLOCK | TEE_MATTR_SECURE |
603 			TEE_MATTR_CACHE_CACHED << TEE_MATTR_CACHE_SHIFT |
604 			(area_flags & (TEE_MATTR_PRWX | TEE_MATTR_URWX));
605 
606 	return attr;
607 }
608 
609 static paddr_t get_pmem_pa(struct tee_pager_pmem *pmem)
610 {
611 	struct core_mmu_table_info *ti;
612 	paddr_t pa;
613 	unsigned idx;
614 
615 	ti = find_table_info((vaddr_t)pmem->va_alias);
616 	idx = core_mmu_va2idx(ti, (vaddr_t)pmem->va_alias);
617 	core_mmu_get_entry(ti, idx, &pa, NULL);
618 	return pa;
619 }
620 
621 static void tee_pager_load_page(struct tee_pager_area *area, vaddr_t page_va,
622 			void *va_alias)
623 {
624 	size_t fobj_pgoffs = ((page_va - area->base) >> SMALL_PAGE_SHIFT) +
625 			     area->fobj_pgoffs;
626 	struct core_mmu_table_info *ti;
627 	uint32_t attr_alias;
628 	paddr_t pa_alias;
629 	unsigned int idx_alias;
630 
631 	/* Insure we are allowed to write to aliased virtual page */
632 	ti = find_table_info((vaddr_t)va_alias);
633 	idx_alias = core_mmu_va2idx(ti, (vaddr_t)va_alias);
634 	core_mmu_get_entry(ti, idx_alias, &pa_alias, &attr_alias);
635 	if (!(attr_alias & TEE_MATTR_PW)) {
636 		attr_alias |= TEE_MATTR_PW;
637 		core_mmu_set_entry(ti, idx_alias, pa_alias, attr_alias);
638 		tlbi_mva_allasid((vaddr_t)va_alias);
639 	}
640 
641 	asan_tag_access(va_alias, (uint8_t *)va_alias + SMALL_PAGE_SIZE);
642 	if (fobj_load_page(area->fobj, fobj_pgoffs, va_alias)) {
643 		EMSG("PH 0x%" PRIxVA " failed", page_va);
644 		panic();
645 	}
646 	switch (area->type) {
647 	case PAGER_AREA_TYPE_RO:
648 		incr_ro_hits();
649 		/* Forbid write to aliases for read-only (maybe exec) pages */
650 		attr_alias &= ~TEE_MATTR_PW;
651 		core_mmu_set_entry(ti, idx_alias, pa_alias, attr_alias);
652 		tlbi_mva_allasid((vaddr_t)va_alias);
653 		break;
654 	case PAGER_AREA_TYPE_RW:
655 		incr_rw_hits();
656 		break;
657 	case PAGER_AREA_TYPE_LOCK:
658 		break;
659 	default:
660 		panic();
661 	}
662 	asan_tag_no_access(va_alias, (uint8_t *)va_alias + SMALL_PAGE_SIZE);
663 }
664 
665 static void tee_pager_save_page(struct tee_pager_pmem *pmem)
666 {
667 	if (pmem_is_dirty(pmem)) {
668 		asan_tag_access(pmem->va_alias,
669 				(uint8_t *)pmem->va_alias + SMALL_PAGE_SIZE);
670 		if (fobj_save_page(pmem->fobj, pmem->fobj_pgidx,
671 				   pmem->va_alias))
672 			panic("fobj_save_page");
673 		asan_tag_no_access(pmem->va_alias,
674 				   (uint8_t *)pmem->va_alias + SMALL_PAGE_SIZE);
675 	}
676 }
677 
678 #ifdef CFG_PAGED_USER_TA
679 static void unlink_area(struct tee_pager_area_head *area_head,
680 			struct tee_pager_area *area)
681 {
682 	uint32_t exceptions = pager_lock_check_stack(64);
683 
684 	TAILQ_REMOVE(area_head, area, link);
685 	TAILQ_REMOVE(&area->fobj->areas, area, fobj_link);
686 
687 	pager_unlock(exceptions);
688 }
689 KEEP_PAGER(unlink_area);
690 
691 static void free_area(struct tee_pager_area *area)
692 {
693 	fobj_put(area->fobj);
694 	free(area);
695 }
696 
697 static TEE_Result pager_add_uta_area(struct user_ta_ctx *utc, vaddr_t base,
698 				     struct fobj *fobj, uint32_t prot)
699 {
700 	struct tee_pager_area *area;
701 	vaddr_t b = base;
702 	size_t fobj_pgoffs = 0;
703 	size_t s = fobj->num_pages * SMALL_PAGE_SIZE;
704 
705 	if (!utc->areas) {
706 		utc->areas = malloc(sizeof(*utc->areas));
707 		if (!utc->areas)
708 			return TEE_ERROR_OUT_OF_MEMORY;
709 		TAILQ_INIT(utc->areas);
710 	}
711 
712 	while (s) {
713 		size_t s2;
714 
715 		if (find_area(utc->areas, b))
716 			return TEE_ERROR_BAD_PARAMETERS;
717 
718 		s2 = MIN(CORE_MMU_PGDIR_SIZE - (b & CORE_MMU_PGDIR_MASK), s);
719 		area = calloc(1, sizeof(*area));
720 		if (!area)
721 			return TEE_ERROR_OUT_OF_MEMORY;
722 
723 		/* Table info will be set when the context is activated. */
724 		area->fobj = fobj_get(fobj);
725 		area->fobj_pgoffs = fobj_pgoffs;
726 		area->type = PAGER_AREA_TYPE_RW;
727 		area->base = b;
728 		area->size = s2;
729 		area->flags = prot;
730 
731 		TAILQ_INSERT_TAIL(utc->areas, area, link);
732 		TAILQ_INSERT_TAIL(&fobj->areas, area, fobj_link);
733 		b += s2;
734 		s -= s2;
735 		fobj_pgoffs += s2 / SMALL_PAGE_SIZE;
736 	}
737 
738 	return TEE_SUCCESS;
739 }
740 
741 TEE_Result tee_pager_add_uta_area(struct user_ta_ctx *utc, vaddr_t base,
742 			    struct fobj *fobj, uint32_t prot)
743 {
744 	TEE_Result res = TEE_SUCCESS;
745 	struct thread_specific_data *tsd = thread_get_tsd();
746 	struct tee_pager_area *area = NULL;
747 	struct core_mmu_table_info dir_info = { NULL };
748 
749 	if (&utc->ctx != tsd->ctx) {
750 		/*
751 		 * Changes are to an utc that isn't active. Just add the
752 		 * areas page tables will be dealt with later.
753 		 */
754 		return pager_add_uta_area(utc, base, fobj, prot);
755 	}
756 
757 	/*
758 	 * Assign page tables before adding areas to be able to tell which
759 	 * are newly added and should be removed in case of failure.
760 	 */
761 	tee_pager_assign_uta_tables(utc);
762 	res = pager_add_uta_area(utc, base, fobj, prot);
763 	if (res) {
764 		struct tee_pager_area *next_a;
765 
766 		/* Remove all added areas */
767 		TAILQ_FOREACH_SAFE(area, utc->areas, link, next_a) {
768 			if (!area->pgt) {
769 				unlink_area(utc->areas, area);
770 				free_area(area);
771 			}
772 		}
773 		return res;
774 	}
775 
776 	/*
777 	 * Assign page tables to the new areas and make sure that the page
778 	 * tables are registered in the upper table.
779 	 */
780 	tee_pager_assign_uta_tables(utc);
781 	core_mmu_get_user_pgdir(&dir_info);
782 	TAILQ_FOREACH(area, utc->areas, link) {
783 		paddr_t pa;
784 		size_t idx;
785 		uint32_t attr;
786 
787 		idx = core_mmu_va2idx(&dir_info, area->pgt->vabase);
788 		core_mmu_get_entry(&dir_info, idx, &pa, &attr);
789 
790 		/*
791 		 * Check if the page table already is used, if it is, it's
792 		 * already registered.
793 		 */
794 		if (area->pgt->num_used_entries) {
795 			assert(attr & TEE_MATTR_TABLE);
796 			assert(pa == virt_to_phys(area->pgt->tbl));
797 			continue;
798 		}
799 
800 		attr = TEE_MATTR_SECURE | TEE_MATTR_TABLE;
801 		pa = virt_to_phys(area->pgt->tbl);
802 		assert(pa);
803 		/*
804 		 * Note that the update of the table entry is guaranteed to
805 		 * be atomic.
806 		 */
807 		core_mmu_set_entry(&dir_info, idx, pa, attr);
808 	}
809 
810 	return TEE_SUCCESS;
811 }
812 
813 static void rem_area(struct tee_pager_area_head *area_head,
814 		     struct tee_pager_area *area)
815 {
816 	struct tee_pager_pmem *pmem;
817 	size_t last_pgoffs = area->fobj_pgoffs +
818 			     (area->size >> SMALL_PAGE_SHIFT) - 1;
819 	uint32_t exceptions;
820 	size_t idx = 0;
821 	uint32_t a = 0;
822 
823 	exceptions = pager_lock_check_stack(64);
824 
825 	TAILQ_REMOVE(area_head, area, link);
826 	TAILQ_REMOVE(&area->fobj->areas, area, fobj_link);
827 
828 	TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link) {
829 		if (pmem->fobj != area->fobj ||
830 		    pmem->fobj_pgidx < area->fobj_pgoffs ||
831 		    pmem->fobj_pgidx > last_pgoffs)
832 			continue;
833 
834 		idx = pmem_get_area_tblidx(pmem, area);
835 		area_get_entry(area, idx, NULL, &a);
836 		if (!(a & TEE_MATTR_VALID_BLOCK))
837 			continue;
838 
839 		area_set_entry(area, idx, 0, 0);
840 		area_tlbi_entry(area, idx);
841 		pgt_dec_used_entries(area->pgt);
842 	}
843 
844 	pager_unlock(exceptions);
845 
846 	free_area(area);
847 }
848 KEEP_PAGER(rem_area);
849 
850 void tee_pager_rem_uta_region(struct user_ta_ctx *utc, vaddr_t base,
851 			      size_t size)
852 {
853 	struct tee_pager_area *area;
854 	struct tee_pager_area *next_a;
855 	size_t s = ROUNDUP(size, SMALL_PAGE_SIZE);
856 
857 	TAILQ_FOREACH_SAFE(area, utc->areas, link, next_a) {
858 		if (core_is_buffer_inside(area->base, area->size, base, s))
859 			rem_area(utc->areas, area);
860 	}
861 	tlbi_asid(utc->vm_info->asid);
862 }
863 
864 void tee_pager_rem_uta_areas(struct user_ta_ctx *utc)
865 {
866 	struct tee_pager_area *area;
867 
868 	if (!utc->areas)
869 		return;
870 
871 	while (true) {
872 		area = TAILQ_FIRST(utc->areas);
873 		if (!area)
874 			break;
875 		unlink_area(utc->areas, area);
876 		free_area(area);
877 	}
878 
879 	free(utc->areas);
880 }
881 
882 static bool __maybe_unused same_context(struct tee_pager_pmem *pmem)
883 {
884 	struct tee_pager_area *a = TAILQ_FIRST(&pmem->fobj->areas);
885 	void *ctx = a->pgt->ctx;
886 
887 	do {
888 		a = TAILQ_NEXT(a, fobj_link);
889 		if (!a)
890 			return true;
891 	} while (a->pgt->ctx == ctx);
892 
893 	return false;
894 }
895 
896 bool tee_pager_set_uta_area_attr(struct user_ta_ctx *utc, vaddr_t base,
897 				 size_t size, uint32_t flags)
898 {
899 	bool ret = false;
900 	vaddr_t b = base;
901 	size_t s = size;
902 	size_t s2 = 0;
903 	struct tee_pager_area *area = find_area(utc->areas, b);
904 	uint32_t exceptions = 0;
905 	struct tee_pager_pmem *pmem = NULL;
906 	uint32_t a = 0;
907 	uint32_t f = 0;
908 	uint32_t mattr = 0;
909 	uint32_t f2 = 0;
910 	size_t tblidx = 0;
911 
912 	f = (flags & TEE_MATTR_URWX) | TEE_MATTR_UR | TEE_MATTR_PR;
913 	if (f & TEE_MATTR_UW)
914 		f |= TEE_MATTR_PW;
915 	mattr = get_area_mattr(f);
916 
917 	exceptions = pager_lock_check_stack(SMALL_PAGE_SIZE);
918 
919 	while (s) {
920 		s2 = MIN(CORE_MMU_PGDIR_SIZE - (b & CORE_MMU_PGDIR_MASK), s);
921 		if (!area || area->base != b || area->size != s2) {
922 			ret = false;
923 			goto out;
924 		}
925 		b += s2;
926 		s -= s2;
927 
928 		if (area->flags == f)
929 			goto next_area;
930 
931 		TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link) {
932 			if (!pmem_is_covered_by_area(pmem, area))
933 				continue;
934 
935 			tblidx = pmem_get_area_tblidx(pmem, area);
936 			area_get_entry(area, tblidx, NULL, &a);
937 			if (a == f)
938 				continue;
939 			area_set_entry(area, tblidx, 0, 0);
940 			area_tlbi_entry(area, tblidx);
941 
942 			pmem->flags &= ~PMEM_FLAG_HIDDEN;
943 			if (pmem_is_dirty(pmem))
944 				f2 = mattr;
945 			else
946 				f2 = mattr & ~(TEE_MATTR_UW | TEE_MATTR_PW);
947 			area_set_entry(area, tblidx, get_pmem_pa(pmem), f2);
948 			if (!(a & TEE_MATTR_VALID_BLOCK))
949 				pgt_inc_used_entries(area->pgt);
950 			/*
951 			 * Make sure the table update is visible before
952 			 * continuing.
953 			 */
954 			dsb_ishst();
955 
956 			/*
957 			 * Here's a problem if this page already is shared.
958 			 * We need do icache invalidate for each context
959 			 * in which it is shared. In practice this will
960 			 * never happen.
961 			 */
962 			if (flags & TEE_MATTR_UX) {
963 				void *va = (void *)area_idx2va(area, tblidx);
964 
965 				/* Assert that the pmem isn't shared. */
966 				assert(same_context(pmem));
967 
968 				dcache_clean_range_pou(va, SMALL_PAGE_SIZE);
969 				icache_inv_user_range(va, SMALL_PAGE_SIZE);
970 			}
971 		}
972 
973 		area->flags = f;
974 next_area:
975 		area = TAILQ_NEXT(area, link);
976 	}
977 
978 	ret = true;
979 out:
980 	pager_unlock(exceptions);
981 	return ret;
982 }
983 KEEP_PAGER(tee_pager_set_uta_area_attr);
984 #endif /*CFG_PAGED_USER_TA*/
985 
986 void tee_pager_invalidate_fobj(struct fobj *fobj)
987 {
988 	struct tee_pager_pmem *pmem;
989 	uint32_t exceptions;
990 
991 	exceptions = pager_lock_check_stack(64);
992 
993 	TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link) {
994 		if (pmem->fobj == fobj) {
995 			pmem->fobj = NULL;
996 			pmem->fobj_pgidx = INVALID_PGIDX;
997 		}
998 	}
999 
1000 	pager_unlock(exceptions);
1001 }
1002 KEEP_PAGER(tee_pager_invalidate_fobj);
1003 
1004 static struct tee_pager_pmem *pmem_find(struct tee_pager_area *area,
1005 					unsigned int tblidx)
1006 {
1007 	struct tee_pager_pmem *pmem = NULL;
1008 
1009 	TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link)
1010 		if (pmem->fobj == area->fobj &&
1011 		    pmem_get_area_tblidx(pmem, area) == tblidx)
1012 			return pmem;
1013 
1014 	return NULL;
1015 }
1016 
1017 static bool tee_pager_unhide_page(struct tee_pager_area *area,
1018 				  unsigned int tblidx)
1019 {
1020 	struct tee_pager_pmem *pmem = pmem_find(area, tblidx);
1021 	uint32_t a = get_area_mattr(area->flags);
1022 	uint32_t attr = 0;
1023 	paddr_t pa = 0;
1024 
1025 	if (!pmem)
1026 		return false;
1027 
1028 	area_get_entry(area, tblidx, NULL, &attr);
1029 	if (attr & TEE_MATTR_VALID_BLOCK)
1030 		return false;
1031 
1032 	/*
1033 	 * The page is hidden, or not not mapped yet. Unhide the page and
1034 	 * move it to the tail.
1035 	 *
1036 	 * Since the page isn't mapped there doesn't exist a valid TLB entry
1037 	 * for this address, so no TLB invalidation is required after setting
1038 	 * the new entry. A DSB is needed though, to make the write visible.
1039 	 *
1040 	 * For user executable pages it's more complicated. Those pages can
1041 	 * be shared between multiple TA mappings and thus populated by
1042 	 * another TA. The reference manual states that:
1043 	 *
1044 	 * "instruction cache maintenance is required only after writing
1045 	 * new data to a physical address that holds an instruction."
1046 	 *
1047 	 * So for hidden pages we would not need to invalidate i-cache, but
1048 	 * for newly populated pages we do. Since we don't know which we
1049 	 * have to assume the worst and always invalidate the i-cache. We
1050 	 * don't need to clean the d-cache though, since that has already
1051 	 * been done earlier.
1052 	 *
1053 	 * Additional bookkeeping to tell if the i-cache invalidation is
1054 	 * needed or not is left as a future optimization.
1055 	 */
1056 
1057 	/* If it's not a dirty block, then it should be read only. */
1058 	if (!pmem_is_dirty(pmem))
1059 		a &= ~(TEE_MATTR_PW | TEE_MATTR_UW);
1060 
1061 	pa = get_pmem_pa(pmem);
1062 	pmem->flags &= ~PMEM_FLAG_HIDDEN;
1063 	if (area->flags & TEE_MATTR_UX) {
1064 		void *va = (void *)area_idx2va(area, tblidx);
1065 
1066 		/* Set a temporary read-only mapping */
1067 		assert(!(a & (TEE_MATTR_UW | TEE_MATTR_PW)));
1068 		area_set_entry(area, tblidx, pa, a & ~TEE_MATTR_UX);
1069 		dsb_ishst();
1070 
1071 		icache_inv_user_range(va, SMALL_PAGE_SIZE);
1072 
1073 		/* Set the final mapping */
1074 		area_set_entry(area, tblidx, pa, a);
1075 		area_tlbi_entry(area, tblidx);
1076 	} else {
1077 		area_set_entry(area, tblidx, pa, a);
1078 		dsb_ishst();
1079 	}
1080 	pgt_inc_used_entries(area->pgt);
1081 
1082 	TAILQ_REMOVE(&tee_pager_pmem_head, pmem, link);
1083 	TAILQ_INSERT_TAIL(&tee_pager_pmem_head, pmem, link);
1084 	incr_hidden_hits();
1085 	return true;
1086 }
1087 
1088 static void tee_pager_hide_pages(void)
1089 {
1090 	struct tee_pager_pmem *pmem = NULL;
1091 	size_t n = 0;
1092 
1093 	TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link) {
1094 		if (n >= TEE_PAGER_NHIDE)
1095 			break;
1096 		n++;
1097 
1098 		/* we cannot hide pages when pmem->fobj is not defined. */
1099 		if (!pmem->fobj)
1100 			continue;
1101 
1102 		if (pmem_is_hidden(pmem))
1103 			continue;
1104 
1105 		pmem->flags |= PMEM_FLAG_HIDDEN;
1106 		pmem_unmap(pmem, NULL);
1107 	}
1108 }
1109 
1110 /*
1111  * Find mapped pmem, hide and move to pageble pmem.
1112  * Return false if page was not mapped, and true if page was mapped.
1113  */
1114 static bool tee_pager_release_one_phys(struct tee_pager_area *area,
1115 				       vaddr_t page_va)
1116 {
1117 	struct tee_pager_pmem *pmem;
1118 	size_t tblidx = 0;
1119 	size_t pgidx = area_va2idx(area, page_va) + area->fobj_pgoffs -
1120 		       ((area->base & CORE_MMU_PGDIR_MASK) >> SMALL_PAGE_SHIFT);
1121 
1122 	TAILQ_FOREACH(pmem, &tee_pager_lock_pmem_head, link) {
1123 		if (pmem->fobj != area->fobj || pmem->fobj_pgidx != pgidx)
1124 			continue;
1125 
1126 		/*
1127 		 * Locked pages may not be shared, these two asserts checks
1128 		 * that there's only a signed area recorded with this pmem.
1129 		 */
1130 		assert(TAILQ_FIRST(&pmem->fobj->areas) == area);
1131 		assert(TAILQ_LAST(&pmem->fobj->areas,
1132 				  tee_pager_area_head) == area);
1133 
1134 		tblidx = pmem_get_area_tblidx(pmem, area);
1135 		area_set_entry(area, tblidx, 0, 0);
1136 		pgt_dec_used_entries(area->pgt);
1137 		TAILQ_REMOVE(&tee_pager_lock_pmem_head, pmem, link);
1138 		pmem->fobj = NULL;
1139 		pmem->fobj_pgidx = INVALID_PGIDX;
1140 		tee_pager_npages++;
1141 		set_npages();
1142 		TAILQ_INSERT_HEAD(&tee_pager_pmem_head, pmem, link);
1143 		incr_zi_released();
1144 		return true;
1145 	}
1146 
1147 	return false;
1148 }
1149 
1150 /* Finds the oldest page and unmaps it from all tables */
1151 static struct tee_pager_pmem *tee_pager_get_page(enum tee_pager_area_type at)
1152 {
1153 	struct tee_pager_pmem *pmem;
1154 
1155 	pmem = TAILQ_FIRST(&tee_pager_pmem_head);
1156 	if (!pmem) {
1157 		EMSG("No pmem entries");
1158 		return NULL;
1159 	}
1160 
1161 	if (pmem->fobj) {
1162 		pmem_unmap(pmem, NULL);
1163 		tee_pager_save_page(pmem);
1164 	}
1165 
1166 	TAILQ_REMOVE(&tee_pager_pmem_head, pmem, link);
1167 	pmem->fobj = NULL;
1168 	pmem->fobj_pgidx = INVALID_PGIDX;
1169 	pmem->flags = 0;
1170 	if (at == PAGER_AREA_TYPE_LOCK) {
1171 		/* Move page to lock list */
1172 		if (tee_pager_npages <= 0)
1173 			panic("running out of page");
1174 		tee_pager_npages--;
1175 		set_npages();
1176 		TAILQ_INSERT_TAIL(&tee_pager_lock_pmem_head, pmem, link);
1177 	} else {
1178 		/* move page to back */
1179 		TAILQ_INSERT_TAIL(&tee_pager_pmem_head, pmem, link);
1180 	}
1181 
1182 	return pmem;
1183 }
1184 
1185 static bool pager_update_permissions(struct tee_pager_area *area,
1186 			struct abort_info *ai, bool *handled)
1187 {
1188 	unsigned int pgidx = area_va2idx(area, ai->va);
1189 	struct tee_pager_pmem *pmem = NULL;
1190 	uint32_t attr = 0;
1191 	paddr_t pa = 0;
1192 
1193 	*handled = false;
1194 
1195 	area_get_entry(area, pgidx, &pa, &attr);
1196 
1197 	/* Not mapped */
1198 	if (!(attr & TEE_MATTR_VALID_BLOCK))
1199 		return false;
1200 
1201 	/* Not readable, should not happen */
1202 	if (abort_is_user_exception(ai)) {
1203 		if (!(attr & TEE_MATTR_UR))
1204 			return true;
1205 	} else {
1206 		if (!(attr & TEE_MATTR_PR)) {
1207 			abort_print_error(ai);
1208 			panic();
1209 		}
1210 	}
1211 
1212 	switch (core_mmu_get_fault_type(ai->fault_descr)) {
1213 	case CORE_MMU_FAULT_TRANSLATION:
1214 	case CORE_MMU_FAULT_READ_PERMISSION:
1215 		if (ai->abort_type == ABORT_TYPE_PREFETCH) {
1216 			/* Check attempting to execute from an NOX page */
1217 			if (abort_is_user_exception(ai)) {
1218 				if (!(attr & TEE_MATTR_UX))
1219 					return true;
1220 			} else {
1221 				if (!(attr & TEE_MATTR_PX)) {
1222 					abort_print_error(ai);
1223 					panic();
1224 				}
1225 			}
1226 		}
1227 		/* Since the page is mapped now it's OK */
1228 		break;
1229 	case CORE_MMU_FAULT_WRITE_PERMISSION:
1230 		/* Check attempting to write to an RO page */
1231 		pmem = pmem_find(area, pgidx);
1232 		if (!pmem)
1233 			panic();
1234 		if (abort_is_user_exception(ai)) {
1235 			if (!(area->flags & TEE_MATTR_UW))
1236 				return true;
1237 			if (!(attr & TEE_MATTR_UW)) {
1238 				FMSG("Dirty %p",
1239 				     (void *)(ai->va & ~SMALL_PAGE_MASK));
1240 				pmem->flags |= PMEM_FLAG_DIRTY;
1241 				area_set_entry(area, pgidx, pa,
1242 					       get_area_mattr(area->flags));
1243 				area_tlbi_entry(area, pgidx);
1244 			}
1245 
1246 		} else {
1247 			if (!(area->flags & TEE_MATTR_PW)) {
1248 				abort_print_error(ai);
1249 				panic();
1250 			}
1251 			if (!(attr & TEE_MATTR_PW)) {
1252 				FMSG("Dirty %p",
1253 				     (void *)(ai->va & ~SMALL_PAGE_MASK));
1254 				pmem->flags |= PMEM_FLAG_DIRTY;
1255 				area_set_entry(area, pgidx, pa,
1256 					       get_area_mattr(area->flags));
1257 				tlbi_mva_allasid(ai->va & ~SMALL_PAGE_MASK);
1258 			}
1259 		}
1260 		/* Since permissions has been updated now it's OK */
1261 		break;
1262 	default:
1263 		/* Some fault we can't deal with */
1264 		if (abort_is_user_exception(ai))
1265 			return true;
1266 		abort_print_error(ai);
1267 		panic();
1268 	}
1269 	*handled = true;
1270 	return true;
1271 }
1272 
1273 #ifdef CFG_TEE_CORE_DEBUG
1274 static void stat_handle_fault(void)
1275 {
1276 	static size_t num_faults;
1277 	static size_t min_npages = SIZE_MAX;
1278 	static size_t total_min_npages = SIZE_MAX;
1279 
1280 	num_faults++;
1281 	if ((num_faults % 1024) == 0 || tee_pager_npages < total_min_npages) {
1282 		DMSG("nfaults %zu npages %zu (min %zu)",
1283 		     num_faults, tee_pager_npages, min_npages);
1284 		min_npages = tee_pager_npages; /* reset */
1285 	}
1286 	if (tee_pager_npages < min_npages)
1287 		min_npages = tee_pager_npages;
1288 	if (tee_pager_npages < total_min_npages)
1289 		total_min_npages = tee_pager_npages;
1290 }
1291 #else
1292 static void stat_handle_fault(void)
1293 {
1294 }
1295 #endif
1296 
1297 bool tee_pager_handle_fault(struct abort_info *ai)
1298 {
1299 	struct tee_pager_area *area;
1300 	vaddr_t page_va = ai->va & ~SMALL_PAGE_MASK;
1301 	uint32_t exceptions;
1302 	bool ret;
1303 	bool clean_user_cache = false;
1304 
1305 #ifdef TEE_PAGER_DEBUG_PRINT
1306 	if (!abort_is_user_exception(ai))
1307 		abort_print(ai);
1308 #endif
1309 
1310 	/*
1311 	 * We're updating pages that can affect several active CPUs at a
1312 	 * time below. We end up here because a thread tries to access some
1313 	 * memory that isn't available. We have to be careful when making
1314 	 * that memory available as other threads may succeed in accessing
1315 	 * that address the moment after we've made it available.
1316 	 *
1317 	 * That means that we can't just map the memory and populate the
1318 	 * page, instead we use the aliased mapping to populate the page
1319 	 * and once everything is ready we map it.
1320 	 */
1321 	exceptions = pager_lock(ai);
1322 
1323 	stat_handle_fault();
1324 
1325 	/* check if the access is valid */
1326 	if (abort_is_user_exception(ai)) {
1327 		area = find_uta_area(ai->va);
1328 		clean_user_cache = true;
1329 	} else {
1330 		area = find_area(&tee_pager_area_head, ai->va);
1331 		if (!area) {
1332 			area = find_uta_area(ai->va);
1333 			clean_user_cache = true;
1334 		}
1335 	}
1336 	if (!area || !area->pgt) {
1337 		ret = false;
1338 		goto out;
1339 	}
1340 
1341 	if (!tee_pager_unhide_page(area, area_va2idx(area, page_va))) {
1342 		struct tee_pager_pmem *pmem = NULL;
1343 		uint32_t attr = 0;
1344 		paddr_t pa = 0;
1345 		size_t tblidx = 0;
1346 
1347 		/*
1348 		 * The page wasn't hidden, but some other core may have
1349 		 * updated the table entry before we got here or we need
1350 		 * to make a read-only page read-write (dirty).
1351 		 */
1352 		if (pager_update_permissions(area, ai, &ret)) {
1353 			/*
1354 			 * Nothing more to do with the abort. The problem
1355 			 * could already have been dealt with from another
1356 			 * core or if ret is false the TA will be paniced.
1357 			 */
1358 			goto out;
1359 		}
1360 
1361 		pmem = tee_pager_get_page(area->type);
1362 		if (!pmem) {
1363 			abort_print(ai);
1364 			panic();
1365 		}
1366 
1367 		/* load page code & data */
1368 		tee_pager_load_page(area, page_va, pmem->va_alias);
1369 
1370 
1371 		pmem->fobj = area->fobj;
1372 		pmem->fobj_pgidx = area_va2idx(area, page_va) +
1373 				   area->fobj_pgoffs -
1374 				   ((area->base & CORE_MMU_PGDIR_MASK) >>
1375 					SMALL_PAGE_SHIFT);
1376 		tblidx = pmem_get_area_tblidx(pmem, area);
1377 		attr = get_area_mattr(area->flags);
1378 		/*
1379 		 * Pages from PAGER_AREA_TYPE_RW starts read-only to be
1380 		 * able to tell when they are updated and should be tagged
1381 		 * as dirty.
1382 		 */
1383 		if (area->type == PAGER_AREA_TYPE_RW)
1384 			attr &= ~(TEE_MATTR_PW | TEE_MATTR_UW);
1385 		pa = get_pmem_pa(pmem);
1386 
1387 		/*
1388 		 * We've updated the page using the aliased mapping and
1389 		 * some cache maintenence is now needed if it's an
1390 		 * executable page.
1391 		 *
1392 		 * Since the d-cache is a Physically-indexed,
1393 		 * physically-tagged (PIPT) cache we can clean either the
1394 		 * aliased address or the real virtual address. In this
1395 		 * case we choose the real virtual address.
1396 		 *
1397 		 * The i-cache can also be PIPT, but may be something else
1398 		 * too like VIPT. The current code requires the caches to
1399 		 * implement the IVIPT extension, that is:
1400 		 * "instruction cache maintenance is required only after
1401 		 * writing new data to a physical address that holds an
1402 		 * instruction."
1403 		 *
1404 		 * To portably invalidate the icache the page has to
1405 		 * be mapped at the final virtual address but not
1406 		 * executable.
1407 		 */
1408 		if (area->flags & (TEE_MATTR_PX | TEE_MATTR_UX)) {
1409 			uint32_t mask = TEE_MATTR_PX | TEE_MATTR_UX |
1410 					TEE_MATTR_PW | TEE_MATTR_UW;
1411 			void *va = (void *)page_va;
1412 
1413 			/* Set a temporary read-only mapping */
1414 			area_set_entry(area, tblidx, pa, attr & ~mask);
1415 			area_tlbi_entry(area, tblidx);
1416 
1417 			dcache_clean_range_pou(va, SMALL_PAGE_SIZE);
1418 			if (clean_user_cache)
1419 				icache_inv_user_range(va, SMALL_PAGE_SIZE);
1420 			else
1421 				icache_inv_range(va, SMALL_PAGE_SIZE);
1422 
1423 			/* Set the final mapping */
1424 			area_set_entry(area, tblidx, pa, attr);
1425 			area_tlbi_entry(area, tblidx);
1426 		} else {
1427 			area_set_entry(area, tblidx, pa, attr);
1428 			/*
1429 			 * No need to flush TLB for this entry, it was
1430 			 * invalid. We should use a barrier though, to make
1431 			 * sure that the change is visible.
1432 			 */
1433 			dsb_ishst();
1434 		}
1435 		pgt_inc_used_entries(area->pgt);
1436 
1437 		FMSG("Mapped 0x%" PRIxVA " -> 0x%" PRIxPA, page_va, pa);
1438 
1439 	}
1440 
1441 	tee_pager_hide_pages();
1442 	ret = true;
1443 out:
1444 	pager_unlock(exceptions);
1445 	return ret;
1446 }
1447 
1448 void tee_pager_add_pages(vaddr_t vaddr, size_t npages, bool unmap)
1449 {
1450 	size_t n;
1451 
1452 	DMSG("0x%" PRIxVA " - 0x%" PRIxVA " : %d",
1453 	     vaddr, vaddr + npages * SMALL_PAGE_SIZE, (int)unmap);
1454 
1455 	/* setup memory */
1456 	for (n = 0; n < npages; n++) {
1457 		struct core_mmu_table_info *ti;
1458 		struct tee_pager_pmem *pmem;
1459 		vaddr_t va = vaddr + n * SMALL_PAGE_SIZE;
1460 		unsigned int pgidx;
1461 		paddr_t pa;
1462 		uint32_t attr;
1463 
1464 		ti = find_table_info(va);
1465 		pgidx = core_mmu_va2idx(ti, va);
1466 		/*
1467 		 * Note that we can only support adding pages in the
1468 		 * valid range of this table info, currently not a problem.
1469 		 */
1470 		core_mmu_get_entry(ti, pgidx, &pa, &attr);
1471 
1472 		/* Ignore unmapped pages/blocks */
1473 		if (!(attr & TEE_MATTR_VALID_BLOCK))
1474 			continue;
1475 
1476 		pmem = calloc(1, sizeof(struct tee_pager_pmem));
1477 		if (!pmem)
1478 			panic("out of mem");
1479 
1480 		pmem->va_alias = pager_add_alias_page(pa);
1481 
1482 		if (unmap) {
1483 			pmem->fobj = NULL;
1484 			pmem->fobj_pgidx = INVALID_PGIDX;
1485 			core_mmu_set_entry(ti, pgidx, 0, 0);
1486 			pgt_dec_used_entries(find_core_pgt(va));
1487 		} else {
1488 			struct tee_pager_area *area = NULL;
1489 
1490 			/*
1491 			 * The page is still mapped, let's assign the area
1492 			 * and update the protection bits accordingly.
1493 			 */
1494 			area = find_area(&tee_pager_area_head, va);
1495 			assert(area && area->pgt == find_core_pgt(va));
1496 			pmem->fobj = area->fobj;
1497 			pmem->fobj_pgidx = pgidx + area->fobj_pgoffs -
1498 					   ((area->base &
1499 							CORE_MMU_PGDIR_MASK) >>
1500 						SMALL_PAGE_SHIFT);
1501 			assert(pgidx == pmem_get_area_tblidx(pmem, area));
1502 			assert(pa == get_pmem_pa(pmem));
1503 			area_set_entry(area, pgidx, pa,
1504 				       get_area_mattr(area->flags));
1505 		}
1506 
1507 		tee_pager_npages++;
1508 		incr_npages_all();
1509 		set_npages();
1510 		TAILQ_INSERT_TAIL(&tee_pager_pmem_head, pmem, link);
1511 	}
1512 
1513 	/*
1514 	 * As this is done at inits, invalidate all TLBs once instead of
1515 	 * targeting only the modified entries.
1516 	 */
1517 	tlbi_all();
1518 }
1519 
1520 #ifdef CFG_PAGED_USER_TA
1521 static struct pgt *find_pgt(struct pgt *pgt, vaddr_t va)
1522 {
1523 	struct pgt *p = pgt;
1524 
1525 	while (p && (va & ~CORE_MMU_PGDIR_MASK) != p->vabase)
1526 		p = SLIST_NEXT(p, link);
1527 	return p;
1528 }
1529 
1530 void tee_pager_assign_uta_tables(struct user_ta_ctx *utc)
1531 {
1532 	struct tee_pager_area *area = NULL;
1533 	struct pgt *pgt = NULL;
1534 
1535 	if (!utc->areas)
1536 		return;
1537 
1538 	pgt = SLIST_FIRST(&thread_get_tsd()->pgt_cache);
1539 	TAILQ_FOREACH(area, utc->areas, link) {
1540 		if (!area->pgt)
1541 			area->pgt = find_pgt(pgt, area->base);
1542 		else
1543 			assert(area->pgt == find_pgt(pgt, area->base));
1544 		if (!area->pgt)
1545 			panic();
1546 	}
1547 }
1548 
1549 void tee_pager_pgt_save_and_release_entries(struct pgt *pgt)
1550 {
1551 	struct tee_pager_pmem *pmem = NULL;
1552 	struct tee_pager_area *area = NULL;
1553 	struct tee_pager_area_head *areas = NULL;
1554 	uint32_t exceptions = pager_lock_check_stack(SMALL_PAGE_SIZE);
1555 
1556 	if (!pgt->num_used_entries)
1557 		goto out;
1558 
1559 	TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link) {
1560 		if (pmem->fobj)
1561 			pmem_unmap(pmem, pgt);
1562 	}
1563 	assert(!pgt->num_used_entries);
1564 
1565 out:
1566 	areas = to_user_ta_ctx(pgt->ctx)->areas;
1567 	if (areas) {
1568 		TAILQ_FOREACH(area, areas, link) {
1569 			if (area->pgt == pgt)
1570 				area->pgt = NULL;
1571 		}
1572 	}
1573 
1574 	pager_unlock(exceptions);
1575 }
1576 KEEP_PAGER(tee_pager_pgt_save_and_release_entries);
1577 #endif /*CFG_PAGED_USER_TA*/
1578 
1579 void tee_pager_release_phys(void *addr, size_t size)
1580 {
1581 	bool unmaped = false;
1582 	vaddr_t va = (vaddr_t)addr;
1583 	vaddr_t begin = ROUNDUP(va, SMALL_PAGE_SIZE);
1584 	vaddr_t end = ROUNDDOWN(va + size, SMALL_PAGE_SIZE);
1585 	struct tee_pager_area *area;
1586 	uint32_t exceptions;
1587 
1588 	if (end <= begin)
1589 		return;
1590 
1591 	exceptions = pager_lock_check_stack(128);
1592 
1593 	for (va = begin; va < end; va += SMALL_PAGE_SIZE) {
1594 		area = find_area(&tee_pager_area_head, va);
1595 		if (!area)
1596 			panic();
1597 		unmaped |= tee_pager_release_one_phys(area, va);
1598 	}
1599 
1600 	if (unmaped)
1601 		tlbi_mva_range(begin, end - begin, SMALL_PAGE_SIZE);
1602 
1603 	pager_unlock(exceptions);
1604 }
1605 KEEP_PAGER(tee_pager_release_phys);
1606 
1607 void *tee_pager_alloc(size_t size)
1608 {
1609 	tee_mm_entry_t *mm = NULL;
1610 	uint8_t *smem = NULL;
1611 	size_t num_pages = 0;
1612 	struct fobj *fobj = NULL;
1613 
1614 	if (!size)
1615 		return NULL;
1616 
1617 	mm = tee_mm_alloc(&tee_mm_vcore, ROUNDUP(size, SMALL_PAGE_SIZE));
1618 	if (!mm)
1619 		return NULL;
1620 
1621 	smem = (uint8_t *)tee_mm_get_smem(mm);
1622 	num_pages = tee_mm_get_bytes(mm) / SMALL_PAGE_SIZE;
1623 	fobj = fobj_locked_paged_alloc(num_pages);
1624 	if (!fobj) {
1625 		tee_mm_free(mm);
1626 		return NULL;
1627 	}
1628 
1629 	tee_pager_add_core_area((vaddr_t)smem, PAGER_AREA_TYPE_LOCK, fobj);
1630 	fobj_put(fobj);
1631 
1632 	asan_tag_access(smem, smem + num_pages * SMALL_PAGE_SIZE);
1633 
1634 	return smem;
1635 }
1636