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