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