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