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