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