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