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