xref: /optee_os/core/arch/arm/kernel/thread.c (revision a1d5c81f8834a9d2c6f4372cce2e59e70e709121)
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 <platform_config.h>
8 
9 #include <arm.h>
10 #include <assert.h>
11 #include <config.h>
12 #include <io.h>
13 #include <keep.h>
14 #include <kernel/asan.h>
15 #include <kernel/boot.h>
16 #include <kernel/linker.h>
17 #include <kernel/lockdep.h>
18 #include <kernel/misc.h>
19 #include <kernel/panic.h>
20 #include <kernel/spinlock.h>
21 #include <kernel/tee_ta_manager.h>
22 #include <kernel/thread_defs.h>
23 #include <kernel/thread.h>
24 #include <kernel/virtualization.h>
25 #include <mm/core_memprot.h>
26 #include <mm/mobj.h>
27 #include <mm/tee_mm.h>
28 #include <mm/tee_mmu.h>
29 #include <mm/tee_pager.h>
30 #include <smccc.h>
31 #include <sm/sm.h>
32 #include <trace.h>
33 #include <util.h>
34 
35 #include "thread_private.h"
36 
37 struct thread_ctx threads[CFG_NUM_THREADS];
38 
39 struct thread_core_local thread_core_local[CFG_TEE_CORE_NB_CORE] __nex_bss;
40 
41 /*
42  * Stacks
43  *
44  * [Lower addresses on the left]
45  *
46  * [ STACK_CANARY_SIZE/2 | STACK_CHECK_EXTRA | STACK_XXX_SIZE | STACK_CANARY_SIZE/2 ]
47  * ^                     ^                   ^                ^
48  * stack_xxx[n]          "hard" top          "soft" top       bottom
49  */
50 
51 #ifdef CFG_WITH_ARM_TRUSTED_FW
52 #define STACK_TMP_OFFS		0
53 #else
54 #define STACK_TMP_OFFS		SM_STACK_TMP_RESERVE_SIZE
55 #endif
56 
57 #ifdef ARM32
58 #ifdef CFG_CORE_SANITIZE_KADDRESS
59 #define STACK_TMP_SIZE		(3072 + STACK_TMP_OFFS)
60 #else
61 #define STACK_TMP_SIZE		(2048 + STACK_TMP_OFFS)
62 #endif
63 #define STACK_THREAD_SIZE	8192
64 
65 #if defined(CFG_CORE_SANITIZE_KADDRESS) || defined(__clang__)
66 #define STACK_ABT_SIZE		3072
67 #else
68 #define STACK_ABT_SIZE		2048
69 #endif
70 
71 #endif /*ARM32*/
72 
73 #ifdef ARM64
74 #if defined(__clang__) && !defined(__OPTIMIZE_SIZE__)
75 #define STACK_TMP_SIZE		(4096 + STACK_TMP_OFFS)
76 #else
77 #define STACK_TMP_SIZE		(2048 + STACK_TMP_OFFS)
78 #endif
79 #define STACK_THREAD_SIZE	8192
80 
81 #if TRACE_LEVEL > 0
82 #define STACK_ABT_SIZE		3072
83 #else
84 #define STACK_ABT_SIZE		1024
85 #endif
86 #endif /*ARM64*/
87 
88 #ifdef CFG_WITH_STACK_CANARIES
89 #ifdef ARM32
90 #define STACK_CANARY_SIZE	(4 * sizeof(uint32_t))
91 #endif
92 #ifdef ARM64
93 #define STACK_CANARY_SIZE	(8 * sizeof(uint32_t))
94 #endif
95 #define START_CANARY_VALUE	0xdededede
96 #define END_CANARY_VALUE	0xabababab
97 #define GET_START_CANARY(name, stack_num) name[stack_num][0]
98 #define GET_END_CANARY(name, stack_num) \
99 	name[stack_num][sizeof(name[stack_num]) / sizeof(uint32_t) - 1]
100 #else
101 #define STACK_CANARY_SIZE	0
102 #endif
103 
104 #ifdef CFG_CORE_DEBUG_CHECK_STACKS
105 /*
106  * Extra space added to each stack in order to reliably detect and dump stack
107  * overflows. Should cover the maximum expected overflow size caused by any C
108  * function (say, 512 bytes; no function should have that much local variables),
109  * plus the maximum stack space needed by __cyg_profile_func_exit(): about 1 KB,
110  * a large part of which is used to print the call stack. Total: 1.5 KB.
111  */
112 #define STACK_CHECK_EXTRA	1536
113 #else
114 #define STACK_CHECK_EXTRA	0
115 #endif
116 
117 #define DECLARE_STACK(name, num_stacks, stack_size, linkage) \
118 linkage uint32_t name[num_stacks] \
119 		[ROUNDUP(stack_size + STACK_CANARY_SIZE + STACK_CHECK_EXTRA, \
120 			 STACK_ALIGNMENT) / sizeof(uint32_t)] \
121 		__attribute__((section(".nozi_stack." # name), \
122 			       aligned(STACK_ALIGNMENT)))
123 
124 #define GET_STACK(stack) ((vaddr_t)(stack) + STACK_SIZE(stack))
125 
126 DECLARE_STACK(stack_tmp, CFG_TEE_CORE_NB_CORE, STACK_TMP_SIZE, static);
127 DECLARE_STACK(stack_abt, CFG_TEE_CORE_NB_CORE, STACK_ABT_SIZE, static);
128 #ifndef CFG_WITH_PAGER
129 DECLARE_STACK(stack_thread, CFG_NUM_THREADS, STACK_THREAD_SIZE, static);
130 #endif
131 
132 #define GET_STACK_TOP_HARD(stack, n) \
133 	((vaddr_t)&(stack)[n] + STACK_CANARY_SIZE / 2)
134 #define GET_STACK_TOP_SOFT(stack, n) \
135 	(GET_STACK_TOP_HARD(stack, n) + STACK_CHECK_EXTRA)
136 #define GET_STACK_BOTTOM(stack, n) ((vaddr_t)&(stack)[n] + sizeof(stack[n]) - \
137 				    STACK_CANARY_SIZE / 2)
138 
139 const void *stack_tmp_export __section(".identity_map.stack_tmp_export") =
140 	(void *)(GET_STACK_BOTTOM(stack_tmp, 0) - STACK_TMP_OFFS);
141 const uint32_t stack_tmp_stride __section(".identity_map.stack_tmp_stride") =
142 	sizeof(stack_tmp[0]);
143 
144 /*
145  * These stack setup info are required by secondary boot cores before they
146  * each locally enable the pager (the mmu). Hence kept in pager sections.
147  */
148 DECLARE_KEEP_PAGER(stack_tmp_export);
149 DECLARE_KEEP_PAGER(stack_tmp_stride);
150 
151 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
152 static vaddr_t thread_user_kcode_va __nex_bss;
153 long thread_user_kcode_offset __nex_bss;
154 static size_t thread_user_kcode_size __nex_bss;
155 #endif
156 
157 #if defined(CFG_CORE_UNMAP_CORE_AT_EL0) && \
158 	defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
159 long thread_user_kdata_sp_offset __nex_bss;
160 static uint8_t thread_user_kdata_page[
161 	ROUNDUP(sizeof(thread_core_local), SMALL_PAGE_SIZE)]
162 	__aligned(SMALL_PAGE_SIZE)
163 #ifndef CFG_VIRTUALIZATION
164 	__section(".nozi.kdata_page");
165 #else
166 	__section(".nex_nozi.kdata_page");
167 #endif
168 #endif
169 
170 static unsigned int thread_global_lock __nex_bss = SPINLOCK_UNLOCK;
171 
172 static void init_canaries(void)
173 {
174 #ifdef CFG_WITH_STACK_CANARIES
175 	size_t n;
176 #define INIT_CANARY(name)						\
177 	for (n = 0; n < ARRAY_SIZE(name); n++) {			\
178 		uint32_t *start_canary = &GET_START_CANARY(name, n);	\
179 		uint32_t *end_canary = &GET_END_CANARY(name, n);	\
180 									\
181 		*start_canary = START_CANARY_VALUE;			\
182 		*end_canary = END_CANARY_VALUE;				\
183 		DMSG("#Stack canaries for %s[%zu] with top at %p",	\
184 			#name, n, (void *)(end_canary - 1));		\
185 		DMSG("watch *%p", (void *)end_canary);			\
186 	}
187 
188 	INIT_CANARY(stack_tmp);
189 	INIT_CANARY(stack_abt);
190 #if !defined(CFG_WITH_PAGER) && !defined(CFG_VIRTUALIZATION)
191 	INIT_CANARY(stack_thread);
192 #endif
193 #endif/*CFG_WITH_STACK_CANARIES*/
194 }
195 
196 #define CANARY_DIED(stack, loc, n) \
197 	do { \
198 		EMSG_RAW("Dead canary at %s of '%s[%zu]'", #loc, #stack, n); \
199 		panic(); \
200 	} while (0)
201 
202 void thread_check_canaries(void)
203 {
204 #ifdef CFG_WITH_STACK_CANARIES
205 	size_t n;
206 
207 	for (n = 0; n < ARRAY_SIZE(stack_tmp); n++) {
208 		if (GET_START_CANARY(stack_tmp, n) != START_CANARY_VALUE)
209 			CANARY_DIED(stack_tmp, start, n);
210 		if (GET_END_CANARY(stack_tmp, n) != END_CANARY_VALUE)
211 			CANARY_DIED(stack_tmp, end, n);
212 	}
213 
214 	for (n = 0; n < ARRAY_SIZE(stack_abt); n++) {
215 		if (GET_START_CANARY(stack_abt, n) != START_CANARY_VALUE)
216 			CANARY_DIED(stack_abt, start, n);
217 		if (GET_END_CANARY(stack_abt, n) != END_CANARY_VALUE)
218 			CANARY_DIED(stack_abt, end, n);
219 
220 	}
221 #if !defined(CFG_WITH_PAGER) && !defined(CFG_VIRTUALIZATION)
222 	for (n = 0; n < ARRAY_SIZE(stack_thread); n++) {
223 		if (GET_START_CANARY(stack_thread, n) != START_CANARY_VALUE)
224 			CANARY_DIED(stack_thread, start, n);
225 		if (GET_END_CANARY(stack_thread, n) != END_CANARY_VALUE)
226 			CANARY_DIED(stack_thread, end, n);
227 	}
228 #endif
229 #endif/*CFG_WITH_STACK_CANARIES*/
230 }
231 
232 void thread_lock_global(void)
233 {
234 	cpu_spin_lock(&thread_global_lock);
235 }
236 
237 void thread_unlock_global(void)
238 {
239 	cpu_spin_unlock(&thread_global_lock);
240 }
241 
242 #ifdef ARM32
243 uint32_t __nostackcheck thread_get_exceptions(void)
244 {
245 	uint32_t cpsr = read_cpsr();
246 
247 	return (cpsr >> CPSR_F_SHIFT) & THREAD_EXCP_ALL;
248 }
249 
250 void __nostackcheck thread_set_exceptions(uint32_t exceptions)
251 {
252 	uint32_t cpsr = read_cpsr();
253 
254 	/* Foreign interrupts must not be unmasked while holding a spinlock */
255 	if (!(exceptions & THREAD_EXCP_FOREIGN_INTR))
256 		assert_have_no_spinlock();
257 
258 	cpsr &= ~(THREAD_EXCP_ALL << CPSR_F_SHIFT);
259 	cpsr |= ((exceptions & THREAD_EXCP_ALL) << CPSR_F_SHIFT);
260 
261 	barrier();
262 	write_cpsr(cpsr);
263 	barrier();
264 }
265 #endif /*ARM32*/
266 
267 #ifdef ARM64
268 uint32_t __nostackcheck thread_get_exceptions(void)
269 {
270 	uint32_t daif = read_daif();
271 
272 	return (daif >> DAIF_F_SHIFT) & THREAD_EXCP_ALL;
273 }
274 
275 void __nostackcheck thread_set_exceptions(uint32_t exceptions)
276 {
277 	uint32_t daif = read_daif();
278 
279 	/* Foreign interrupts must not be unmasked while holding a spinlock */
280 	if (!(exceptions & THREAD_EXCP_FOREIGN_INTR))
281 		assert_have_no_spinlock();
282 
283 	daif &= ~(THREAD_EXCP_ALL << DAIF_F_SHIFT);
284 	daif |= ((exceptions & THREAD_EXCP_ALL) << DAIF_F_SHIFT);
285 
286 	barrier();
287 	write_daif(daif);
288 	barrier();
289 }
290 #endif /*ARM64*/
291 
292 uint32_t __nostackcheck thread_mask_exceptions(uint32_t exceptions)
293 {
294 	uint32_t state = thread_get_exceptions();
295 
296 	thread_set_exceptions(state | (exceptions & THREAD_EXCP_ALL));
297 	return state;
298 }
299 
300 void __nostackcheck thread_unmask_exceptions(uint32_t state)
301 {
302 	thread_set_exceptions(state & THREAD_EXCP_ALL);
303 }
304 
305 
306 static struct thread_core_local * __nostackcheck
307 get_core_local(unsigned int pos)
308 {
309 	/*
310 	 * Foreign interrupts must be disabled before playing with core_local
311 	 * since we otherwise may be rescheduled to a different core in the
312 	 * middle of this function.
313 	 */
314 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
315 
316 	assert(pos < CFG_TEE_CORE_NB_CORE);
317 	return &thread_core_local[pos];
318 }
319 
320 struct thread_core_local * __nostackcheck thread_get_core_local(void)
321 {
322 	unsigned int pos = get_core_pos();
323 
324 	return get_core_local(pos);
325 }
326 
327 #ifdef CFG_CORE_DEBUG_CHECK_STACKS
328 static void print_stack_limits(void)
329 {
330 	size_t n = 0;
331 	vaddr_t __maybe_unused start = 0;
332 	vaddr_t __maybe_unused end = 0;
333 
334 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++) {
335 		start = GET_STACK_TOP_SOFT(stack_tmp, n);
336 		end = GET_STACK_BOTTOM(stack_tmp, n);
337 		DMSG("tmp [%zu] 0x%" PRIxVA "..0x%" PRIxVA, n, start, end);
338 	}
339 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++) {
340 		start = GET_STACK_TOP_SOFT(stack_abt, n);
341 		end = GET_STACK_BOTTOM(stack_abt, n);
342 		DMSG("abt [%zu] 0x%" PRIxVA "..0x%" PRIxVA, n, start, end);
343 	}
344 	for (n = 0; n < CFG_NUM_THREADS; n++) {
345 		end = threads[n].stack_va_end;
346 		start = end - STACK_THREAD_SIZE;
347 		DMSG("thr [%zu] 0x%" PRIxVA "..0x%" PRIxVA, n, start, end);
348 	}
349 }
350 
351 static void check_stack_limits(void)
352 {
353 	vaddr_t stack_start = 0;
354 	vaddr_t stack_end = 0;
355 	/* Any value in the current stack frame will do */
356 	vaddr_t current_sp = (vaddr_t)&stack_start;
357 
358 	if (!get_stack_soft_limits(&stack_start, &stack_end))
359 		panic("Unknown stack limits");
360 	if (current_sp < stack_start || current_sp > stack_end) {
361 		DMSG("Stack pointer out of range (0x%" PRIxVA ")", current_sp);
362 		print_stack_limits();
363 		panic();
364 	}
365 }
366 
367 static bool * __nostackcheck get_stackcheck_recursion_flag(void)
368 {
369 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
370 	unsigned int pos = get_core_pos();
371 	struct thread_core_local *l = get_core_local(pos);
372 	int ct = l->curr_thread;
373 	bool *p = NULL;
374 
375 	if (l->flags & (THREAD_CLF_ABORT | THREAD_CLF_TMP))
376 		p = &l->stackcheck_recursion;
377 	else if (!l->flags)
378 		p = &threads[ct].tsd.stackcheck_recursion;
379 
380 	thread_unmask_exceptions(exceptions);
381 	return p;
382 }
383 
384 void __cyg_profile_func_enter(void *this_fn, void *call_site);
385 void __nostackcheck __cyg_profile_func_enter(void *this_fn __unused,
386 					     void *call_site __unused)
387 {
388 	bool *p = get_stackcheck_recursion_flag();
389 
390 	assert(p);
391 	if (*p)
392 		return;
393 	*p = true;
394 	check_stack_limits();
395 	*p = false;
396 }
397 
398 void __cyg_profile_func_exit(void *this_fn, void *call_site);
399 void __nostackcheck __cyg_profile_func_exit(void *this_fn __unused,
400 					    void *call_site __unused)
401 {
402 }
403 #else
404 static void print_stack_limits(void)
405 {
406 }
407 #endif
408 
409 static void thread_lazy_save_ns_vfp(void)
410 {
411 #ifdef CFG_WITH_VFP
412 	struct thread_ctx *thr = threads + thread_get_id();
413 
414 	thr->vfp_state.ns_saved = false;
415 	vfp_lazy_save_state_init(&thr->vfp_state.ns);
416 #endif /*CFG_WITH_VFP*/
417 }
418 
419 static void thread_lazy_restore_ns_vfp(void)
420 {
421 #ifdef CFG_WITH_VFP
422 	struct thread_ctx *thr = threads + thread_get_id();
423 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
424 
425 	assert(!thr->vfp_state.sec_lazy_saved && !thr->vfp_state.sec_saved);
426 
427 	if (tuv && tuv->lazy_saved && !tuv->saved) {
428 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
429 		tuv->saved = true;
430 	}
431 
432 	vfp_lazy_restore_state(&thr->vfp_state.ns, thr->vfp_state.ns_saved);
433 	thr->vfp_state.ns_saved = false;
434 #endif /*CFG_WITH_VFP*/
435 }
436 
437 #ifdef ARM32
438 static void init_regs(struct thread_ctx *thread, uint32_t a0, uint32_t a1,
439 		      uint32_t a2, uint32_t a3)
440 {
441 	thread->regs.pc = (uint32_t)thread_std_smc_entry;
442 
443 	/*
444 	 * Stdcalls starts in SVC mode with masked foreign interrupts, masked
445 	 * Asynchronous abort and unmasked native interrupts.
446 	 */
447 	thread->regs.cpsr = read_cpsr() & ARM32_CPSR_E;
448 	thread->regs.cpsr |= CPSR_MODE_SVC | CPSR_A |
449 			(THREAD_EXCP_FOREIGN_INTR << ARM32_CPSR_F_SHIFT);
450 	/* Enable thumb mode if it's a thumb instruction */
451 	if (thread->regs.pc & 1)
452 		thread->regs.cpsr |= CPSR_T;
453 	/* Reinitialize stack pointer */
454 	thread->regs.svc_sp = thread->stack_va_end;
455 
456 	/*
457 	 * Copy arguments into context. This will make the
458 	 * arguments appear in r0-r7 when thread is started.
459 	 */
460 	thread->regs.r0 = a0;
461 	thread->regs.r1 = a1;
462 	thread->regs.r2 = a2;
463 	thread->regs.r3 = a3;
464 	thread->regs.r4 = 0;
465 	thread->regs.r5 = 0;
466 	thread->regs.r6 = 0;
467 	thread->regs.r7 = 0;
468 }
469 #endif /*ARM32*/
470 
471 #ifdef ARM64
472 static void init_regs(struct thread_ctx *thread, uint32_t a0, uint32_t a1,
473 		      uint32_t a2, uint32_t a3)
474 {
475 	thread->regs.pc = (uint64_t)thread_std_smc_entry;
476 
477 	/*
478 	 * Stdcalls starts in SVC mode with masked foreign interrupts, masked
479 	 * Asynchronous abort and unmasked native interrupts.
480 	 */
481 	thread->regs.cpsr = SPSR_64(SPSR_64_MODE_EL1, SPSR_64_MODE_SP_EL0,
482 				THREAD_EXCP_FOREIGN_INTR | DAIFBIT_ABT);
483 	/* Reinitialize stack pointer */
484 	thread->regs.sp = thread->stack_va_end;
485 
486 	/*
487 	 * Copy arguments into context. This will make the
488 	 * arguments appear in x0-x7 when thread is started.
489 	 */
490 	thread->regs.x[0] = a0;
491 	thread->regs.x[1] = a1;
492 	thread->regs.x[2] = a2;
493 	thread->regs.x[3] = a3;
494 	thread->regs.x[4] = 0;
495 	thread->regs.x[5] = 0;
496 	thread->regs.x[6] = 0;
497 	thread->regs.x[7] = 0;
498 
499 	/* Set up frame pointer as per the Aarch64 AAPCS */
500 	thread->regs.x[29] = 0;
501 }
502 #endif /*ARM64*/
503 
504 void thread_init_boot_thread(void)
505 {
506 	struct thread_core_local *l = thread_get_core_local();
507 
508 	thread_init_threads();
509 
510 	l->curr_thread = 0;
511 	threads[0].state = THREAD_STATE_ACTIVE;
512 }
513 
514 void __nostackcheck thread_clr_boot_thread(void)
515 {
516 	struct thread_core_local *l = thread_get_core_local();
517 
518 	assert(l->curr_thread >= 0 && l->curr_thread < CFG_NUM_THREADS);
519 	assert(threads[l->curr_thread].state == THREAD_STATE_ACTIVE);
520 	threads[l->curr_thread].state = THREAD_STATE_FREE;
521 	l->curr_thread = -1;
522 }
523 
524 void thread_alloc_and_run(uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3)
525 {
526 	size_t n;
527 	struct thread_core_local *l = thread_get_core_local();
528 	bool found_thread = false;
529 
530 	assert(l->curr_thread == -1);
531 
532 	thread_lock_global();
533 
534 	for (n = 0; n < CFG_NUM_THREADS; n++) {
535 		if (threads[n].state == THREAD_STATE_FREE) {
536 			threads[n].state = THREAD_STATE_ACTIVE;
537 			found_thread = true;
538 			break;
539 		}
540 	}
541 
542 	thread_unlock_global();
543 
544 	if (!found_thread)
545 		return;
546 
547 	l->curr_thread = n;
548 
549 	threads[n].flags = 0;
550 	init_regs(threads + n, a0, a1, a2, a3);
551 
552 	thread_lazy_save_ns_vfp();
553 
554 	l->flags &= ~THREAD_CLF_TMP;
555 	thread_resume(&threads[n].regs);
556 	/*NOTREACHED*/
557 	panic();
558 }
559 
560 #ifdef ARM32
561 static void copy_a0_to_a3(struct thread_ctx_regs *regs, uint32_t a0,
562 			  uint32_t a1, uint32_t a2, uint32_t a3)
563 {
564 	/*
565 	 * Update returned values from RPC, values will appear in
566 	 * r0-r3 when thread is resumed.
567 	 */
568 	regs->r0 = a0;
569 	regs->r1 = a1;
570 	regs->r2 = a2;
571 	regs->r3 = a3;
572 }
573 #endif /*ARM32*/
574 
575 #ifdef ARM64
576 static void copy_a0_to_a3(struct thread_ctx_regs *regs, uint32_t a0,
577 			  uint32_t a1, uint32_t a2, uint32_t a3)
578 {
579 	/*
580 	 * Update returned values from RPC, values will appear in
581 	 * x0-x3 when thread is resumed.
582 	 */
583 	regs->x[0] = a0;
584 	regs->x[1] = a1;
585 	regs->x[2] = a2;
586 	regs->x[3] = a3;
587 }
588 #endif /*ARM64*/
589 
590 #ifdef ARM32
591 static bool is_from_user(uint32_t cpsr)
592 {
593 	return (cpsr & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_USR;
594 }
595 #endif
596 
597 #ifdef ARM64
598 static bool is_from_user(uint32_t cpsr)
599 {
600 	if (cpsr & (SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT))
601 		return true;
602 	if (((cpsr >> SPSR_64_MODE_EL_SHIFT) & SPSR_64_MODE_EL_MASK) ==
603 	     SPSR_64_MODE_EL0)
604 		return true;
605 	return false;
606 }
607 #endif
608 
609 #ifdef CFG_SYSCALL_FTRACE
610 static void __noprof ftrace_suspend(void)
611 {
612 	struct tee_ta_session *s = TAILQ_FIRST(&thread_get_tsd()->sess_stack);
613 
614 	if (!s)
615 		return;
616 
617 	if (s->fbuf)
618 		s->fbuf->syscall_trace_suspended = true;
619 }
620 
621 static void __noprof ftrace_resume(void)
622 {
623 	struct tee_ta_session *s = TAILQ_FIRST(&thread_get_tsd()->sess_stack);
624 
625 	if (!s)
626 		return;
627 
628 	if (s->fbuf)
629 		s->fbuf->syscall_trace_suspended = false;
630 }
631 #else
632 static void __noprof ftrace_suspend(void)
633 {
634 }
635 
636 static void __noprof ftrace_resume(void)
637 {
638 }
639 #endif
640 
641 static bool is_user_mode(struct thread_ctx_regs *regs)
642 {
643 	return is_from_user((uint32_t)regs->cpsr);
644 }
645 
646 void thread_resume_from_rpc(uint32_t thread_id, uint32_t a0, uint32_t a1,
647 			    uint32_t a2, uint32_t a3)
648 {
649 	size_t n = thread_id;
650 	struct thread_core_local *l = thread_get_core_local();
651 	bool found_thread = false;
652 
653 	assert(l->curr_thread == -1);
654 
655 	thread_lock_global();
656 
657 	if (n < CFG_NUM_THREADS && threads[n].state == THREAD_STATE_SUSPENDED) {
658 		threads[n].state = THREAD_STATE_ACTIVE;
659 		found_thread = true;
660 	}
661 
662 	thread_unlock_global();
663 
664 	if (!found_thread)
665 		return;
666 
667 	l->curr_thread = n;
668 
669 	if (threads[n].have_user_map) {
670 		core_mmu_set_user_map(&threads[n].user_map);
671 		if (threads[n].flags & THREAD_FLAGS_EXIT_ON_FOREIGN_INTR)
672 			tee_ta_ftrace_update_times_resume();
673 	}
674 
675 	if (is_user_mode(&threads[n].regs))
676 		tee_ta_update_session_utime_resume();
677 
678 	/*
679 	 * Return from RPC to request service of a foreign interrupt must not
680 	 * get parameters from non-secure world.
681 	 */
682 	if (threads[n].flags & THREAD_FLAGS_COPY_ARGS_ON_RETURN) {
683 		copy_a0_to_a3(&threads[n].regs, a0, a1, a2, a3);
684 		threads[n].flags &= ~THREAD_FLAGS_COPY_ARGS_ON_RETURN;
685 	}
686 
687 	thread_lazy_save_ns_vfp();
688 
689 	if (threads[n].have_user_map)
690 		ftrace_resume();
691 
692 	l->flags &= ~THREAD_CLF_TMP;
693 	thread_resume(&threads[n].regs);
694 	/*NOTREACHED*/
695 	panic();
696 }
697 
698 void __nostackcheck *thread_get_tmp_sp(void)
699 {
700 	struct thread_core_local *l = thread_get_core_local();
701 
702 	/*
703 	 * Called from assembly when switching to the temporary stack, so flags
704 	 * need updating
705 	 */
706 	l->flags |= THREAD_CLF_TMP;
707 
708 	return (void *)l->tmp_stack_va_end;
709 }
710 
711 #ifdef ARM64
712 vaddr_t thread_get_saved_thread_sp(void)
713 {
714 	struct thread_core_local *l = thread_get_core_local();
715 	int ct = l->curr_thread;
716 
717 	assert(ct != -1);
718 	return threads[ct].kern_sp;
719 }
720 #endif /*ARM64*/
721 
722 vaddr_t thread_stack_start(void)
723 {
724 	struct thread_ctx *thr;
725 	int ct = thread_get_id_may_fail();
726 
727 	if (ct == -1)
728 		return 0;
729 
730 	thr = threads + ct;
731 	return thr->stack_va_end - STACK_THREAD_SIZE;
732 }
733 
734 size_t thread_stack_size(void)
735 {
736 	return STACK_THREAD_SIZE;
737 }
738 
739 bool get_stack_limits(vaddr_t *start, vaddr_t *end, bool hard)
740 {
741 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
742 	unsigned int pos = get_core_pos();
743 	struct thread_core_local *l = get_core_local(pos);
744 	int ct = l->curr_thread;
745 	bool ret = false;
746 
747 	if (l->flags & THREAD_CLF_TMP) {
748 		if (hard)
749 			*start = GET_STACK_TOP_HARD(stack_tmp, pos);
750 		else
751 			*start = GET_STACK_TOP_SOFT(stack_tmp, pos);
752 		*end = GET_STACK_BOTTOM(stack_tmp, pos);
753 		ret = true;
754 	} else if (l->flags & THREAD_CLF_ABORT) {
755 		if (hard)
756 			*start = GET_STACK_TOP_HARD(stack_abt, pos);
757 		else
758 			*start = GET_STACK_TOP_SOFT(stack_abt, pos);
759 		*end = GET_STACK_BOTTOM(stack_abt, pos);
760 		ret = true;
761 	} else if (!l->flags) {
762 		if (ct < 0 || ct >= CFG_NUM_THREADS)
763 			goto out;
764 
765 		*end = threads[ct].stack_va_end;
766 		*start = *end - STACK_THREAD_SIZE;
767 		if (!hard)
768 			*start += STACK_CHECK_EXTRA;
769 		ret = true;
770 	}
771 out:
772 	thread_unmask_exceptions(exceptions);
773 	return ret;
774 }
775 
776 bool thread_is_from_abort_mode(void)
777 {
778 	struct thread_core_local *l = thread_get_core_local();
779 
780 	return (l->flags >> THREAD_CLF_SAVED_SHIFT) & THREAD_CLF_ABORT;
781 }
782 
783 #ifdef ARM32
784 bool thread_is_in_normal_mode(void)
785 {
786 	return (read_cpsr() & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_SVC;
787 }
788 #endif
789 
790 #ifdef ARM64
791 bool thread_is_in_normal_mode(void)
792 {
793 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
794 	struct thread_core_local *l = thread_get_core_local();
795 	bool ret;
796 
797 	/*
798 	 * If any bit in l->flags is set aside from THREAD_CLF_TMP we're
799 	 * handling some exception.
800 	 */
801 	ret = (l->curr_thread != -1) && !(l->flags & ~THREAD_CLF_TMP);
802 	thread_unmask_exceptions(exceptions);
803 
804 	return ret;
805 }
806 #endif
807 
808 void thread_state_free(void)
809 {
810 	struct thread_core_local *l = thread_get_core_local();
811 	int ct = l->curr_thread;
812 
813 	assert(ct != -1);
814 
815 	thread_lazy_restore_ns_vfp();
816 	tee_pager_release_phys(
817 		(void *)(threads[ct].stack_va_end - STACK_THREAD_SIZE),
818 		STACK_THREAD_SIZE);
819 
820 	thread_lock_global();
821 
822 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
823 	threads[ct].state = THREAD_STATE_FREE;
824 	threads[ct].flags = 0;
825 	l->curr_thread = -1;
826 
827 #ifdef CFG_VIRTUALIZATION
828 	virt_unset_guest();
829 #endif
830 	thread_unlock_global();
831 }
832 
833 #ifdef CFG_WITH_PAGER
834 static void release_unused_kernel_stack(struct thread_ctx *thr,
835 					uint32_t cpsr __maybe_unused)
836 {
837 #ifdef ARM64
838 	/*
839 	 * If we're from user mode then thr->regs.sp is the saved user
840 	 * stack pointer and thr->kern_sp holds the last kernel stack
841 	 * pointer. But if we're from kernel mode then thr->kern_sp isn't
842 	 * up to date so we need to read from thr->regs.sp instead.
843 	 */
844 	vaddr_t sp = is_from_user(cpsr) ?  thr->kern_sp : thr->regs.sp;
845 #else
846 	vaddr_t sp = thr->regs.svc_sp;
847 #endif
848 	vaddr_t base = thr->stack_va_end - STACK_THREAD_SIZE;
849 	size_t len = sp - base;
850 
851 	tee_pager_release_phys((void *)base, len);
852 }
853 #else
854 static void release_unused_kernel_stack(struct thread_ctx *thr __unused,
855 					uint32_t cpsr __unused)
856 {
857 }
858 #endif
859 
860 int thread_state_suspend(uint32_t flags, uint32_t cpsr, vaddr_t pc)
861 {
862 	struct thread_core_local *l = thread_get_core_local();
863 	int ct = l->curr_thread;
864 
865 	assert(ct != -1);
866 
867 	if (core_mmu_user_mapping_is_active())
868 		ftrace_suspend();
869 
870 	thread_check_canaries();
871 
872 	release_unused_kernel_stack(threads + ct, cpsr);
873 
874 	if (is_from_user(cpsr)) {
875 		thread_user_save_vfp();
876 		tee_ta_update_session_utime_suspend();
877 		tee_ta_gprof_sample_pc(pc);
878 	}
879 	thread_lazy_restore_ns_vfp();
880 
881 	thread_lock_global();
882 
883 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
884 	threads[ct].flags |= flags;
885 	threads[ct].regs.cpsr = cpsr;
886 	threads[ct].regs.pc = pc;
887 	threads[ct].state = THREAD_STATE_SUSPENDED;
888 
889 	threads[ct].have_user_map = core_mmu_user_mapping_is_active();
890 	if (threads[ct].have_user_map) {
891 		if (threads[ct].flags & THREAD_FLAGS_EXIT_ON_FOREIGN_INTR)
892 			tee_ta_ftrace_update_times_suspend();
893 		core_mmu_get_user_map(&threads[ct].user_map);
894 		core_mmu_set_user_map(NULL);
895 	}
896 
897 	l->curr_thread = -1;
898 
899 #ifdef CFG_VIRTUALIZATION
900 	virt_unset_guest();
901 #endif
902 
903 	thread_unlock_global();
904 
905 	return ct;
906 }
907 
908 #ifdef ARM32
909 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
910 {
911 	l->tmp_stack_va_end = sp;
912 	thread_set_irq_sp(sp);
913 	thread_set_fiq_sp(sp);
914 }
915 
916 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
917 {
918 	l->abt_stack_va_end = sp;
919 	thread_set_abt_sp((vaddr_t)l);
920 	thread_set_und_sp((vaddr_t)l);
921 }
922 #endif /*ARM32*/
923 
924 #ifdef ARM64
925 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
926 {
927 	/*
928 	 * We're already using the tmp stack when this function is called
929 	 * so there's no need to assign it to any stack pointer. However,
930 	 * we'll need to restore it at different times so store it here.
931 	 */
932 	l->tmp_stack_va_end = sp;
933 }
934 
935 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
936 {
937 	l->abt_stack_va_end = sp;
938 }
939 #endif /*ARM64*/
940 
941 bool thread_init_stack(uint32_t thread_id, vaddr_t sp)
942 {
943 	if (thread_id >= CFG_NUM_THREADS)
944 		return false;
945 	threads[thread_id].stack_va_end = sp;
946 	return true;
947 }
948 
949 short int thread_get_id_may_fail(void)
950 {
951 	/*
952 	 * thread_get_core_local() requires foreign interrupts to be disabled
953 	 */
954 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
955 	struct thread_core_local *l = thread_get_core_local();
956 	short int ct = l->curr_thread;
957 
958 	thread_unmask_exceptions(exceptions);
959 	return ct;
960 }
961 
962 short int thread_get_id(void)
963 {
964 	short int ct = thread_get_id_may_fail();
965 
966 	/* Thread ID has to fit in a short int */
967 	COMPILE_TIME_ASSERT(CFG_NUM_THREADS <= SHRT_MAX);
968 	assert(ct >= 0 && ct < CFG_NUM_THREADS);
969 	return ct;
970 }
971 
972 #ifdef CFG_WITH_PAGER
973 static void init_thread_stacks(void)
974 {
975 	size_t n = 0;
976 
977 	/*
978 	 * Allocate virtual memory for thread stacks.
979 	 */
980 	for (n = 0; n < CFG_NUM_THREADS; n++) {
981 		tee_mm_entry_t *mm = NULL;
982 		vaddr_t sp = 0;
983 		size_t num_pages = 0;
984 		struct fobj *fobj = NULL;
985 
986 		/* Find vmem for thread stack and its protection gap */
987 		mm = tee_mm_alloc(&tee_mm_vcore,
988 				  SMALL_PAGE_SIZE + STACK_THREAD_SIZE);
989 		assert(mm);
990 
991 		/* Claim eventual physical page */
992 		tee_pager_add_pages(tee_mm_get_smem(mm), tee_mm_get_size(mm),
993 				    true);
994 
995 		num_pages = tee_mm_get_bytes(mm) / SMALL_PAGE_SIZE - 1;
996 		fobj = fobj_locked_paged_alloc(num_pages);
997 
998 		/* Add the area to the pager */
999 		tee_pager_add_core_area(tee_mm_get_smem(mm) + SMALL_PAGE_SIZE,
1000 					PAGER_AREA_TYPE_LOCK, fobj);
1001 		fobj_put(fobj);
1002 
1003 		/* init effective stack */
1004 		sp = tee_mm_get_smem(mm) + tee_mm_get_bytes(mm);
1005 		asan_tag_access((void *)tee_mm_get_smem(mm), (void *)sp);
1006 		if (!thread_init_stack(n, sp))
1007 			panic("init stack failed");
1008 	}
1009 }
1010 #else
1011 static void init_thread_stacks(void)
1012 {
1013 	size_t n;
1014 
1015 	/* Assign the thread stacks */
1016 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1017 		if (!thread_init_stack(n, GET_STACK_BOTTOM(stack_thread, n)))
1018 			panic("thread_init_stack failed");
1019 	}
1020 }
1021 #endif /*CFG_WITH_PAGER*/
1022 
1023 static void init_user_kcode(void)
1024 {
1025 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
1026 	vaddr_t v = (vaddr_t)thread_excp_vect;
1027 	vaddr_t ve = (vaddr_t)thread_excp_vect_end;
1028 
1029 	thread_user_kcode_va = ROUNDDOWN(v, CORE_MMU_USER_CODE_SIZE);
1030 	ve = ROUNDUP(ve, CORE_MMU_USER_CODE_SIZE);
1031 	thread_user_kcode_size = ve - thread_user_kcode_va;
1032 
1033 	core_mmu_get_user_va_range(&v, NULL);
1034 	thread_user_kcode_offset = thread_user_kcode_va - v;
1035 
1036 #if defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
1037 	/*
1038 	 * When transitioning to EL0 subtract SP with this much to point to
1039 	 * this special kdata page instead. SP is restored by add this much
1040 	 * while transitioning back to EL1.
1041 	 */
1042 	v += thread_user_kcode_size;
1043 	thread_user_kdata_sp_offset = (vaddr_t)thread_core_local - v;
1044 #endif
1045 #endif /*CFG_CORE_UNMAP_CORE_AT_EL0*/
1046 }
1047 
1048 void thread_init_threads(void)
1049 {
1050 	size_t n = 0;
1051 
1052 	init_thread_stacks();
1053 	print_stack_limits();
1054 	pgt_init();
1055 
1056 	mutex_lockdep_init();
1057 
1058 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1059 		TAILQ_INIT(&threads[n].tsd.sess_stack);
1060 		SLIST_INIT(&threads[n].tsd.pgt_cache);
1061 	}
1062 }
1063 
1064 void __nostackcheck thread_init_thread_core_local(void)
1065 {
1066 	size_t n = 0;
1067 	struct thread_core_local *tcl = thread_core_local;
1068 
1069 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++) {
1070 		tcl[n].curr_thread = -1;
1071 		tcl[n].flags = THREAD_CLF_TMP;
1072 	}
1073 
1074 	tcl[0].tmp_stack_va_end = GET_STACK_BOTTOM(stack_tmp, 0);
1075 }
1076 
1077 void thread_init_primary(void)
1078 {
1079 	/* Initialize canaries around the stacks */
1080 	init_canaries();
1081 
1082 	init_user_kcode();
1083 }
1084 
1085 static void init_sec_mon_stack(size_t pos __maybe_unused)
1086 {
1087 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
1088 	/* Initialize secure monitor */
1089 	sm_init(GET_STACK_BOTTOM(stack_tmp, pos));
1090 #endif
1091 }
1092 
1093 static uint32_t __maybe_unused get_midr_implementer(uint32_t midr)
1094 {
1095 	return (midr >> MIDR_IMPLEMENTER_SHIFT) & MIDR_IMPLEMENTER_MASK;
1096 }
1097 
1098 static uint32_t __maybe_unused get_midr_primary_part(uint32_t midr)
1099 {
1100 	return (midr >> MIDR_PRIMARY_PART_NUM_SHIFT) &
1101 	       MIDR_PRIMARY_PART_NUM_MASK;
1102 }
1103 
1104 #ifdef ARM64
1105 static bool probe_workaround_available(void)
1106 {
1107 	int32_t r;
1108 
1109 	r = thread_smc(SMCCC_VERSION, 0, 0, 0);
1110 	if (r < 0)
1111 		return false;
1112 	if (r < 0x10001)	/* compare with version 1.1 */
1113 		return false;
1114 
1115 	/* Version >= 1.1, so SMCCC_ARCH_FEATURES is available */
1116 	r = thread_smc(SMCCC_ARCH_FEATURES, SMCCC_ARCH_WORKAROUND_1, 0, 0);
1117 	return r >= 0;
1118 }
1119 
1120 static vaddr_t __maybe_unused select_vector(vaddr_t a)
1121 {
1122 	if (probe_workaround_available()) {
1123 		DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") available",
1124 		     SMCCC_ARCH_WORKAROUND_1);
1125 		DMSG("SMC Workaround for CVE-2017-5715 used");
1126 		return a;
1127 	}
1128 
1129 	DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") unavailable",
1130 	     SMCCC_ARCH_WORKAROUND_1);
1131 	DMSG("SMC Workaround for CVE-2017-5715 not needed (if ARM-TF is up to date)");
1132 	return (vaddr_t)thread_excp_vect;
1133 }
1134 #else
1135 static vaddr_t __maybe_unused select_vector(vaddr_t a)
1136 {
1137 	return a;
1138 }
1139 #endif
1140 
1141 static vaddr_t get_excp_vect(void)
1142 {
1143 #ifdef CFG_CORE_WORKAROUND_SPECTRE_BP_SEC
1144 	uint32_t midr = read_midr();
1145 
1146 	if (get_midr_implementer(midr) != MIDR_IMPLEMENTER_ARM)
1147 		return (vaddr_t)thread_excp_vect;
1148 
1149 	switch (get_midr_primary_part(midr)) {
1150 #ifdef ARM32
1151 	case CORTEX_A8_PART_NUM:
1152 	case CORTEX_A9_PART_NUM:
1153 	case CORTEX_A17_PART_NUM:
1154 #endif
1155 	case CORTEX_A57_PART_NUM:
1156 	case CORTEX_A72_PART_NUM:
1157 	case CORTEX_A73_PART_NUM:
1158 	case CORTEX_A75_PART_NUM:
1159 		return select_vector((vaddr_t)thread_excp_vect_workaround);
1160 #ifdef ARM32
1161 	case CORTEX_A15_PART_NUM:
1162 		return select_vector((vaddr_t)thread_excp_vect_workaround_a15);
1163 #endif
1164 	default:
1165 		return (vaddr_t)thread_excp_vect;
1166 	}
1167 #endif /*CFG_CORE_WORKAROUND_SPECTRE_BP_SEC*/
1168 
1169 	return (vaddr_t)thread_excp_vect;
1170 }
1171 
1172 void thread_init_per_cpu(void)
1173 {
1174 	size_t pos = get_core_pos();
1175 	struct thread_core_local *l = thread_get_core_local();
1176 
1177 	init_sec_mon_stack(pos);
1178 
1179 	set_tmp_stack(l, GET_STACK_BOTTOM(stack_tmp, pos) - STACK_TMP_OFFS);
1180 	set_abt_stack(l, GET_STACK_BOTTOM(stack_abt, pos));
1181 
1182 	thread_init_vbar(get_excp_vect());
1183 
1184 #ifdef CFG_FTRACE_SUPPORT
1185 	/*
1186 	 * Enable accesses to frequency register and physical counter
1187 	 * register in EL0/PL0 required for timestamping during
1188 	 * function tracing.
1189 	 */
1190 	write_cntkctl(read_cntkctl() | CNTKCTL_PL0PCTEN);
1191 #endif
1192 }
1193 
1194 struct thread_specific_data *thread_get_tsd(void)
1195 {
1196 	return &threads[thread_get_id()].tsd;
1197 }
1198 
1199 struct thread_ctx_regs * __nostackcheck thread_get_ctx_regs(void)
1200 {
1201 	struct thread_core_local *l = thread_get_core_local();
1202 
1203 	assert(l->curr_thread != -1);
1204 	return &threads[l->curr_thread].regs;
1205 }
1206 
1207 void thread_set_foreign_intr(bool enable)
1208 {
1209 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1210 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1211 	struct thread_core_local *l;
1212 
1213 	l = thread_get_core_local();
1214 
1215 	assert(l->curr_thread != -1);
1216 
1217 	if (enable) {
1218 		threads[l->curr_thread].flags |=
1219 					THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1220 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1221 	} else {
1222 		/*
1223 		 * No need to disable foreign interrupts here since they're
1224 		 * already disabled above.
1225 		 */
1226 		threads[l->curr_thread].flags &=
1227 					~THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1228 	}
1229 }
1230 
1231 void thread_restore_foreign_intr(void)
1232 {
1233 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1234 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1235 	struct thread_core_local *l;
1236 
1237 	l = thread_get_core_local();
1238 
1239 	assert(l->curr_thread != -1);
1240 
1241 	if (threads[l->curr_thread].flags & THREAD_FLAGS_FOREIGN_INTR_ENABLE)
1242 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1243 }
1244 
1245 #ifdef CFG_WITH_VFP
1246 uint32_t thread_kernel_enable_vfp(void)
1247 {
1248 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1249 	struct thread_ctx *thr = threads + thread_get_id();
1250 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1251 
1252 	assert(!vfp_is_enabled());
1253 
1254 	if (!thr->vfp_state.ns_saved) {
1255 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1256 					  true /*force_save*/);
1257 		thr->vfp_state.ns_saved = true;
1258 	} else if (thr->vfp_state.sec_lazy_saved &&
1259 		   !thr->vfp_state.sec_saved) {
1260 		/*
1261 		 * This happens when we're handling an abort while the
1262 		 * thread was using the VFP state.
1263 		 */
1264 		vfp_lazy_save_state_final(&thr->vfp_state.sec,
1265 					  false /*!force_save*/);
1266 		thr->vfp_state.sec_saved = true;
1267 	} else if (tuv && tuv->lazy_saved && !tuv->saved) {
1268 		/*
1269 		 * This can happen either during syscall or abort
1270 		 * processing (while processing a syscall).
1271 		 */
1272 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
1273 		tuv->saved = true;
1274 	}
1275 
1276 	vfp_enable();
1277 	return exceptions;
1278 }
1279 
1280 void thread_kernel_disable_vfp(uint32_t state)
1281 {
1282 	uint32_t exceptions;
1283 
1284 	assert(vfp_is_enabled());
1285 
1286 	vfp_disable();
1287 	exceptions = thread_get_exceptions();
1288 	assert(exceptions & THREAD_EXCP_FOREIGN_INTR);
1289 	exceptions &= ~THREAD_EXCP_FOREIGN_INTR;
1290 	exceptions |= state & THREAD_EXCP_FOREIGN_INTR;
1291 	thread_set_exceptions(exceptions);
1292 }
1293 
1294 void thread_kernel_save_vfp(void)
1295 {
1296 	struct thread_ctx *thr = threads + thread_get_id();
1297 
1298 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1299 	if (vfp_is_enabled()) {
1300 		vfp_lazy_save_state_init(&thr->vfp_state.sec);
1301 		thr->vfp_state.sec_lazy_saved = true;
1302 	}
1303 }
1304 
1305 void thread_kernel_restore_vfp(void)
1306 {
1307 	struct thread_ctx *thr = threads + thread_get_id();
1308 
1309 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1310 	assert(!vfp_is_enabled());
1311 	if (thr->vfp_state.sec_lazy_saved) {
1312 		vfp_lazy_restore_state(&thr->vfp_state.sec,
1313 				       thr->vfp_state.sec_saved);
1314 		thr->vfp_state.sec_saved = false;
1315 		thr->vfp_state.sec_lazy_saved = false;
1316 	}
1317 }
1318 
1319 void thread_user_enable_vfp(struct thread_user_vfp_state *uvfp)
1320 {
1321 	struct thread_ctx *thr = threads + thread_get_id();
1322 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1323 
1324 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1325 	assert(!vfp_is_enabled());
1326 
1327 	if (!thr->vfp_state.ns_saved) {
1328 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1329 					  true /*force_save*/);
1330 		thr->vfp_state.ns_saved = true;
1331 	} else if (tuv && uvfp != tuv) {
1332 		if (tuv->lazy_saved && !tuv->saved) {
1333 			vfp_lazy_save_state_final(&tuv->vfp,
1334 						  false /*!force_save*/);
1335 			tuv->saved = true;
1336 		}
1337 	}
1338 
1339 	if (uvfp->lazy_saved)
1340 		vfp_lazy_restore_state(&uvfp->vfp, uvfp->saved);
1341 	uvfp->lazy_saved = false;
1342 	uvfp->saved = false;
1343 
1344 	thr->vfp_state.uvfp = uvfp;
1345 	vfp_enable();
1346 }
1347 
1348 void thread_user_save_vfp(void)
1349 {
1350 	struct thread_ctx *thr = threads + thread_get_id();
1351 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1352 
1353 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1354 	if (!vfp_is_enabled())
1355 		return;
1356 
1357 	assert(tuv && !tuv->lazy_saved && !tuv->saved);
1358 	vfp_lazy_save_state_init(&tuv->vfp);
1359 	tuv->lazy_saved = true;
1360 }
1361 
1362 void thread_user_clear_vfp(struct thread_user_vfp_state *uvfp)
1363 {
1364 	struct thread_ctx *thr = threads + thread_get_id();
1365 
1366 	if (uvfp == thr->vfp_state.uvfp)
1367 		thr->vfp_state.uvfp = NULL;
1368 	uvfp->lazy_saved = false;
1369 	uvfp->saved = false;
1370 }
1371 #endif /*CFG_WITH_VFP*/
1372 
1373 #ifdef ARM32
1374 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1375 {
1376 	uint32_t s;
1377 
1378 	if (!is_32bit)
1379 		return false;
1380 
1381 	s = read_cpsr();
1382 	s &= ~(CPSR_MODE_MASK | CPSR_T | CPSR_IT_MASK1 | CPSR_IT_MASK2);
1383 	s |= CPSR_MODE_USR;
1384 	if (entry_func & 1)
1385 		s |= CPSR_T;
1386 	*spsr = s;
1387 	return true;
1388 }
1389 #endif
1390 
1391 #ifdef ARM64
1392 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1393 {
1394 	uint32_t s;
1395 
1396 	if (is_32bit) {
1397 		s = read_daif() & (SPSR_32_AIF_MASK << SPSR_32_AIF_SHIFT);
1398 		s |= SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT;
1399 		s |= (entry_func & SPSR_32_T_MASK) << SPSR_32_T_SHIFT;
1400 	} else {
1401 		s = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
1402 	}
1403 
1404 	*spsr = s;
1405 	return true;
1406 }
1407 #endif
1408 
1409 static void set_ctx_regs(struct thread_ctx_regs *regs, unsigned long a0,
1410 			 unsigned long a1, unsigned long a2, unsigned long a3,
1411 			 unsigned long user_sp, unsigned long entry_func,
1412 			 uint32_t spsr)
1413 {
1414 	/*
1415 	 * First clear all registers to avoid leaking information from
1416 	 * other TAs or even the Core itself.
1417 	 */
1418 	*regs = (struct thread_ctx_regs){ };
1419 #ifdef ARM32
1420 	regs->r0 = a0;
1421 	regs->r1 = a1;
1422 	regs->r2 = a2;
1423 	regs->r3 = a3;
1424 	regs->usr_sp = user_sp;
1425 	regs->pc = entry_func;
1426 	regs->cpsr = spsr;
1427 #endif
1428 #ifdef ARM64
1429 	regs->x[0] = a0;
1430 	regs->x[1] = a1;
1431 	regs->x[2] = a2;
1432 	regs->x[3] = a3;
1433 	regs->sp = user_sp;
1434 	regs->pc = entry_func;
1435 	regs->cpsr = spsr;
1436 	regs->x[13] = user_sp;	/* Used when running TA in Aarch32 */
1437 	regs->sp = user_sp;	/* Used when running TA in Aarch64 */
1438 	/* Set frame pointer (user stack can't be unwound past this point) */
1439 	regs->x[29] = 0;
1440 #endif
1441 }
1442 
1443 uint32_t thread_enter_user_mode(unsigned long a0, unsigned long a1,
1444 		unsigned long a2, unsigned long a3, unsigned long user_sp,
1445 		unsigned long entry_func, bool is_32bit,
1446 		uint32_t *exit_status0, uint32_t *exit_status1)
1447 {
1448 	uint32_t spsr = 0;
1449 	uint32_t exceptions = 0;
1450 	uint32_t rc = 0;
1451 	struct thread_ctx_regs *regs = NULL;
1452 
1453 	tee_ta_update_session_utime_resume();
1454 
1455 	/* Derive SPSR from current CPSR/PSTATE readout. */
1456 	if (!get_spsr(is_32bit, entry_func, &spsr)) {
1457 		*exit_status0 = 1; /* panic */
1458 		*exit_status1 = 0xbadbadba;
1459 		return 0;
1460 	}
1461 
1462 	exceptions = thread_mask_exceptions(THREAD_EXCP_ALL);
1463 	/*
1464 	 * We're using the per thread location of saved context registers
1465 	 * for temporary storage. Now that exceptions are masked they will
1466 	 * not be used for any thing else until they are eventually
1467 	 * unmasked when user mode has been entered.
1468 	 */
1469 	regs = thread_get_ctx_regs();
1470 	set_ctx_regs(regs, a0, a1, a2, a3, user_sp, entry_func, spsr);
1471 	rc = __thread_enter_user_mode(regs, exit_status0, exit_status1);
1472 	thread_unmask_exceptions(exceptions);
1473 	return rc;
1474 }
1475 
1476 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
1477 void thread_get_user_kcode(struct mobj **mobj, size_t *offset,
1478 			   vaddr_t *va, size_t *sz)
1479 {
1480 	core_mmu_get_user_va_range(va, NULL);
1481 	*mobj = mobj_tee_ram;
1482 	*offset = thread_user_kcode_va - VCORE_START_VA;
1483 	*sz = thread_user_kcode_size;
1484 }
1485 #endif
1486 
1487 #if defined(CFG_CORE_UNMAP_CORE_AT_EL0) && \
1488 	defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
1489 void thread_get_user_kdata(struct mobj **mobj, size_t *offset,
1490 			   vaddr_t *va, size_t *sz)
1491 {
1492 	vaddr_t v;
1493 
1494 	core_mmu_get_user_va_range(&v, NULL);
1495 	*va = v + thread_user_kcode_size;
1496 	*mobj = mobj_tee_ram;
1497 	*offset = (vaddr_t)thread_user_kdata_page - VCORE_START_VA;
1498 	*sz = sizeof(thread_user_kdata_page);
1499 }
1500 #endif
1501 
1502 static void setup_unwind_user_mode(struct thread_svc_regs *regs)
1503 {
1504 #ifdef ARM32
1505 	regs->lr = (uintptr_t)thread_unwind_user_mode;
1506 	regs->spsr = read_cpsr();
1507 #endif
1508 #ifdef ARM64
1509 	regs->elr = (uintptr_t)thread_unwind_user_mode;
1510 	regs->spsr = SPSR_64(SPSR_64_MODE_EL1, SPSR_64_MODE_SP_EL0, 0);
1511 	regs->spsr |= read_daif();
1512 	/*
1513 	 * Regs is the value of stack pointer before calling the SVC
1514 	 * handler.  By the addition matches for the reserved space at the
1515 	 * beginning of el0_sync_svc(). This prepares the stack when
1516 	 * returning to thread_unwind_user_mode instead of a normal
1517 	 * exception return.
1518 	 */
1519 	regs->sp_el0 = (uint64_t)(regs + 1);
1520 #endif
1521 }
1522 
1523 /*
1524  * Note: this function is weak just to make it possible to exclude it from
1525  * the unpaged area.
1526  */
1527 void __weak thread_svc_handler(struct thread_svc_regs *regs)
1528 {
1529 	struct tee_ta_session *sess = NULL;
1530 	uint32_t state = 0;
1531 
1532 	/* Enable native interrupts */
1533 	state = thread_get_exceptions();
1534 	thread_unmask_exceptions(state & ~THREAD_EXCP_NATIVE_INTR);
1535 
1536 	thread_user_save_vfp();
1537 
1538 	/* TA has just entered kernel mode */
1539 	tee_ta_update_session_utime_suspend();
1540 
1541 	/* Restore foreign interrupts which are disabled on exception entry */
1542 	thread_restore_foreign_intr();
1543 
1544 	tee_ta_get_current_session(&sess);
1545 	assert(sess && sess->ctx->ops && sess->ctx->ops->handle_svc);
1546 	if (sess->ctx->ops->handle_svc(regs)) {
1547 		/* We're about to switch back to user mode */
1548 		tee_ta_update_session_utime_resume();
1549 	} else {
1550 		/* We're returning from __thread_enter_user_mode() */
1551 		setup_unwind_user_mode(regs);
1552 	}
1553 }
1554 
1555 static struct mobj *alloc_shm(enum thread_shm_type shm_type, size_t size)
1556 {
1557 	switch (shm_type) {
1558 	case THREAD_SHM_TYPE_APPLICATION:
1559 		return thread_rpc_alloc_payload(size);
1560 	case THREAD_SHM_TYPE_KERNEL_PRIVATE:
1561 		return thread_rpc_alloc_kernel_payload(size);
1562 	case THREAD_SHM_TYPE_GLOBAL:
1563 		return thread_rpc_alloc_global_payload(size);
1564 	default:
1565 		return NULL;
1566 	}
1567 }
1568 
1569 static void clear_shm_cache_entry(struct thread_shm_cache_entry *ce)
1570 {
1571 	if (ce->mobj) {
1572 		switch (ce->type) {
1573 		case THREAD_SHM_TYPE_APPLICATION:
1574 			thread_rpc_free_payload(ce->mobj);
1575 			break;
1576 		case THREAD_SHM_TYPE_KERNEL_PRIVATE:
1577 			thread_rpc_free_kernel_payload(ce->mobj);
1578 			break;
1579 		case THREAD_SHM_TYPE_GLOBAL:
1580 			thread_rpc_free_global_payload(ce->mobj);
1581 			break;
1582 		default:
1583 			assert(0); /* "can't happen" */
1584 			break;
1585 		}
1586 	}
1587 	ce->mobj = NULL;
1588 	ce->size = 0;
1589 }
1590 
1591 static struct thread_shm_cache_entry *
1592 get_shm_cache_entry(enum thread_shm_cache_user user)
1593 {
1594 	struct thread_shm_cache *cache = &threads[thread_get_id()].shm_cache;
1595 	struct thread_shm_cache_entry *ce = NULL;
1596 
1597 	SLIST_FOREACH(ce, cache, link)
1598 		if (ce->user == user)
1599 			return ce;
1600 
1601 	ce = calloc(1, sizeof(*ce));
1602 	if (ce) {
1603 		ce->user = user;
1604 		SLIST_INSERT_HEAD(cache, ce, link);
1605 	}
1606 
1607 	return ce;
1608 }
1609 
1610 void *thread_rpc_shm_cache_alloc(enum thread_shm_cache_user user,
1611 				 enum thread_shm_type shm_type,
1612 				 size_t size, struct mobj **mobj)
1613 {
1614 	struct thread_shm_cache_entry *ce = NULL;
1615 	size_t sz = size;
1616 	paddr_t p = 0;
1617 	void *va = NULL;
1618 
1619 	if (!size)
1620 		return NULL;
1621 
1622 	ce = get_shm_cache_entry(user);
1623 	if (!ce)
1624 		return NULL;
1625 
1626 	/*
1627 	 * Always allocate in page chunks as normal world allocates payload
1628 	 * memory as complete pages.
1629 	 */
1630 	sz = ROUNDUP(size, SMALL_PAGE_SIZE);
1631 
1632 	if (ce->type != shm_type || sz > ce->size) {
1633 		clear_shm_cache_entry(ce);
1634 
1635 		ce->mobj = alloc_shm(shm_type, sz);
1636 		if (!ce->mobj)
1637 			return NULL;
1638 
1639 		if (mobj_get_pa(ce->mobj, 0, 0, &p))
1640 			goto err;
1641 
1642 		if (!ALIGNMENT_IS_OK(p, uint64_t))
1643 			goto err;
1644 
1645 		va = mobj_get_va(ce->mobj, 0);
1646 		if (!va)
1647 			goto err;
1648 
1649 		ce->size = sz;
1650 		ce->type = shm_type;
1651 	} else {
1652 		va = mobj_get_va(ce->mobj, 0);
1653 		if (!va)
1654 			goto err;
1655 	}
1656 	*mobj = ce->mobj;
1657 
1658 	return va;
1659 err:
1660 	clear_shm_cache_entry(ce);
1661 	return NULL;
1662 }
1663 
1664 void thread_rpc_shm_cache_clear(struct thread_shm_cache *cache)
1665 {
1666 	while (true) {
1667 		struct thread_shm_cache_entry *ce = SLIST_FIRST(cache);
1668 
1669 		if (!ce)
1670 			break;
1671 		SLIST_REMOVE_HEAD(cache, link);
1672 		clear_shm_cache_entry(ce);
1673 		free(ce);
1674 	}
1675 }
1676 
1677 #ifdef CFG_WITH_ARM_TRUSTED_FW
1678 /*
1679  * These five functions are __weak to allow platforms to override them if
1680  * needed.
1681  */
1682 unsigned long __weak thread_cpu_off_handler(unsigned long a0 __unused,
1683 					    unsigned long a1 __unused)
1684 {
1685 	return 0;
1686 }
1687 DECLARE_KEEP_PAGER(thread_cpu_off_handler);
1688 
1689 unsigned long __weak thread_cpu_suspend_handler(unsigned long a0 __unused,
1690 						unsigned long a1 __unused)
1691 {
1692 	return 0;
1693 }
1694 DECLARE_KEEP_PAGER(thread_cpu_suspend_handler);
1695 
1696 unsigned long __weak thread_cpu_resume_handler(unsigned long a0 __unused,
1697 					       unsigned long a1 __unused)
1698 {
1699 	return 0;
1700 }
1701 DECLARE_KEEP_PAGER(thread_cpu_resume_handler);
1702 
1703 unsigned long __weak thread_system_off_handler(unsigned long a0 __unused,
1704 					       unsigned long a1 __unused)
1705 {
1706 	return 0;
1707 }
1708 DECLARE_KEEP_PAGER(thread_system_off_handler);
1709 
1710 unsigned long __weak thread_system_reset_handler(unsigned long a0 __unused,
1711 						 unsigned long a1 __unused)
1712 {
1713 	return 0;
1714 }
1715 DECLARE_KEEP_PAGER(thread_system_reset_handler);
1716 #endif /*CFG_WITH_ARM_TRUSTED_FW*/
1717