xref: /optee_os/core/arch/arm/mm/tee_pager.c (revision a257edb40b64022bb94445649e67ab4176a51603)
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/tee_misc.h>
36 #include <kernel/tee_ta_manager.h>
37 #include <kernel/thread.h>
38 #include <kernel/tz_proc.h>
39 #include <mm/core_memprot.h>
40 #include <mm/tee_mm.h>
41 #include <mm/tee_mmu_defs.h>
42 #include <mm/tee_pager.h>
43 #include <types_ext.h>
44 #include <stdlib.h>
45 #include <tee_api_defines.h>
46 #include <tee/tee_cryp_provider.h>
47 #include <trace.h>
48 #include <utee_defines.h>
49 #include <util.h>
50 
51 #include "pager_private.h"
52 
53 #define PAGER_AE_KEY_BITS	256
54 
55 struct pager_rw_pstate {
56 	uint64_t iv;
57 	uint8_t tag[PAGER_AES_GCM_TAG_LEN];
58 };
59 
60 enum area_type {
61 	AREA_TYPE_RO,
62 	AREA_TYPE_RW,
63 	AREA_TYPE_LOCK,
64 };
65 
66 struct tee_pager_area {
67 	union {
68 		const uint8_t *hashes;
69 		struct pager_rw_pstate *rwp;
70 	} u;
71 	uint8_t *store;
72 	enum area_type type;
73 	uint32_t flags;
74 	vaddr_t base;
75 	size_t size;
76 	struct pgt *pgt;
77 	TAILQ_ENTRY(tee_pager_area) link;
78 };
79 
80 TAILQ_HEAD(tee_pager_area_head, tee_pager_area);
81 
82 static struct tee_pager_area_head tee_pager_area_head =
83 	TAILQ_HEAD_INITIALIZER(tee_pager_area_head);
84 
85 #define INVALID_PGIDX	UINT_MAX
86 
87 /*
88  * struct tee_pager_pmem - Represents a physical page used for paging.
89  *
90  * @pgidx	an index of the entry in area->ti.
91  * @va_alias	Virtual address where the physical page always is aliased.
92  *		Used during remapping of the page when the content need to
93  *		be updated before it's available at the new location.
94  * @area	a pointer to the pager area
95  */
96 struct tee_pager_pmem {
97 	unsigned pgidx;
98 	void *va_alias;
99 	struct tee_pager_area *area;
100 	TAILQ_ENTRY(tee_pager_pmem) link;
101 };
102 
103 /* The list of physical pages. The first page in the list is the oldest */
104 TAILQ_HEAD(tee_pager_pmem_head, tee_pager_pmem);
105 
106 static struct tee_pager_pmem_head tee_pager_pmem_head =
107 	TAILQ_HEAD_INITIALIZER(tee_pager_pmem_head);
108 
109 static struct tee_pager_pmem_head tee_pager_lock_pmem_head =
110 	TAILQ_HEAD_INITIALIZER(tee_pager_lock_pmem_head);
111 
112 static uint8_t pager_ae_key[PAGER_AE_KEY_BITS / 8];
113 
114 /* number of pages hidden */
115 #define TEE_PAGER_NHIDE (tee_pager_npages / 3)
116 
117 /* Number of registered physical pages, used hiding pages. */
118 static size_t tee_pager_npages;
119 
120 #ifdef CFG_WITH_STATS
121 static struct tee_pager_stats pager_stats;
122 
123 static inline void incr_ro_hits(void)
124 {
125 	pager_stats.ro_hits++;
126 }
127 
128 static inline void incr_rw_hits(void)
129 {
130 	pager_stats.rw_hits++;
131 }
132 
133 static inline void incr_hidden_hits(void)
134 {
135 	pager_stats.hidden_hits++;
136 }
137 
138 static inline void incr_zi_released(void)
139 {
140 	pager_stats.zi_released++;
141 }
142 
143 static inline void incr_npages_all(void)
144 {
145 	pager_stats.npages_all++;
146 }
147 
148 static inline void set_npages(void)
149 {
150 	pager_stats.npages = tee_pager_npages;
151 }
152 
153 void tee_pager_get_stats(struct tee_pager_stats *stats)
154 {
155 	*stats = pager_stats;
156 
157 	pager_stats.hidden_hits = 0;
158 	pager_stats.ro_hits = 0;
159 	pager_stats.rw_hits = 0;
160 	pager_stats.zi_released = 0;
161 }
162 
163 #else /* CFG_WITH_STATS */
164 static inline void incr_ro_hits(void) { }
165 static inline void incr_rw_hits(void) { }
166 static inline void incr_hidden_hits(void) { }
167 static inline void incr_zi_released(void) { }
168 static inline void incr_npages_all(void) { }
169 static inline void set_npages(void) { }
170 
171 void tee_pager_get_stats(struct tee_pager_stats *stats)
172 {
173 	memset(stats, 0, sizeof(struct tee_pager_stats));
174 }
175 #endif /* CFG_WITH_STATS */
176 
177 static struct pgt pager_core_pgt;
178 struct core_mmu_table_info tee_pager_tbl_info;
179 static struct core_mmu_table_info pager_alias_tbl_info;
180 
181 static unsigned pager_spinlock = SPINLOCK_UNLOCK;
182 
183 /* Defines the range of the alias area */
184 static tee_mm_entry_t *pager_alias_area;
185 /*
186  * Physical pages are added in a stack like fashion to the alias area,
187  * @pager_alias_next_free gives the address of next free entry if
188  * @pager_alias_next_free is != 0
189  */
190 static uintptr_t pager_alias_next_free;
191 
192 static uint32_t pager_lock(void)
193 {
194 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_ALL);
195 
196 	cpu_spin_lock(&pager_spinlock);
197 	return exceptions;
198 }
199 
200 static void pager_unlock(uint32_t exceptions)
201 {
202 	cpu_spin_unlock(&pager_spinlock);
203 	thread_set_exceptions(exceptions);
204 }
205 
206 static void set_alias_area(tee_mm_entry_t *mm)
207 {
208 	struct core_mmu_table_info *ti = &pager_alias_tbl_info;
209 	size_t tbl_va_size;
210 	unsigned idx;
211 	unsigned last_idx;
212 	vaddr_t smem = tee_mm_get_smem(mm);
213 	size_t nbytes = tee_mm_get_bytes(mm);
214 
215 	DMSG("0x%" PRIxVA " - 0x%" PRIxVA, smem, smem + nbytes);
216 
217 	if (pager_alias_area)
218 		panic("null pager_alias_area");
219 
220 	if (!ti->num_entries && !core_mmu_find_table(smem, UINT_MAX, ti))
221 		panic("Can't find translation table");
222 
223 	if ((1 << ti->shift) != SMALL_PAGE_SIZE)
224 		panic("Unsupported page size in translation table");
225 
226 	tbl_va_size = (1 << ti->shift) * ti->num_entries;
227 	if (!core_is_buffer_inside(smem, nbytes,
228 				   ti->va_base, tbl_va_size)) {
229 		EMSG("area 0x%" PRIxVA " len 0x%zx doesn't fit it translation table 0x%" PRIxVA " len 0x%zx",
230 		     smem, nbytes, ti->va_base, tbl_va_size);
231 		panic();
232 	}
233 
234 	if (smem & SMALL_PAGE_MASK || nbytes & SMALL_PAGE_MASK)
235 		panic("invalid area alignment");
236 
237 	pager_alias_area = mm;
238 	pager_alias_next_free = smem;
239 
240 	/* Clear all mapping in the alias area */
241 	idx = core_mmu_va2idx(ti, smem);
242 	last_idx = core_mmu_va2idx(ti, smem + nbytes);
243 	for (; idx < last_idx; idx++)
244 		core_mmu_set_entry(ti, idx, 0, 0);
245 
246 	/* TODO only invalidate entries touched above */
247 	core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0);
248 }
249 
250 static void generate_ae_key(void)
251 {
252 	if (rng_generate(pager_ae_key, sizeof(pager_ae_key)) != TEE_SUCCESS)
253 		panic("failed to generate random");
254 }
255 
256 void tee_pager_init(tee_mm_entry_t *mm_alias)
257 {
258 	set_alias_area(mm_alias);
259 	generate_ae_key();
260 }
261 
262 static void *pager_add_alias_page(paddr_t pa)
263 {
264 	unsigned idx;
265 	struct core_mmu_table_info *ti = &pager_alias_tbl_info;
266 	uint32_t attr = TEE_MATTR_VALID_BLOCK | TEE_MATTR_GLOBAL |
267 			(TEE_MATTR_CACHE_CACHED << TEE_MATTR_CACHE_SHIFT) |
268 			TEE_MATTR_SECURE | TEE_MATTR_PRW;
269 
270 	DMSG("0x%" PRIxPA, pa);
271 
272 	if (!pager_alias_next_free || !ti->num_entries)
273 		panic("invalid alias entry");
274 
275 	idx = core_mmu_va2idx(ti, pager_alias_next_free);
276 	core_mmu_set_entry(ti, idx, pa, attr);
277 	pgt_inc_used_entries(&pager_core_pgt);
278 	pager_alias_next_free += SMALL_PAGE_SIZE;
279 	if (pager_alias_next_free >= (tee_mm_get_smem(pager_alias_area) +
280 				      tee_mm_get_bytes(pager_alias_area)))
281 		pager_alias_next_free = 0;
282 	return (void *)core_mmu_idx2va(ti, idx);
283 }
284 
285 static struct tee_pager_area *alloc_area(struct pgt *pgt,
286 					 vaddr_t base, size_t size,
287 					 uint32_t flags, const void *store,
288 					 const void *hashes)
289 {
290 	struct tee_pager_area *area = calloc(1, sizeof(*area));
291 	enum area_type at;
292 	tee_mm_entry_t *mm_store = NULL;
293 
294 	if (!area)
295 		return NULL;
296 
297 	if (flags & (TEE_MATTR_PW | TEE_MATTR_UW)) {
298 		if (flags & TEE_MATTR_LOCKED) {
299 			at = AREA_TYPE_LOCK;
300 			goto out;
301 		}
302 		mm_store = tee_mm_alloc(&tee_mm_sec_ddr, size);
303 		if (!mm_store)
304 			goto bad;
305 		area->store = phys_to_virt(tee_mm_get_smem(mm_store),
306 					   MEM_AREA_TA_RAM);
307 		if (!area->store)
308 			goto bad;
309 		area->u.rwp = calloc(size / SMALL_PAGE_SIZE,
310 				     sizeof(struct pager_rw_pstate));
311 		if (!area->u.rwp)
312 			goto bad;
313 		at = AREA_TYPE_RW;
314 	} else {
315 		area->store = (void *)store;
316 		area->u.hashes = hashes;
317 		at = AREA_TYPE_RO;
318 	}
319 out:
320 	area->pgt = pgt;
321 	area->base = base;
322 	area->size = size;
323 	area->flags = flags;
324 	area->type = at;
325 	return area;
326 bad:
327 	tee_mm_free(mm_store);
328 	free(area->u.rwp);
329 	free(area);
330 	return NULL;
331 }
332 
333 static void area_insert_tail(struct tee_pager_area *area)
334 {
335 	uint32_t exceptions = pager_lock();
336 
337 	TAILQ_INSERT_TAIL(&tee_pager_area_head, area, link);
338 
339 	pager_unlock(exceptions);
340 }
341 KEEP_PAGER(area_insert_tail);
342 
343 static size_t tbl_usage_count(struct pgt *pgt)
344 {
345 	size_t n;
346 	paddr_t pa;
347 	size_t usage = 0;
348 
349 	for (n = 0; n < tee_pager_tbl_info.num_entries; n++) {
350 		core_mmu_get_entry_primitive(pgt->tbl, tee_pager_tbl_info.level,
351 					     n, &pa, NULL);
352 		if (pa)
353 			usage++;
354 	}
355 	return usage;
356 }
357 
358 bool tee_pager_add_core_area(vaddr_t base, size_t size, uint32_t flags,
359 			const void *store, const void *hashes)
360 {
361 	struct tee_pager_area *area;
362 	size_t tbl_va_size;
363 	struct core_mmu_table_info *ti = &tee_pager_tbl_info;
364 
365 	DMSG("0x%" PRIxPTR " - 0x%" PRIxPTR " : flags 0x%x, store %p, hashes %p",
366 		base, base + size, flags, store, hashes);
367 
368 	if (base & SMALL_PAGE_MASK || size & SMALL_PAGE_MASK || !size) {
369 		EMSG("invalid pager area [%" PRIxVA " +0x%zx]", base, size);
370 		panic();
371 	}
372 
373 	if (!(flags & TEE_MATTR_PW) && (!store || !hashes))
374 		panic("write pages cannot provide store or hashes");
375 
376 	if ((flags & TEE_MATTR_PW) && (store || hashes))
377 		panic("non-write pages must provide store and hashes");
378 
379 	if (!pager_core_pgt.tbl) {
380 		pager_core_pgt.tbl = ti->table;
381 		pgt_set_used_entries(&pager_core_pgt,
382 				     tbl_usage_count(&pager_core_pgt));
383 	}
384 
385 	tbl_va_size = (1 << ti->shift) * ti->num_entries;
386 	if (!core_is_buffer_inside(base, size, ti->va_base, tbl_va_size)) {
387 		DMSG("area 0x%" PRIxPTR " len 0x%zx doesn't fit it translation table 0x%" PRIxVA " len 0x%zx",
388 			base, size, ti->va_base, tbl_va_size);
389 		return false;
390 	}
391 
392 	area = alloc_area(&pager_core_pgt, base, size, flags, store, hashes);
393 	if (!area)
394 		return false;
395 
396 	area_insert_tail(area);
397 	return true;
398 }
399 
400 #ifdef CFG_PAGED_USER_TA
401 bool tee_pager_add_uta_area(struct user_ta_ctx *utc, vaddr_t base, size_t size)
402 {
403 	struct tee_pager_area *area;
404 	uint32_t flags;
405 	vaddr_t b = base;
406 	size_t s = size;
407 
408 	if (!utc->areas) {
409 		utc->areas = malloc(sizeof(*utc->areas));
410 		if (!utc->areas)
411 			return false;
412 		TAILQ_INIT(utc->areas);
413 	}
414 
415 	flags = TEE_MATTR_PRW | TEE_MATTR_URWX;
416 
417 	while (s) {
418 		size_t s2;
419 
420 		s2 = MIN(CORE_MMU_PGDIR_SIZE - (b & CORE_MMU_PGDIR_MASK), s);
421 
422 		/* Table info will be set when the context is activated. */
423 		area = alloc_area(NULL, b, s2, flags, NULL, NULL);
424 		if (!area)
425 			return false;
426 		TAILQ_INSERT_TAIL(utc->areas, area, link);
427 		b += s2;
428 		s -= s2;
429 	}
430 
431 	return true;
432 }
433 
434 void tee_pager_rem_uta_areas(struct user_ta_ctx *utc)
435 {
436 	struct tee_pager_area *area;
437 
438 	if (!utc->areas)
439 		return;
440 
441 	while (true) {
442 		area = TAILQ_FIRST(utc->areas);
443 		if (!area)
444 			break;
445 		TAILQ_REMOVE(utc->areas, area, link);
446 		tee_mm_free(tee_mm_find(&tee_mm_sec_ddr,
447 					virt_to_phys(area->store)));
448 		if (area->type == AREA_TYPE_RW)
449 			free(area->u.rwp);
450 		free(area);
451 	}
452 
453 	free(utc->areas);
454 }
455 #endif /*CFG_PAGED_USER_TA*/
456 
457 static struct tee_pager_area *find_area(struct tee_pager_area_head *areas,
458 					vaddr_t va)
459 {
460 	struct tee_pager_area *area;
461 
462 	if (!areas)
463 		return NULL;
464 
465 	TAILQ_FOREACH(area, areas, link) {
466 		if (core_is_buffer_inside(va, 1, area->base, area->size))
467 			return area;
468 	}
469 	return NULL;
470 }
471 
472 #ifdef CFG_PAGED_USER_TA
473 static struct tee_pager_area *find_uta_area(vaddr_t va)
474 {
475 	struct tee_ta_ctx *ctx = thread_get_tsd()->ctx;
476 
477 	if (!ctx || !is_user_ta_ctx(ctx))
478 		return NULL;
479 	return find_area(to_user_ta_ctx(ctx)->areas, va);
480 }
481 #else
482 static struct tee_pager_area *find_uta_area(vaddr_t va __unused)
483 {
484 	return NULL;
485 }
486 #endif /*CFG_PAGED_USER_TA*/
487 
488 
489 static uint32_t get_area_mattr(uint32_t area_flags)
490 {
491 	uint32_t attr = TEE_MATTR_VALID_BLOCK | TEE_MATTR_SECURE |
492 			TEE_MATTR_CACHE_CACHED << TEE_MATTR_CACHE_SHIFT |
493 			(area_flags & (TEE_MATTR_PRWX | TEE_MATTR_URWX));
494 
495 	if (!(area_flags & (TEE_MATTR_UR | TEE_MATTR_UX | TEE_MATTR_UW)))
496 		attr |= TEE_MATTR_GLOBAL;
497 
498 	return attr;
499 }
500 
501 static paddr_t get_pmem_pa(struct tee_pager_pmem *pmem)
502 {
503 	paddr_t pa;
504 	unsigned idx;
505 
506 	idx = core_mmu_va2idx(&pager_alias_tbl_info, (vaddr_t)pmem->va_alias);
507 	core_mmu_get_entry(&pager_alias_tbl_info, idx, &pa, NULL);
508 	return pa;
509 }
510 
511 static bool decrypt_page(struct pager_rw_pstate *rwp, const void *src,
512 			void *dst)
513 {
514 	struct pager_aes_gcm_iv iv = {
515 		{ (vaddr_t)rwp, rwp->iv >> 32, rwp->iv }
516 	};
517 
518 	return pager_aes_gcm_decrypt(pager_ae_key, sizeof(pager_ae_key),
519 				     &iv, rwp->tag, src, dst, SMALL_PAGE_SIZE);
520 }
521 
522 static void encrypt_page(struct pager_rw_pstate *rwp, void *src, void *dst)
523 {
524 	struct pager_aes_gcm_iv iv;
525 
526 	assert((rwp->iv + 1) > rwp->iv);
527 	rwp->iv++;
528 	/*
529 	 * IV is constructed as recommended in section "8.2.1 Deterministic
530 	 * Construction" of "Recommendation for Block Cipher Modes of
531 	 * Operation: Galois/Counter Mode (GCM) and GMAC",
532 	 * http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
533 	 */
534 	iv.iv[0] = (vaddr_t)rwp;
535 	iv.iv[1] = rwp->iv >> 32;
536 	iv.iv[2] = rwp->iv;
537 
538 	if (!pager_aes_gcm_encrypt(pager_ae_key, sizeof(pager_ae_key),
539 				   &iv, rwp->tag,
540 				   src, dst, SMALL_PAGE_SIZE))
541 		panic("gcm failed");
542 }
543 
544 static void tee_pager_load_page(struct tee_pager_area *area, vaddr_t page_va,
545 			void *va_alias)
546 {
547 	size_t idx = (page_va - area->base) >> SMALL_PAGE_SHIFT;
548 	const void *stored_page = area->store + idx * SMALL_PAGE_SIZE;
549 
550 	switch (area->type) {
551 	case AREA_TYPE_RO:
552 		{
553 			const void *hash = area->u.hashes +
554 					   idx * TEE_SHA256_HASH_SIZE;
555 
556 			memcpy(va_alias, stored_page, SMALL_PAGE_SIZE);
557 			incr_ro_hits();
558 
559 			if (hash_sha256_check(hash, va_alias,
560 					      SMALL_PAGE_SIZE) != TEE_SUCCESS) {
561 				EMSG("PH 0x%" PRIxVA " failed", page_va);
562 				panic();
563 			}
564 		}
565 		break;
566 	case AREA_TYPE_RW:
567 		FMSG("Restore %p %#" PRIxVA " iv %#" PRIx64,
568 			va_alias, page_va, area->u.rwp[idx].iv);
569 		if (!area->u.rwp[idx].iv)
570 			memset(va_alias, 0, SMALL_PAGE_SIZE);
571 		else if (!decrypt_page(&area->u.rwp[idx], stored_page,
572 				       va_alias)) {
573 			EMSG("PH 0x%" PRIxVA " failed", page_va);
574 			panic();
575 		}
576 		incr_rw_hits();
577 		break;
578 	case AREA_TYPE_LOCK:
579 		FMSG("Zero init %p %#" PRIxVA, va_alias, page_va);
580 		memset(va_alias, 0, SMALL_PAGE_SIZE);
581 		break;
582 	default:
583 		panic();
584 	}
585 }
586 
587 static void tee_pager_save_page(struct tee_pager_pmem *pmem, uint32_t attr)
588 {
589 	const uint32_t dirty_bits = TEE_MATTR_PW | TEE_MATTR_UW |
590 				    TEE_MATTR_HIDDEN_DIRTY_BLOCK;
591 
592 	if (pmem->area->type == AREA_TYPE_RW && (attr & dirty_bits)) {
593 		size_t offs = pmem->area->base & CORE_MMU_PGDIR_MASK;
594 		size_t idx = pmem->pgidx - (offs >> SMALL_PAGE_SHIFT);
595 		void *stored_page = pmem->area->store + idx * SMALL_PAGE_SIZE;
596 
597 		assert(pmem->area->flags & (TEE_MATTR_PW | TEE_MATTR_UW));
598 		encrypt_page(&pmem->area->u.rwp[idx], pmem->va_alias,
599 			     stored_page);
600 		FMSG("Saved %#" PRIxVA " iv %#" PRIx64,
601 			pmem->area->base + idx * SMALL_PAGE_SIZE,
602 			pmem->area->u.rwp[idx].iv);
603 	}
604 }
605 
606 static void area_get_entry(struct tee_pager_area *area, size_t idx,
607 			   paddr_t *pa, uint32_t *attr)
608 {
609 	assert(area->pgt);
610 	assert(idx < tee_pager_tbl_info.num_entries);
611 	core_mmu_get_entry_primitive(area->pgt->tbl, tee_pager_tbl_info.level,
612 				     idx, pa, attr);
613 }
614 
615 static void area_set_entry(struct tee_pager_area *area, size_t idx,
616 			   paddr_t pa, uint32_t attr)
617 {
618 	assert(area->pgt);
619 	assert(idx < tee_pager_tbl_info.num_entries);
620 	core_mmu_set_entry_primitive(area->pgt->tbl, tee_pager_tbl_info.level,
621 				     idx, pa, attr);
622 }
623 
624 static size_t area_va2idx(struct tee_pager_area *area, vaddr_t va)
625 {
626 	return (va - (area->base & ~CORE_MMU_PGDIR_MASK)) >> SMALL_PAGE_SHIFT;
627 }
628 
629 static vaddr_t __maybe_unused area_idx2va(struct tee_pager_area *area,
630 					  size_t idx)
631 {
632 	return (idx << SMALL_PAGE_SHIFT) + (area->base & ~CORE_MMU_PGDIR_MASK);
633 }
634 
635 #ifdef CFG_PAGED_USER_TA
636 bool tee_pager_set_uta_area_attr(struct user_ta_ctx *utc, vaddr_t base,
637 				 size_t size, uint32_t flags)
638 {
639 	bool ret;
640 	vaddr_t b = base;
641 	size_t s = size;
642 	size_t s2;
643 	struct tee_pager_area *area = find_area(utc->areas, b);
644 	uint32_t exceptions;
645 	struct tee_pager_pmem *pmem;
646 	paddr_t pa;
647 	uint32_t a;
648 	uint32_t f;
649 
650 	f = (flags & TEE_MATTR_URWX) | TEE_MATTR_UR | TEE_MATTR_PR;
651 	if (f & TEE_MATTR_UW)
652 		f |= TEE_MATTR_PW;
653 	f = get_area_mattr(f);
654 
655 	exceptions = pager_lock();
656 
657 	while (s) {
658 		s2 = MIN(CORE_MMU_PGDIR_SIZE - (b & CORE_MMU_PGDIR_MASK), s);
659 		if (!area || area->base != b || area->size != s2) {
660 			ret = false;
661 			goto out;
662 		}
663 		b += s2;
664 		s -= s2;
665 
666 		TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link) {
667 			if (pmem->area != area)
668 				continue;
669 			area_get_entry(pmem->area, pmem->pgidx, &pa, &a);
670 			if (a & TEE_MATTR_VALID_BLOCK)
671 				assert(pa == get_pmem_pa(pmem));
672 			else
673 				pa = get_pmem_pa(pmem);
674 			if (a == f)
675 				continue;
676 			area_set_entry(pmem->area, pmem->pgidx, 0, 0);
677 			/* TODO only invalidate entries touched above */
678 			core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0);
679 			if (!(flags & TEE_MATTR_UW))
680 				tee_pager_save_page(pmem, a);
681 			area_set_entry(pmem->area, pmem->pgidx, pa, f);
682 		}
683 
684 		area->flags = f;
685 		area = TAILQ_NEXT(area, link);
686 	}
687 
688 	ret = true;
689 out:
690 	pager_unlock(exceptions);
691 	return ret;
692 }
693 KEEP_PAGER(tee_pager_set_uta_area_attr);
694 #endif /*CFG_PAGED_USER_TA*/
695 
696 static bool tee_pager_unhide_page(vaddr_t page_va)
697 {
698 	struct tee_pager_pmem *pmem;
699 
700 	TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link) {
701 		paddr_t pa;
702 		uint32_t attr;
703 
704 		if (pmem->pgidx == INVALID_PGIDX)
705 			continue;
706 
707 		area_get_entry(pmem->area, pmem->pgidx, &pa, &attr);
708 
709 		if (!(attr &
710 		     (TEE_MATTR_HIDDEN_BLOCK | TEE_MATTR_HIDDEN_DIRTY_BLOCK)))
711 			continue;
712 
713 		if (area_va2idx(pmem->area, page_va) == pmem->pgidx) {
714 			uint32_t a = get_area_mattr(pmem->area->flags);
715 
716 			/* page is hidden, show and move to back */
717 			if (pa != get_pmem_pa(pmem))
718 				panic("unexpected pa");
719 
720 			/*
721 			 * If it's not a dirty block, then it should be
722 			 * read only.
723 			 */
724 			if (!(attr & TEE_MATTR_HIDDEN_DIRTY_BLOCK))
725 				a &= ~(TEE_MATTR_PW | TEE_MATTR_UW);
726 			else
727 				FMSG("Unhide %#" PRIxVA, page_va);
728 
729 			if (page_va == 0x8000a000)
730 				FMSG("unhide %#" PRIxVA " a %#" PRIX32,
731 					page_va, a);
732 			area_set_entry(pmem->area, pmem->pgidx, pa, a);
733 
734 			TAILQ_REMOVE(&tee_pager_pmem_head, pmem, link);
735 			TAILQ_INSERT_TAIL(&tee_pager_pmem_head, pmem, link);
736 
737 			/* TODO only invalidate entry touched above */
738 			core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0);
739 
740 			incr_hidden_hits();
741 			return true;
742 		}
743 	}
744 
745 	return false;
746 }
747 
748 static void tee_pager_hide_pages(void)
749 {
750 	struct tee_pager_pmem *pmem;
751 	size_t n = 0;
752 
753 	TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link) {
754 		paddr_t pa;
755 		uint32_t attr;
756 		uint32_t a;
757 
758 		if (n >= TEE_PAGER_NHIDE)
759 			break;
760 		n++;
761 
762 		/* we cannot hide pages when pmem->area is not defined. */
763 		if (!pmem->area)
764 			continue;
765 
766 		area_get_entry(pmem->area, pmem->pgidx, &pa, &attr);
767 		if (!(attr & TEE_MATTR_VALID_BLOCK))
768 			continue;
769 
770 		assert(pa == get_pmem_pa(pmem));
771 		if (attr & (TEE_MATTR_PW | TEE_MATTR_UW)){
772 			a = TEE_MATTR_HIDDEN_DIRTY_BLOCK;
773 			FMSG("Hide %#" PRIxVA,
774 			     area_idx2va(pmem->area, pmem->pgidx));
775 		} else
776 			a = TEE_MATTR_HIDDEN_BLOCK;
777 		area_set_entry(pmem->area, pmem->pgidx, pa, a);
778 	}
779 
780 	/* TODO only invalidate entries touched above */
781 	core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0);
782 }
783 
784 /*
785  * Find mapped pmem, hide and move to pageble pmem.
786  * Return false if page was not mapped, and true if page was mapped.
787  */
788 static bool tee_pager_release_one_phys(struct tee_pager_area *area,
789 				       vaddr_t page_va)
790 {
791 	struct tee_pager_pmem *pmem;
792 	unsigned pgidx;
793 	paddr_t pa;
794 	uint32_t attr;
795 
796 	pgidx = area_va2idx(area, page_va);
797 	area_get_entry(area, pgidx, &pa, &attr);
798 
799 	FMSG("%" PRIxVA " : %" PRIxPA "|%x", page_va, pa, attr);
800 
801 	TAILQ_FOREACH(pmem, &tee_pager_lock_pmem_head, link) {
802 		if (pmem->area != area || pmem->pgidx != pgidx)
803 			continue;
804 
805 		assert(pa == get_pmem_pa(pmem));
806 		area_set_entry(area, pgidx, 0, 0);
807 		pgt_dec_used_entries(area->pgt);
808 		TAILQ_REMOVE(&tee_pager_lock_pmem_head, pmem, link);
809 		pmem->area = NULL;
810 		pmem->pgidx = INVALID_PGIDX;
811 		tee_pager_npages++;
812 		set_npages();
813 		TAILQ_INSERT_HEAD(&tee_pager_pmem_head, pmem, link);
814 		incr_zi_released();
815 		return true;
816 	}
817 
818 	return false;
819 }
820 
821 /* Finds the oldest page and unmats it from its old virtual address */
822 static struct tee_pager_pmem *tee_pager_get_page(struct tee_pager_area *area)
823 {
824 	struct tee_pager_pmem *pmem;
825 
826 	pmem = TAILQ_FIRST(&tee_pager_pmem_head);
827 	if (!pmem) {
828 		EMSG("No pmem entries");
829 		return NULL;
830 	}
831 	if (pmem->pgidx != INVALID_PGIDX) {
832 		uint32_t a;
833 
834 		assert(pmem->area && pmem->area->pgt);
835 		area_get_entry(pmem->area, pmem->pgidx, NULL, &a);
836 		area_set_entry(pmem->area, pmem->pgidx, 0, 0);
837 		pgt_dec_used_entries(pmem->area->pgt);
838 		/* TODO only invalidate entries touched above */
839 		core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0);
840 		tee_pager_save_page(pmem, a);
841 	}
842 
843 	TAILQ_REMOVE(&tee_pager_pmem_head, pmem, link);
844 	pmem->pgidx = INVALID_PGIDX;
845 	pmem->area = NULL;
846 	if (area->type == AREA_TYPE_LOCK) {
847 		/* Move page to lock list */
848 		if (tee_pager_npages <= 0)
849 			panic("running out of page");
850 		tee_pager_npages--;
851 		set_npages();
852 		TAILQ_INSERT_TAIL(&tee_pager_lock_pmem_head, pmem, link);
853 	} else {
854 		/* move page to back */
855 		TAILQ_INSERT_TAIL(&tee_pager_pmem_head, pmem, link);
856 	}
857 
858 	return pmem;
859 }
860 
861 static bool pager_update_permissions(struct tee_pager_area *area,
862 			struct abort_info *ai, bool *handled)
863 {
864 	unsigned int pgidx = area_va2idx(area, ai->va);
865 	uint32_t attr;
866 	paddr_t pa;
867 
868 	*handled = false;
869 
870 	area_get_entry(area, pgidx, &pa, &attr);
871 
872 	/* Not mapped */
873 	if (!(attr & TEE_MATTR_VALID_BLOCK))
874 		return false;
875 
876 	/* Not readable, should not happen */
877 	if (abort_is_user_exception(ai)) {
878 		if (!(attr & TEE_MATTR_UR))
879 			return true;
880 	} else {
881 		if (!(attr & TEE_MATTR_PR)) {
882 			abort_print_error(ai);
883 			panic();
884 		}
885 	}
886 
887 	switch (core_mmu_get_fault_type(ai->fault_descr)) {
888 	case CORE_MMU_FAULT_TRANSLATION:
889 	case CORE_MMU_FAULT_READ_PERMISSION:
890 		if (ai->abort_type == ABORT_TYPE_PREFETCH) {
891 			/* Check attempting to execute from an NOX page */
892 			if (abort_is_user_exception(ai)) {
893 				if (!(attr & TEE_MATTR_UX))
894 					return true;
895 			} else {
896 				if (!(attr & TEE_MATTR_PX)) {
897 					abort_print_error(ai);
898 					panic();
899 				}
900 			}
901 		}
902 		/* Since the page is mapped now it's OK */
903 		break;
904 	case CORE_MMU_FAULT_WRITE_PERMISSION:
905 		/* Check attempting to write to an RO page */
906 		if (abort_is_user_exception(ai)) {
907 			if (!(area->flags & TEE_MATTR_UW))
908 				return true;
909 			if (!(attr & TEE_MATTR_UW)) {
910 				FMSG("Dirty %p",
911 				     (void *)(ai->va & ~SMALL_PAGE_MASK));
912 				area_set_entry(area, pgidx, pa,
913 					       get_area_mattr(area->flags));
914 				/* TODO only invalidate entry above */
915 				core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0);
916 			}
917 
918 		} else {
919 			if (!(area->flags & TEE_MATTR_PW)) {
920 				abort_print_error(ai);
921 				panic();
922 			}
923 			if (!(attr & TEE_MATTR_PW)) {
924 				FMSG("Dirty %p",
925 				     (void *)(ai->va & ~SMALL_PAGE_MASK));
926 				area_set_entry(area, pgidx, pa,
927 					       get_area_mattr(area->flags));
928 				/* TODO only invalidate entry above */
929 				core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0);
930 			}
931 		}
932 		/* Since permissions has been updated now it's OK */
933 		break;
934 	default:
935 		/* Some fault we can't deal with */
936 		if (abort_is_user_exception(ai))
937 			return true;
938 		abort_print_error(ai);
939 		panic();
940 	}
941 	*handled = true;
942 	return true;
943 }
944 
945 #ifdef CFG_TEE_CORE_DEBUG
946 static void stat_handle_fault(void)
947 {
948 	static size_t num_faults;
949 	static size_t min_npages = SIZE_MAX;
950 	static size_t total_min_npages = SIZE_MAX;
951 
952 	num_faults++;
953 	if ((num_faults % 1024) == 0 || tee_pager_npages < total_min_npages) {
954 		DMSG("nfaults %zu npages %zu (min %zu)",
955 		     num_faults, tee_pager_npages, min_npages);
956 		min_npages = tee_pager_npages; /* reset */
957 	}
958 	if (tee_pager_npages < min_npages)
959 		min_npages = tee_pager_npages;
960 	if (tee_pager_npages < total_min_npages)
961 		total_min_npages = tee_pager_npages;
962 }
963 #else
964 static void stat_handle_fault(void)
965 {
966 }
967 #endif
968 
969 bool tee_pager_handle_fault(struct abort_info *ai)
970 {
971 	struct tee_pager_area *area;
972 	vaddr_t page_va = ai->va & ~SMALL_PAGE_MASK;
973 	uint32_t exceptions;
974 	bool ret;
975 
976 #ifdef TEE_PAGER_DEBUG_PRINT
977 	abort_print(ai);
978 #endif
979 
980 	/*
981 	 * We're updating pages that can affect several active CPUs at a
982 	 * time below. We end up here because a thread tries to access some
983 	 * memory that isn't available. We have to be careful when making
984 	 * that memory available as other threads may succeed in accessing
985 	 * that address the moment after we've made it available.
986 	 *
987 	 * That means that we can't just map the memory and populate the
988 	 * page, instead we use the aliased mapping to populate the page
989 	 * and once everything is ready we map it.
990 	 */
991 	exceptions = pager_lock();
992 
993 	stat_handle_fault();
994 
995 	/* check if the access is valid */
996 	if (abort_is_user_exception(ai)) {
997 		area = find_uta_area(ai->va);
998 
999 	} else {
1000 		area = find_area(&tee_pager_area_head, ai->va);
1001 		if (!area)
1002 			area = find_uta_area(ai->va);
1003 	}
1004 	if (!area) {
1005 		ret = false;
1006 		goto out;
1007 	}
1008 
1009 	if (!tee_pager_unhide_page(page_va)) {
1010 		struct tee_pager_pmem *pmem = NULL;
1011 		uint32_t attr;
1012 
1013 		/*
1014 		 * The page wasn't hidden, but some other core may have
1015 		 * updated the table entry before we got here or we need
1016 		 * to make a read-only page read-write (dirty).
1017 		 */
1018 		if (pager_update_permissions(area, ai, &ret)) {
1019 			/*
1020 			 * Nothing more to do with the abort. The problem
1021 			 * could already have been dealt with from another
1022 			 * core or if ret is false the TA will be paniced.
1023 			 */
1024 			goto out;
1025 		}
1026 
1027 		pmem = tee_pager_get_page(area);
1028 		if (!pmem) {
1029 			abort_print(ai);
1030 			panic();
1031 		}
1032 
1033 		/* load page code & data */
1034 		tee_pager_load_page(area, page_va, pmem->va_alias);
1035 
1036 		/*
1037 		 * We've updated the page using the aliased mapping and
1038 		 * some cache maintenence is now needed if it's an
1039 		 * executable page.
1040 		 *
1041 		 * Since the d-cache is a Physically-indexed,
1042 		 * physically-tagged (PIPT) cache we can clean the aliased
1043 		 * address instead of the real virtual address.
1044 		 *
1045 		 * The i-cache can also be PIPT, but may be something else
1046 		 * to, to keep it simple we invalidate the entire i-cache.
1047 		 * As a future optimization we may invalidate only the
1048 		 * aliased area if it a PIPT cache else the entire cache.
1049 		 */
1050 		if (area->flags & (TEE_MATTR_PX | TEE_MATTR_UX)) {
1051 			/*
1052 			 * Doing these operations to LoUIS (Level of
1053 			 * unification, Inner Shareable) would be enough
1054 			 */
1055 			cache_maintenance_l1(DCACHE_AREA_CLEAN,
1056 				pmem->va_alias, SMALL_PAGE_SIZE);
1057 
1058 			cache_maintenance_l1(ICACHE_INVALIDATE, NULL, 0);
1059 		}
1060 
1061 		pmem->area = area;
1062 		pmem->pgidx = area_va2idx(area, ai->va);
1063 		attr = get_area_mattr(area->flags) &
1064 			~(TEE_MATTR_PW | TEE_MATTR_UW);
1065 		area_set_entry(area, pmem->pgidx, get_pmem_pa(pmem), attr);
1066 		pgt_inc_used_entries(area->pgt);
1067 
1068 		FMSG("Mapped 0x%" PRIxVA " -> 0x%" PRIxPA,
1069 		     area_idx2va(area, pmem->pgidx), get_pmem_pa(pmem));
1070 
1071 	}
1072 
1073 	tee_pager_hide_pages();
1074 	ret = true;
1075 out:
1076 	pager_unlock(exceptions);
1077 	return ret;
1078 }
1079 
1080 void tee_pager_add_pages(vaddr_t vaddr, size_t npages, bool unmap)
1081 {
1082 	struct core_mmu_table_info *ti = &tee_pager_tbl_info;
1083 	size_t n;
1084 
1085 	DMSG("0x%" PRIxVA " - 0x%" PRIxVA " : %d",
1086 	     vaddr, vaddr + npages * SMALL_PAGE_SIZE, (int)unmap);
1087 
1088 	/* setup memory */
1089 	for (n = 0; n < npages; n++) {
1090 		struct tee_pager_pmem *pmem;
1091 		vaddr_t va = vaddr + n * SMALL_PAGE_SIZE;
1092 		unsigned pgidx = core_mmu_va2idx(ti, va);
1093 		paddr_t pa;
1094 		uint32_t attr;
1095 
1096 		/*
1097 		 * Note that we can only support adding pages in the
1098 		 * valid range of this table info, currently not a problem.
1099 		 */
1100 		core_mmu_get_entry(ti, pgidx, &pa, &attr);
1101 
1102 		/* Ignore unmapped pages/blocks */
1103 		if (!(attr & TEE_MATTR_VALID_BLOCK))
1104 			continue;
1105 
1106 		pmem = malloc(sizeof(struct tee_pager_pmem));
1107 		if (!pmem)
1108 			panic("out of mem");
1109 
1110 		pmem->va_alias = pager_add_alias_page(pa);
1111 
1112 		if (unmap) {
1113 			pmem->area = NULL;
1114 			pmem->pgidx = INVALID_PGIDX;
1115 			core_mmu_set_entry(ti, pgidx, 0, 0);
1116 			pgt_dec_used_entries(&pager_core_pgt);
1117 		} else {
1118 			/*
1119 			 * The page is still mapped, let's assign the area
1120 			 * and update the protection bits accordingly.
1121 			 */
1122 			pmem->area = find_area(&tee_pager_area_head, va);
1123 			assert(pmem->area->pgt == &pager_core_pgt);
1124 			pmem->pgidx = pgidx;
1125 			assert(pa == get_pmem_pa(pmem));
1126 			area_set_entry(pmem->area, pgidx, pa,
1127 				       get_area_mattr(pmem->area->flags));
1128 		}
1129 
1130 		tee_pager_npages++;
1131 		incr_npages_all();
1132 		set_npages();
1133 		TAILQ_INSERT_TAIL(&tee_pager_pmem_head, pmem, link);
1134 	}
1135 
1136 	/* Invalidate secure TLB */
1137 	core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0);
1138 }
1139 
1140 #ifdef CFG_PAGED_USER_TA
1141 static struct pgt *find_pgt(struct pgt *pgt, vaddr_t va)
1142 {
1143 	struct pgt *p = pgt;
1144 
1145 	while (p && (va & ~CORE_MMU_PGDIR_MASK) != p->vabase)
1146 		p = SLIST_NEXT(p, link);
1147 	return p;
1148 }
1149 
1150 void tee_pager_assign_uta_tables(struct user_ta_ctx *utc)
1151 {
1152 	struct tee_pager_area *area;
1153 	struct pgt *pgt = SLIST_FIRST(&thread_get_tsd()->pgt_cache);
1154 
1155 	TAILQ_FOREACH(area, utc->areas, link) {
1156 		if (!area->pgt)
1157 			area->pgt = find_pgt(pgt, area->base);
1158 		else
1159 			assert(area->pgt == find_pgt(pgt, area->base));
1160 		if (!area->pgt)
1161 			panic();
1162 	}
1163 }
1164 
1165 void tee_pager_pgt_save_and_release_entries(struct pgt *pgt)
1166 {
1167 	struct tee_pager_pmem *pmem;
1168 	struct tee_pager_area *area;
1169 	uint32_t exceptions;
1170 	uint32_t attr;
1171 
1172 	exceptions = pager_lock();
1173 
1174 	if (!pgt->num_used_entries)
1175 		goto out;
1176 
1177 	TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link) {
1178 		if (!pmem->area || pmem->pgidx == INVALID_PGIDX)
1179 			continue;
1180 		if (pmem->area->pgt == pgt) {
1181 			area_get_entry(pmem->area, pmem->pgidx, NULL, &attr);
1182 			area_set_entry(pmem->area, pmem->pgidx, 0, 0);
1183 			tee_pager_save_page(pmem, attr);
1184 			pmem->pgidx = INVALID_PGIDX;
1185 			pmem->area = NULL;
1186 			pgt->num_used_entries--;
1187 		}
1188 	}
1189 	assert(!pgt->num_used_entries);
1190 
1191 out:
1192 	if (is_user_ta_ctx(pgt->ctx)) {
1193 		TAILQ_FOREACH(area, to_user_ta_ctx(pgt->ctx)->areas, link) {
1194 			if (area->pgt == pgt)
1195 				area->pgt = NULL;
1196 		}
1197 	}
1198 
1199 	pager_unlock(exceptions);
1200 }
1201 KEEP_PAGER(tee_pager_pgt_save_and_release_entries);
1202 #endif /*CFG_PAGED_USER_TA*/
1203 
1204 void tee_pager_release_phys(void *addr, size_t size)
1205 {
1206 	bool unmaped = false;
1207 	vaddr_t va = (vaddr_t)addr;
1208 	vaddr_t begin = ROUNDUP(va, SMALL_PAGE_SIZE);
1209 	vaddr_t end = ROUNDDOWN(va + size, SMALL_PAGE_SIZE);
1210 	struct tee_pager_area *area;
1211 	uint32_t exceptions;
1212 
1213 	if (!size)
1214 		return;
1215 
1216 	area = find_area(&tee_pager_area_head, begin);
1217 	if (!area ||
1218 	    area != find_area(&tee_pager_area_head, end - SMALL_PAGE_SIZE))
1219 		panic();
1220 
1221 	exceptions = pager_lock();
1222 
1223 	for (va = begin; va < end; va += SMALL_PAGE_SIZE)
1224 		unmaped |= tee_pager_release_one_phys(area, va);
1225 
1226 	/* Invalidate secure TLB */
1227 	if (unmaped)
1228 		core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0);
1229 
1230 	pager_unlock(exceptions);
1231 }
1232 KEEP_PAGER(tee_pager_release_phys);
1233 
1234 void *tee_pager_alloc(size_t size, uint32_t flags)
1235 {
1236 	tee_mm_entry_t *mm;
1237 	uint32_t f = TEE_MATTR_PW | TEE_MATTR_PR | (flags & TEE_MATTR_LOCKED);
1238 
1239 	if (!size)
1240 		return NULL;
1241 
1242 	mm = tee_mm_alloc(&tee_mm_vcore, ROUNDUP(size, SMALL_PAGE_SIZE));
1243 	if (!mm)
1244 		return NULL;
1245 
1246 	tee_pager_add_core_area(tee_mm_get_smem(mm), tee_mm_get_bytes(mm),
1247 				f, NULL, NULL);
1248 
1249 	return (void *)tee_mm_get_smem(mm);
1250 }
1251