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