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