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