xref: /optee_os/core/arch/arm/kernel/thread.c (revision 612791d01ca4d6aa33a97953e7716b74d3d653e9)
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/lockdep.h>
15 #include <kernel/misc.h>
16 #include <kernel/panic.h>
17 #include <kernel/spinlock.h>
18 #include <kernel/tee_ta_manager.h>
19 #include <kernel/thread_defs.h>
20 #include <kernel/thread.h>
21 #include <kernel/virtualization.h>
22 #include <mm/core_memprot.h>
23 #include <mm/mobj.h>
24 #include <mm/tee_mm.h>
25 #include <mm/tee_mmu.h>
26 #include <mm/tee_pager.h>
27 #include <smccc.h>
28 #include <sm/sm.h>
29 #include <trace.h>
30 #include <util.h>
31 
32 #include "thread_private.h"
33 
34 #ifdef CFG_WITH_ARM_TRUSTED_FW
35 #define STACK_TMP_OFFS		0
36 #else
37 #define STACK_TMP_OFFS		SM_STACK_TMP_RESERVE_SIZE
38 #endif
39 
40 
41 #ifdef ARM32
42 #ifdef CFG_CORE_SANITIZE_KADDRESS
43 #define STACK_TMP_SIZE		(3072 + STACK_TMP_OFFS)
44 #else
45 #define STACK_TMP_SIZE		(2048 + STACK_TMP_OFFS)
46 #endif
47 #define STACK_THREAD_SIZE	8192
48 
49 #ifdef CFG_CORE_SANITIZE_KADDRESS
50 #define STACK_ABT_SIZE		3072
51 #else
52 #define STACK_ABT_SIZE		2048
53 #endif
54 
55 #endif /*ARM32*/
56 
57 #ifdef ARM64
58 #define STACK_TMP_SIZE		(2048 + STACK_TMP_OFFS)
59 #define STACK_THREAD_SIZE	8192
60 
61 #if TRACE_LEVEL > 0
62 #define STACK_ABT_SIZE		3072
63 #else
64 #define STACK_ABT_SIZE		1024
65 #endif
66 #endif /*ARM64*/
67 
68 struct thread_ctx threads[CFG_NUM_THREADS];
69 
70 struct thread_core_local thread_core_local[CFG_TEE_CORE_NB_CORE] __nex_bss;
71 
72 #ifdef CFG_WITH_STACK_CANARIES
73 #ifdef ARM32
74 #define STACK_CANARY_SIZE	(4 * sizeof(uint32_t))
75 #endif
76 #ifdef ARM64
77 #define STACK_CANARY_SIZE	(8 * sizeof(uint32_t))
78 #endif
79 #define START_CANARY_VALUE	0xdededede
80 #define END_CANARY_VALUE	0xabababab
81 #define GET_START_CANARY(name, stack_num) name[stack_num][0]
82 #define GET_END_CANARY(name, stack_num) \
83 	name[stack_num][sizeof(name[stack_num]) / sizeof(uint32_t) - 1]
84 #else
85 #define STACK_CANARY_SIZE	0
86 #endif
87 
88 #define DECLARE_STACK(name, num_stacks, stack_size, linkage) \
89 linkage uint32_t name[num_stacks] \
90 		[ROUNDUP(stack_size + STACK_CANARY_SIZE, STACK_ALIGNMENT) / \
91 		sizeof(uint32_t)] \
92 		__attribute__((section(".nozi_stack." # name), \
93 			       aligned(STACK_ALIGNMENT)))
94 
95 #define STACK_SIZE(stack) (sizeof(stack) - STACK_CANARY_SIZE / 2)
96 
97 #define GET_STACK(stack) \
98 	((vaddr_t)(stack) + STACK_SIZE(stack))
99 
100 DECLARE_STACK(stack_tmp, CFG_TEE_CORE_NB_CORE, STACK_TMP_SIZE, static);
101 DECLARE_STACK(stack_abt, CFG_TEE_CORE_NB_CORE, STACK_ABT_SIZE, static);
102 #ifndef CFG_WITH_PAGER
103 DECLARE_STACK(stack_thread, CFG_NUM_THREADS, STACK_THREAD_SIZE, static);
104 #endif
105 
106 const void *stack_tmp_export = (uint8_t *)stack_tmp + sizeof(stack_tmp[0]) -
107 			       (STACK_TMP_OFFS + STACK_CANARY_SIZE / 2);
108 const uint32_t stack_tmp_stride = sizeof(stack_tmp[0]);
109 
110 /*
111  * These stack setup info are required by secondary boot cores before they
112  * each locally enable the pager (the mmu). Hence kept in pager sections.
113  */
114 KEEP_PAGER(stack_tmp_export);
115 KEEP_PAGER(stack_tmp_stride);
116 
117 thread_nintr_handler_t thread_nintr_handler_ptr __nex_bss;
118 thread_pm_handler_t thread_cpu_on_handler_ptr __nex_bss;
119 thread_pm_handler_t thread_cpu_off_handler_ptr __nex_bss;
120 thread_pm_handler_t thread_cpu_suspend_handler_ptr __nex_bss;
121 thread_pm_handler_t thread_cpu_resume_handler_ptr __nex_bss;
122 thread_pm_handler_t thread_system_off_handler_ptr __nex_bss;
123 thread_pm_handler_t thread_system_reset_handler_ptr __nex_bss;
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 struct thread_core_local *thread_get_core_local(void)
275 {
276 	uint32_t cpu_id = get_core_pos();
277 
278 	/*
279 	 * Foreign interrupts must be disabled before playing with core_local
280 	 * since we otherwise may be rescheduled to a different core in the
281 	 * middle of this function.
282 	 */
283 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
284 
285 	assert(cpu_id < CFG_TEE_CORE_NB_CORE);
286 	return &thread_core_local[cpu_id];
287 }
288 
289 static void thread_lazy_save_ns_vfp(void)
290 {
291 #ifdef CFG_WITH_VFP
292 	struct thread_ctx *thr = threads + thread_get_id();
293 
294 	thr->vfp_state.ns_saved = false;
295 	vfp_lazy_save_state_init(&thr->vfp_state.ns);
296 #endif /*CFG_WITH_VFP*/
297 }
298 
299 static void thread_lazy_restore_ns_vfp(void)
300 {
301 #ifdef CFG_WITH_VFP
302 	struct thread_ctx *thr = threads + thread_get_id();
303 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
304 
305 	assert(!thr->vfp_state.sec_lazy_saved && !thr->vfp_state.sec_saved);
306 
307 	if (tuv && tuv->lazy_saved && !tuv->saved) {
308 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
309 		tuv->saved = true;
310 	}
311 
312 	vfp_lazy_restore_state(&thr->vfp_state.ns, thr->vfp_state.ns_saved);
313 	thr->vfp_state.ns_saved = false;
314 #endif /*CFG_WITH_VFP*/
315 }
316 
317 #ifdef ARM32
318 static void init_regs(struct thread_ctx *thread, uint32_t a0, uint32_t a1,
319 		      uint32_t a2, uint32_t a3)
320 {
321 	thread->regs.pc = (uint32_t)thread_std_smc_entry;
322 
323 	/*
324 	 * Stdcalls starts in SVC mode with masked foreign interrupts, masked
325 	 * Asynchronous abort and unmasked native interrupts.
326 	 */
327 	thread->regs.cpsr = read_cpsr() & ARM32_CPSR_E;
328 	thread->regs.cpsr |= CPSR_MODE_SVC | CPSR_A |
329 			(THREAD_EXCP_FOREIGN_INTR << ARM32_CPSR_F_SHIFT);
330 	/* Enable thumb mode if it's a thumb instruction */
331 	if (thread->regs.pc & 1)
332 		thread->regs.cpsr |= CPSR_T;
333 	/* Reinitialize stack pointer */
334 	thread->regs.svc_sp = thread->stack_va_end;
335 
336 	/*
337 	 * Copy arguments into context. This will make the
338 	 * arguments appear in r0-r7 when thread is started.
339 	 */
340 	thread->regs.r0 = a0;
341 	thread->regs.r1 = a1;
342 	thread->regs.r2 = a2;
343 	thread->regs.r3 = a3;
344 	thread->regs.r4 = 0;
345 	thread->regs.r5 = 0;
346 	thread->regs.r6 = 0;
347 	thread->regs.r7 = 0;
348 }
349 #endif /*ARM32*/
350 
351 #ifdef ARM64
352 static void init_regs(struct thread_ctx *thread, uint32_t a0, uint32_t a1,
353 		      uint32_t a2, uint32_t a3)
354 {
355 	thread->regs.pc = (uint64_t)thread_std_smc_entry;
356 
357 	/*
358 	 * Stdcalls starts in SVC mode with masked foreign interrupts, masked
359 	 * Asynchronous abort and unmasked native interrupts.
360 	 */
361 	thread->regs.cpsr = SPSR_64(SPSR_64_MODE_EL1, SPSR_64_MODE_SP_EL0,
362 				THREAD_EXCP_FOREIGN_INTR | DAIFBIT_ABT);
363 	/* Reinitialize stack pointer */
364 	thread->regs.sp = thread->stack_va_end;
365 
366 	/*
367 	 * Copy arguments into context. This will make the
368 	 * arguments appear in x0-x7 when thread is started.
369 	 */
370 	thread->regs.x[0] = a0;
371 	thread->regs.x[1] = a1;
372 	thread->regs.x[2] = a2;
373 	thread->regs.x[3] = a3;
374 	thread->regs.x[4] = 0;
375 	thread->regs.x[5] = 0;
376 	thread->regs.x[6] = 0;
377 	thread->regs.x[7] = 0;
378 
379 	/* Set up frame pointer as per the Aarch64 AAPCS */
380 	thread->regs.x[29] = 0;
381 }
382 #endif /*ARM64*/
383 
384 void thread_init_boot_thread(void)
385 {
386 	struct thread_core_local *l = thread_get_core_local();
387 
388 	thread_init_threads();
389 
390 	l->curr_thread = 0;
391 	threads[0].state = THREAD_STATE_ACTIVE;
392 }
393 
394 void thread_clr_boot_thread(void)
395 {
396 	struct thread_core_local *l = thread_get_core_local();
397 
398 	assert(l->curr_thread >= 0 && l->curr_thread < CFG_NUM_THREADS);
399 	assert(threads[l->curr_thread].state == THREAD_STATE_ACTIVE);
400 	threads[l->curr_thread].state = THREAD_STATE_FREE;
401 	l->curr_thread = -1;
402 }
403 
404 void thread_alloc_and_run(uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3)
405 {
406 	size_t n;
407 	struct thread_core_local *l = thread_get_core_local();
408 	bool found_thread = false;
409 
410 	assert(l->curr_thread == -1);
411 
412 	thread_lock_global();
413 
414 	for (n = 0; n < CFG_NUM_THREADS; n++) {
415 		if (threads[n].state == THREAD_STATE_FREE) {
416 			threads[n].state = THREAD_STATE_ACTIVE;
417 			found_thread = true;
418 			break;
419 		}
420 	}
421 
422 	thread_unlock_global();
423 
424 	if (!found_thread)
425 		return;
426 
427 	l->curr_thread = n;
428 
429 	threads[n].flags = 0;
430 	init_regs(threads + n, a0, a1, a2, a3);
431 
432 	thread_lazy_save_ns_vfp();
433 	thread_resume(&threads[n].regs);
434 	/*NOTREACHED*/
435 	panic();
436 }
437 
438 #ifdef ARM32
439 static void copy_a0_to_a5(struct thread_ctx_regs *regs, uint32_t a0,
440 			  uint32_t a1, uint32_t a2, uint32_t a3, uint32_t a4,
441 			  uint32_t a5)
442 {
443 	/*
444 	 * Update returned values from RPC, values will appear in
445 	 * r0-r3 when thread is resumed.
446 	 */
447 	regs->r0 = a0;
448 	regs->r1 = a1;
449 	regs->r2 = a2;
450 	regs->r3 = a3;
451 	regs->r4 = a4;
452 	regs->r5 = a5;
453 }
454 #endif /*ARM32*/
455 
456 #ifdef ARM64
457 static void copy_a0_to_a5(struct thread_ctx_regs *regs, uint32_t a0,
458 			  uint32_t a1, uint32_t a2, uint32_t a3, uint32_t a4,
459 			  uint32_t a5)
460 {
461 	/*
462 	 * Update returned values from RPC, values will appear in
463 	 * x0-x3 when thread is resumed.
464 	 */
465 	regs->x[0] = a0;
466 	regs->x[1] = a1;
467 	regs->x[2] = a2;
468 	regs->x[3] = a3;
469 	regs->x[4] = a4;
470 	regs->x[5] = a5;
471 }
472 #endif /*ARM64*/
473 
474 #ifdef ARM32
475 static bool is_from_user(uint32_t cpsr)
476 {
477 	return (cpsr & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_USR;
478 }
479 #endif
480 
481 #ifdef ARM64
482 static bool is_from_user(uint32_t cpsr)
483 {
484 	if (cpsr & (SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT))
485 		return true;
486 	if (((cpsr >> SPSR_64_MODE_EL_SHIFT) & SPSR_64_MODE_EL_MASK) ==
487 	     SPSR_64_MODE_EL0)
488 		return true;
489 	return false;
490 }
491 #endif
492 
493 static bool is_user_mode(struct thread_ctx_regs *regs)
494 {
495 	return is_from_user((uint32_t)regs->cpsr);
496 }
497 
498 void thread_resume_from_rpc(uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3,
499 			    uint32_t a4, uint32_t a5)
500 {
501 	size_t n = a3; /* thread id */
502 	struct thread_core_local *l = thread_get_core_local();
503 	bool found_thread = false;
504 
505 	assert(l->curr_thread == -1);
506 
507 	thread_lock_global();
508 
509 	if (n < CFG_NUM_THREADS && threads[n].state == THREAD_STATE_SUSPENDED) {
510 		threads[n].state = THREAD_STATE_ACTIVE;
511 		found_thread = true;
512 	}
513 
514 	thread_unlock_global();
515 
516 	if (!found_thread)
517 		return;
518 
519 	l->curr_thread = n;
520 
521 	if (threads[n].have_user_map)
522 		core_mmu_set_user_map(&threads[n].user_map);
523 
524 	if (is_user_mode(&threads[n].regs))
525 		tee_ta_update_session_utime_resume();
526 
527 	/*
528 	 * Return from RPC to request service of a foreign interrupt must not
529 	 * get parameters from non-secure world.
530 	 */
531 	if (threads[n].flags & THREAD_FLAGS_COPY_ARGS_ON_RETURN) {
532 		copy_a0_to_a5(&threads[n].regs, a0, a1, a2, a3, a4, a5);
533 		threads[n].flags &= ~THREAD_FLAGS_COPY_ARGS_ON_RETURN;
534 	}
535 
536 	thread_lazy_save_ns_vfp();
537 	thread_resume(&threads[n].regs);
538 	/*NOTREACHED*/
539 	panic();
540 }
541 
542 void *thread_get_tmp_sp(void)
543 {
544 	struct thread_core_local *l = thread_get_core_local();
545 
546 	return (void *)l->tmp_stack_va_end;
547 }
548 
549 #ifdef ARM64
550 vaddr_t thread_get_saved_thread_sp(void)
551 {
552 	struct thread_core_local *l = thread_get_core_local();
553 	int ct = l->curr_thread;
554 
555 	assert(ct != -1);
556 	return threads[ct].kern_sp;
557 }
558 #endif /*ARM64*/
559 
560 vaddr_t thread_stack_start(void)
561 {
562 	struct thread_ctx *thr;
563 	int ct = thread_get_id_may_fail();
564 
565 	if (ct == -1)
566 		return 0;
567 
568 	thr = threads + ct;
569 	return thr->stack_va_end - STACK_THREAD_SIZE;
570 }
571 
572 size_t thread_stack_size(void)
573 {
574 	return STACK_THREAD_SIZE;
575 }
576 
577 bool thread_is_from_abort_mode(void)
578 {
579 	struct thread_core_local *l = thread_get_core_local();
580 
581 	return (l->flags >> THREAD_CLF_SAVED_SHIFT) & THREAD_CLF_ABORT;
582 }
583 
584 #ifdef ARM32
585 bool thread_is_in_normal_mode(void)
586 {
587 	return (read_cpsr() & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_SVC;
588 }
589 #endif
590 
591 #ifdef ARM64
592 bool thread_is_in_normal_mode(void)
593 {
594 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
595 	struct thread_core_local *l = thread_get_core_local();
596 	bool ret;
597 
598 	/* If any bit in l->flags is set we're handling some exception. */
599 	ret = !l->flags;
600 	thread_unmask_exceptions(exceptions);
601 
602 	return ret;
603 }
604 #endif
605 
606 void thread_state_free(void)
607 {
608 	struct thread_core_local *l = thread_get_core_local();
609 	int ct = l->curr_thread;
610 
611 	assert(ct != -1);
612 
613 	thread_lazy_restore_ns_vfp();
614 	tee_pager_release_phys(
615 		(void *)(threads[ct].stack_va_end - STACK_THREAD_SIZE),
616 		STACK_THREAD_SIZE);
617 
618 	thread_lock_global();
619 
620 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
621 	threads[ct].state = THREAD_STATE_FREE;
622 	threads[ct].flags = 0;
623 	l->curr_thread = -1;
624 
625 #ifdef CFG_VIRTUALIZATION
626 	virt_unset_guest();
627 #endif
628 	thread_unlock_global();
629 }
630 
631 #ifdef CFG_WITH_PAGER
632 static void release_unused_kernel_stack(struct thread_ctx *thr,
633 					uint32_t cpsr __maybe_unused)
634 {
635 #ifdef ARM64
636 	/*
637 	 * If we're from user mode then thr->regs.sp is the saved user
638 	 * stack pointer and thr->kern_sp holds the last kernel stack
639 	 * pointer. But if we're from kernel mode then thr->kern_sp isn't
640 	 * up to date so we need to read from thr->regs.sp instead.
641 	 */
642 	vaddr_t sp = is_from_user(cpsr) ?  thr->kern_sp : thr->regs.sp;
643 #else
644 	vaddr_t sp = thr->regs.svc_sp;
645 #endif
646 	vaddr_t base = thr->stack_va_end - STACK_THREAD_SIZE;
647 	size_t len = sp - base;
648 
649 	tee_pager_release_phys((void *)base, len);
650 }
651 #else
652 static void release_unused_kernel_stack(struct thread_ctx *thr __unused,
653 					uint32_t cpsr __unused)
654 {
655 }
656 #endif
657 
658 int thread_state_suspend(uint32_t flags, uint32_t cpsr, vaddr_t pc)
659 {
660 	struct thread_core_local *l = thread_get_core_local();
661 	int ct = l->curr_thread;
662 
663 	assert(ct != -1);
664 
665 	thread_check_canaries();
666 
667 	release_unused_kernel_stack(threads + ct, cpsr);
668 
669 	if (is_from_user(cpsr)) {
670 		thread_user_save_vfp();
671 		tee_ta_update_session_utime_suspend();
672 		tee_ta_gprof_sample_pc(pc);
673 	}
674 	thread_lazy_restore_ns_vfp();
675 
676 	thread_lock_global();
677 
678 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
679 	threads[ct].flags |= flags;
680 	threads[ct].regs.cpsr = cpsr;
681 	threads[ct].regs.pc = pc;
682 	threads[ct].state = THREAD_STATE_SUSPENDED;
683 
684 	threads[ct].have_user_map = core_mmu_user_mapping_is_active();
685 	if (threads[ct].have_user_map) {
686 		core_mmu_get_user_map(&threads[ct].user_map);
687 		core_mmu_set_user_map(NULL);
688 	}
689 
690 	l->curr_thread = -1;
691 
692 #ifdef CFG_VIRTUALIZATION
693 	virt_unset_guest();
694 #endif
695 
696 	thread_unlock_global();
697 
698 	return ct;
699 }
700 
701 #ifdef ARM32
702 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
703 {
704 	l->tmp_stack_va_end = sp;
705 	thread_set_irq_sp(sp);
706 	thread_set_fiq_sp(sp);
707 }
708 
709 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
710 {
711 	l->abt_stack_va_end = sp;
712 	thread_set_abt_sp((vaddr_t)l);
713 	thread_set_und_sp((vaddr_t)l);
714 }
715 #endif /*ARM32*/
716 
717 #ifdef ARM64
718 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
719 {
720 	/*
721 	 * We're already using the tmp stack when this function is called
722 	 * so there's no need to assign it to any stack pointer. However,
723 	 * we'll need to restore it at different times so store it here.
724 	 */
725 	l->tmp_stack_va_end = sp;
726 }
727 
728 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
729 {
730 	l->abt_stack_va_end = sp;
731 }
732 #endif /*ARM64*/
733 
734 bool thread_init_stack(uint32_t thread_id, vaddr_t sp)
735 {
736 	if (thread_id >= CFG_NUM_THREADS)
737 		return false;
738 	threads[thread_id].stack_va_end = sp;
739 	return true;
740 }
741 
742 int thread_get_id_may_fail(void)
743 {
744 	/*
745 	 * thread_get_core_local() requires foreign interrupts to be disabled
746 	 */
747 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
748 	struct thread_core_local *l = thread_get_core_local();
749 	int ct = l->curr_thread;
750 
751 	thread_unmask_exceptions(exceptions);
752 	return ct;
753 }
754 
755 int thread_get_id(void)
756 {
757 	int ct = thread_get_id_may_fail();
758 
759 	assert(ct >= 0 && ct < CFG_NUM_THREADS);
760 	return ct;
761 }
762 
763 static void init_handlers(const struct thread_handlers *handlers)
764 {
765 	thread_nintr_handler_ptr = handlers->nintr;
766 	thread_cpu_on_handler_ptr = handlers->cpu_on;
767 	thread_cpu_off_handler_ptr = handlers->cpu_off;
768 	thread_cpu_suspend_handler_ptr = handlers->cpu_suspend;
769 	thread_cpu_resume_handler_ptr = handlers->cpu_resume;
770 	thread_system_off_handler_ptr = handlers->system_off;
771 	thread_system_reset_handler_ptr = handlers->system_reset;
772 }
773 
774 #ifdef CFG_WITH_PAGER
775 static void init_thread_stacks(void)
776 {
777 	size_t n = 0;
778 
779 	/*
780 	 * Allocate virtual memory for thread stacks.
781 	 */
782 	for (n = 0; n < CFG_NUM_THREADS; n++) {
783 		tee_mm_entry_t *mm = NULL;
784 		vaddr_t sp = 0;
785 		size_t num_pages = 0;
786 		struct fobj *fobj = NULL;
787 
788 		/* Find vmem for thread stack and its protection gap */
789 		mm = tee_mm_alloc(&tee_mm_vcore,
790 				  SMALL_PAGE_SIZE + STACK_THREAD_SIZE);
791 		assert(mm);
792 
793 		/* Claim eventual physical page */
794 		tee_pager_add_pages(tee_mm_get_smem(mm), tee_mm_get_size(mm),
795 				    true);
796 
797 		num_pages = tee_mm_get_bytes(mm) / SMALL_PAGE_SIZE - 1;
798 		fobj = fobj_locked_paged_alloc(num_pages);
799 
800 		/* Add the area to the pager */
801 		tee_pager_add_core_area(tee_mm_get_smem(mm) + SMALL_PAGE_SIZE,
802 					PAGER_AREA_TYPE_LOCK, fobj);
803 		fobj_put(fobj);
804 
805 		/* init effective stack */
806 		sp = tee_mm_get_smem(mm) + tee_mm_get_bytes(mm);
807 		asan_tag_access((void *)tee_mm_get_smem(mm), (void *)sp);
808 		if (!thread_init_stack(n, sp))
809 			panic("init stack failed");
810 	}
811 }
812 #else
813 static void init_thread_stacks(void)
814 {
815 	size_t n;
816 
817 	/* Assign the thread stacks */
818 	for (n = 0; n < CFG_NUM_THREADS; n++) {
819 		if (!thread_init_stack(n, GET_STACK(stack_thread[n])))
820 			panic("thread_init_stack failed");
821 	}
822 }
823 #endif /*CFG_WITH_PAGER*/
824 
825 static void init_user_kcode(void)
826 {
827 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
828 	vaddr_t v = (vaddr_t)thread_excp_vect;
829 	vaddr_t ve = (vaddr_t)thread_excp_vect_end;
830 
831 	thread_user_kcode_va = ROUNDDOWN(v, CORE_MMU_USER_CODE_SIZE);
832 	ve = ROUNDUP(ve, CORE_MMU_USER_CODE_SIZE);
833 	thread_user_kcode_size = ve - thread_user_kcode_va;
834 
835 	core_mmu_get_user_va_range(&v, NULL);
836 	thread_user_kcode_offset = thread_user_kcode_va - v;
837 
838 #if defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
839 	/*
840 	 * When transitioning to EL0 subtract SP with this much to point to
841 	 * this special kdata page instead. SP is restored by add this much
842 	 * while transitioning back to EL1.
843 	 */
844 	v += thread_user_kcode_size;
845 	thread_user_kdata_sp_offset = (vaddr_t)thread_core_local - v;
846 #endif
847 #endif /*CFG_CORE_UNMAP_CORE_AT_EL0*/
848 }
849 
850 void thread_init_threads(void)
851 {
852 	size_t n;
853 
854 	init_thread_stacks();
855 	pgt_init();
856 
857 	mutex_lockdep_init();
858 
859 	for (n = 0; n < CFG_NUM_THREADS; n++) {
860 		TAILQ_INIT(&threads[n].tsd.sess_stack);
861 		SLIST_INIT(&threads[n].tsd.pgt_cache);
862 	}
863 
864 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++)
865 		thread_core_local[n].curr_thread = -1;
866 }
867 
868 void thread_init_primary(const struct thread_handlers *handlers)
869 {
870 	init_handlers(handlers);
871 
872 	/* Initialize canaries around the stacks */
873 	init_canaries();
874 
875 	init_user_kcode();
876 }
877 
878 static void init_sec_mon(size_t pos __maybe_unused)
879 {
880 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
881 	/* Initialize secure monitor */
882 	sm_init(GET_STACK(stack_tmp[pos]));
883 #endif
884 }
885 
886 static uint32_t __maybe_unused get_midr_implementer(uint32_t midr)
887 {
888 	return (midr >> MIDR_IMPLEMENTER_SHIFT) & MIDR_IMPLEMENTER_MASK;
889 }
890 
891 static uint32_t __maybe_unused get_midr_primary_part(uint32_t midr)
892 {
893 	return (midr >> MIDR_PRIMARY_PART_NUM_SHIFT) &
894 	       MIDR_PRIMARY_PART_NUM_MASK;
895 }
896 
897 #ifdef ARM64
898 static bool probe_workaround_available(void)
899 {
900 	int32_t r;
901 
902 	r = thread_smc(SMCCC_VERSION, 0, 0, 0);
903 	if (r < 0)
904 		return false;
905 	if (r < 0x10001)	/* compare with version 1.1 */
906 		return false;
907 
908 	/* Version >= 1.1, so SMCCC_ARCH_FEATURES is available */
909 	r = thread_smc(SMCCC_ARCH_FEATURES, SMCCC_ARCH_WORKAROUND_1, 0, 0);
910 	return r >= 0;
911 }
912 
913 static vaddr_t __maybe_unused select_vector(vaddr_t a)
914 {
915 	if (probe_workaround_available()) {
916 		DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") available",
917 		     SMCCC_ARCH_WORKAROUND_1);
918 		DMSG("SMC Workaround for CVE-2017-5715 used");
919 		return a;
920 	}
921 
922 	DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") unavailable",
923 	     SMCCC_ARCH_WORKAROUND_1);
924 	DMSG("SMC Workaround for CVE-2017-5715 not needed (if ARM-TF is up to date)");
925 	return (vaddr_t)thread_excp_vect;
926 }
927 #else
928 static vaddr_t __maybe_unused select_vector(vaddr_t a)
929 {
930 	return a;
931 }
932 #endif
933 
934 static vaddr_t get_excp_vect(void)
935 {
936 #ifdef CFG_CORE_WORKAROUND_SPECTRE_BP_SEC
937 	uint32_t midr = read_midr();
938 
939 	if (get_midr_implementer(midr) != MIDR_IMPLEMENTER_ARM)
940 		return (vaddr_t)thread_excp_vect;
941 
942 	switch (get_midr_primary_part(midr)) {
943 #ifdef ARM32
944 	case CORTEX_A8_PART_NUM:
945 	case CORTEX_A9_PART_NUM:
946 	case CORTEX_A17_PART_NUM:
947 #endif
948 	case CORTEX_A57_PART_NUM:
949 	case CORTEX_A72_PART_NUM:
950 	case CORTEX_A73_PART_NUM:
951 	case CORTEX_A75_PART_NUM:
952 		return select_vector((vaddr_t)thread_excp_vect_workaround);
953 #ifdef ARM32
954 	case CORTEX_A15_PART_NUM:
955 		return select_vector((vaddr_t)thread_excp_vect_workaround_a15);
956 #endif
957 	default:
958 		return (vaddr_t)thread_excp_vect;
959 	}
960 #endif /*CFG_CORE_WORKAROUND_SPECTRE_BP_SEC*/
961 
962 	return (vaddr_t)thread_excp_vect;
963 }
964 
965 void thread_init_per_cpu(void)
966 {
967 	size_t pos = get_core_pos();
968 	struct thread_core_local *l = thread_get_core_local();
969 
970 	init_sec_mon(pos);
971 
972 	set_tmp_stack(l, GET_STACK(stack_tmp[pos]) - STACK_TMP_OFFS);
973 	set_abt_stack(l, GET_STACK(stack_abt[pos]));
974 
975 	thread_init_vbar(get_excp_vect());
976 
977 #ifdef CFG_TA_FTRACE_SUPPORT
978 	/*
979 	 * Enable accesses to frequency register and physical counter
980 	 * register in EL0/PL0 required for timestamping during
981 	 * function tracing.
982 	 */
983 	write_cntkctl(read_cntkctl() | CNTKCTL_PL0PCTEN);
984 #endif
985 }
986 
987 struct thread_specific_data *thread_get_tsd(void)
988 {
989 	return &threads[thread_get_id()].tsd;
990 }
991 
992 struct thread_ctx_regs *thread_get_ctx_regs(void)
993 {
994 	struct thread_core_local *l = thread_get_core_local();
995 
996 	assert(l->curr_thread != -1);
997 	return &threads[l->curr_thread].regs;
998 }
999 
1000 void thread_set_foreign_intr(bool enable)
1001 {
1002 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1003 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1004 	struct thread_core_local *l;
1005 
1006 	l = thread_get_core_local();
1007 
1008 	assert(l->curr_thread != -1);
1009 
1010 	if (enable) {
1011 		threads[l->curr_thread].flags |=
1012 					THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1013 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1014 	} else {
1015 		/*
1016 		 * No need to disable foreign interrupts here since they're
1017 		 * already disabled above.
1018 		 */
1019 		threads[l->curr_thread].flags &=
1020 					~THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1021 	}
1022 }
1023 
1024 void thread_restore_foreign_intr(void)
1025 {
1026 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1027 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1028 	struct thread_core_local *l;
1029 
1030 	l = thread_get_core_local();
1031 
1032 	assert(l->curr_thread != -1);
1033 
1034 	if (threads[l->curr_thread].flags & THREAD_FLAGS_FOREIGN_INTR_ENABLE)
1035 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1036 }
1037 
1038 #ifdef CFG_WITH_VFP
1039 uint32_t thread_kernel_enable_vfp(void)
1040 {
1041 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1042 	struct thread_ctx *thr = threads + thread_get_id();
1043 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1044 
1045 	assert(!vfp_is_enabled());
1046 
1047 	if (!thr->vfp_state.ns_saved) {
1048 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1049 					  true /*force_save*/);
1050 		thr->vfp_state.ns_saved = true;
1051 	} else if (thr->vfp_state.sec_lazy_saved &&
1052 		   !thr->vfp_state.sec_saved) {
1053 		/*
1054 		 * This happens when we're handling an abort while the
1055 		 * thread was using the VFP state.
1056 		 */
1057 		vfp_lazy_save_state_final(&thr->vfp_state.sec,
1058 					  false /*!force_save*/);
1059 		thr->vfp_state.sec_saved = true;
1060 	} else if (tuv && tuv->lazy_saved && !tuv->saved) {
1061 		/*
1062 		 * This can happen either during syscall or abort
1063 		 * processing (while processing a syscall).
1064 		 */
1065 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
1066 		tuv->saved = true;
1067 	}
1068 
1069 	vfp_enable();
1070 	return exceptions;
1071 }
1072 
1073 void thread_kernel_disable_vfp(uint32_t state)
1074 {
1075 	uint32_t exceptions;
1076 
1077 	assert(vfp_is_enabled());
1078 
1079 	vfp_disable();
1080 	exceptions = thread_get_exceptions();
1081 	assert(exceptions & THREAD_EXCP_FOREIGN_INTR);
1082 	exceptions &= ~THREAD_EXCP_FOREIGN_INTR;
1083 	exceptions |= state & THREAD_EXCP_FOREIGN_INTR;
1084 	thread_set_exceptions(exceptions);
1085 }
1086 
1087 void thread_kernel_save_vfp(void)
1088 {
1089 	struct thread_ctx *thr = threads + thread_get_id();
1090 
1091 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1092 	if (vfp_is_enabled()) {
1093 		vfp_lazy_save_state_init(&thr->vfp_state.sec);
1094 		thr->vfp_state.sec_lazy_saved = true;
1095 	}
1096 }
1097 
1098 void thread_kernel_restore_vfp(void)
1099 {
1100 	struct thread_ctx *thr = threads + thread_get_id();
1101 
1102 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1103 	assert(!vfp_is_enabled());
1104 	if (thr->vfp_state.sec_lazy_saved) {
1105 		vfp_lazy_restore_state(&thr->vfp_state.sec,
1106 				       thr->vfp_state.sec_saved);
1107 		thr->vfp_state.sec_saved = false;
1108 		thr->vfp_state.sec_lazy_saved = false;
1109 	}
1110 }
1111 
1112 void thread_user_enable_vfp(struct thread_user_vfp_state *uvfp)
1113 {
1114 	struct thread_ctx *thr = threads + thread_get_id();
1115 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1116 
1117 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1118 	assert(!vfp_is_enabled());
1119 
1120 	if (!thr->vfp_state.ns_saved) {
1121 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1122 					  true /*force_save*/);
1123 		thr->vfp_state.ns_saved = true;
1124 	} else if (tuv && uvfp != tuv) {
1125 		if (tuv->lazy_saved && !tuv->saved) {
1126 			vfp_lazy_save_state_final(&tuv->vfp,
1127 						  false /*!force_save*/);
1128 			tuv->saved = true;
1129 		}
1130 	}
1131 
1132 	if (uvfp->lazy_saved)
1133 		vfp_lazy_restore_state(&uvfp->vfp, uvfp->saved);
1134 	uvfp->lazy_saved = false;
1135 	uvfp->saved = false;
1136 
1137 	thr->vfp_state.uvfp = uvfp;
1138 	vfp_enable();
1139 }
1140 
1141 void thread_user_save_vfp(void)
1142 {
1143 	struct thread_ctx *thr = threads + thread_get_id();
1144 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1145 
1146 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1147 	if (!vfp_is_enabled())
1148 		return;
1149 
1150 	assert(tuv && !tuv->lazy_saved && !tuv->saved);
1151 	vfp_lazy_save_state_init(&tuv->vfp);
1152 	tuv->lazy_saved = true;
1153 }
1154 
1155 void thread_user_clear_vfp(struct thread_user_vfp_state *uvfp)
1156 {
1157 	struct thread_ctx *thr = threads + thread_get_id();
1158 
1159 	if (uvfp == thr->vfp_state.uvfp)
1160 		thr->vfp_state.uvfp = NULL;
1161 	uvfp->lazy_saved = false;
1162 	uvfp->saved = false;
1163 }
1164 #endif /*CFG_WITH_VFP*/
1165 
1166 #ifdef ARM32
1167 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1168 {
1169 	uint32_t s;
1170 
1171 	if (!is_32bit)
1172 		return false;
1173 
1174 	s = read_spsr();
1175 	s &= ~(CPSR_MODE_MASK | CPSR_T | CPSR_IT_MASK1 | CPSR_IT_MASK2);
1176 	s |= CPSR_MODE_USR;
1177 	if (entry_func & 1)
1178 		s |= CPSR_T;
1179 	*spsr = s;
1180 	return true;
1181 }
1182 #endif
1183 
1184 #ifdef ARM64
1185 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1186 {
1187 	uint32_t s;
1188 
1189 	if (is_32bit) {
1190 		s = read_daif() & (SPSR_32_AIF_MASK << SPSR_32_AIF_SHIFT);
1191 		s |= SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT;
1192 		s |= (entry_func & SPSR_32_T_MASK) << SPSR_32_T_SHIFT;
1193 	} else {
1194 		s = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
1195 	}
1196 
1197 	*spsr = s;
1198 	return true;
1199 }
1200 #endif
1201 
1202 uint32_t thread_enter_user_mode(unsigned long a0, unsigned long a1,
1203 		unsigned long a2, unsigned long a3, unsigned long user_sp,
1204 		unsigned long entry_func, bool is_32bit,
1205 		uint32_t *exit_status0, uint32_t *exit_status1)
1206 {
1207 	uint32_t spsr;
1208 
1209 	tee_ta_update_session_utime_resume();
1210 
1211 	if (!get_spsr(is_32bit, entry_func, &spsr)) {
1212 		*exit_status0 = 1; /* panic */
1213 		*exit_status1 = 0xbadbadba;
1214 		return 0;
1215 	}
1216 	return __thread_enter_user_mode(a0, a1, a2, a3, user_sp, entry_func,
1217 					spsr, exit_status0, exit_status1);
1218 }
1219 
1220 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
1221 void thread_get_user_kcode(struct mobj **mobj, size_t *offset,
1222 			   vaddr_t *va, size_t *sz)
1223 {
1224 	core_mmu_get_user_va_range(va, NULL);
1225 	*mobj = mobj_tee_ram;
1226 	*offset = thread_user_kcode_va - TEE_RAM_START;
1227 	*sz = thread_user_kcode_size;
1228 }
1229 #endif
1230 
1231 #if defined(CFG_CORE_UNMAP_CORE_AT_EL0) && \
1232 	defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
1233 void thread_get_user_kdata(struct mobj **mobj, size_t *offset,
1234 			   vaddr_t *va, size_t *sz)
1235 {
1236 	vaddr_t v;
1237 
1238 	core_mmu_get_user_va_range(&v, NULL);
1239 	*va = v + thread_user_kcode_size;
1240 	*mobj = mobj_tee_ram;
1241 	*offset = (vaddr_t)thread_user_kdata_page - TEE_RAM_START;
1242 	*sz = sizeof(thread_user_kdata_page);
1243 }
1244 #endif
1245