xref: /optee_os/core/arch/arm/kernel/thread.c (revision dc57b1101a33ec9bf18ee3d2b88a0d8ff12d2ede)
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 
517 	if (is_user_mode(&threads[n].regs))
518 		tee_ta_update_session_utime_resume();
519 
520 	/*
521 	 * Return from RPC to request service of a foreign interrupt must not
522 	 * get parameters from non-secure world.
523 	 */
524 	if (threads[n].flags & THREAD_FLAGS_COPY_ARGS_ON_RETURN) {
525 		copy_a0_to_a3(&threads[n].regs, a0, a1, a2, a3);
526 		threads[n].flags &= ~THREAD_FLAGS_COPY_ARGS_ON_RETURN;
527 	}
528 
529 	thread_lazy_save_ns_vfp();
530 	thread_resume(&threads[n].regs);
531 	/*NOTREACHED*/
532 	panic();
533 }
534 
535 void *thread_get_tmp_sp(void)
536 {
537 	struct thread_core_local *l = thread_get_core_local();
538 
539 	return (void *)l->tmp_stack_va_end;
540 }
541 
542 #ifdef ARM64
543 vaddr_t thread_get_saved_thread_sp(void)
544 {
545 	struct thread_core_local *l = thread_get_core_local();
546 	int ct = l->curr_thread;
547 
548 	assert(ct != -1);
549 	return threads[ct].kern_sp;
550 }
551 #endif /*ARM64*/
552 
553 vaddr_t thread_stack_start(void)
554 {
555 	struct thread_ctx *thr;
556 	int ct = thread_get_id_may_fail();
557 
558 	if (ct == -1)
559 		return 0;
560 
561 	thr = threads + ct;
562 	return thr->stack_va_end - STACK_THREAD_SIZE;
563 }
564 
565 size_t thread_stack_size(void)
566 {
567 	return STACK_THREAD_SIZE;
568 }
569 
570 bool thread_is_from_abort_mode(void)
571 {
572 	struct thread_core_local *l = thread_get_core_local();
573 
574 	return (l->flags >> THREAD_CLF_SAVED_SHIFT) & THREAD_CLF_ABORT;
575 }
576 
577 #ifdef ARM32
578 bool thread_is_in_normal_mode(void)
579 {
580 	return (read_cpsr() & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_SVC;
581 }
582 #endif
583 
584 #ifdef ARM64
585 bool thread_is_in_normal_mode(void)
586 {
587 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
588 	struct thread_core_local *l = thread_get_core_local();
589 	bool ret;
590 
591 	/* If any bit in l->flags is set we're handling some exception. */
592 	ret = !l->flags;
593 	thread_unmask_exceptions(exceptions);
594 
595 	return ret;
596 }
597 #endif
598 
599 void thread_state_free(void)
600 {
601 	struct thread_core_local *l = thread_get_core_local();
602 	int ct = l->curr_thread;
603 
604 	assert(ct != -1);
605 
606 	thread_lazy_restore_ns_vfp();
607 	tee_pager_release_phys(
608 		(void *)(threads[ct].stack_va_end - STACK_THREAD_SIZE),
609 		STACK_THREAD_SIZE);
610 
611 	thread_lock_global();
612 
613 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
614 	threads[ct].state = THREAD_STATE_FREE;
615 	threads[ct].flags = 0;
616 	l->curr_thread = -1;
617 
618 #ifdef CFG_VIRTUALIZATION
619 	virt_unset_guest();
620 #endif
621 	thread_unlock_global();
622 }
623 
624 #ifdef CFG_WITH_PAGER
625 static void release_unused_kernel_stack(struct thread_ctx *thr,
626 					uint32_t cpsr __maybe_unused)
627 {
628 #ifdef ARM64
629 	/*
630 	 * If we're from user mode then thr->regs.sp is the saved user
631 	 * stack pointer and thr->kern_sp holds the last kernel stack
632 	 * pointer. But if we're from kernel mode then thr->kern_sp isn't
633 	 * up to date so we need to read from thr->regs.sp instead.
634 	 */
635 	vaddr_t sp = is_from_user(cpsr) ?  thr->kern_sp : thr->regs.sp;
636 #else
637 	vaddr_t sp = thr->regs.svc_sp;
638 #endif
639 	vaddr_t base = thr->stack_va_end - STACK_THREAD_SIZE;
640 	size_t len = sp - base;
641 
642 	tee_pager_release_phys((void *)base, len);
643 }
644 #else
645 static void release_unused_kernel_stack(struct thread_ctx *thr __unused,
646 					uint32_t cpsr __unused)
647 {
648 }
649 #endif
650 
651 int thread_state_suspend(uint32_t flags, uint32_t cpsr, vaddr_t pc)
652 {
653 	struct thread_core_local *l = thread_get_core_local();
654 	int ct = l->curr_thread;
655 
656 	assert(ct != -1);
657 
658 	thread_check_canaries();
659 
660 	release_unused_kernel_stack(threads + ct, cpsr);
661 
662 	if (is_from_user(cpsr)) {
663 		thread_user_save_vfp();
664 		tee_ta_update_session_utime_suspend();
665 		tee_ta_gprof_sample_pc(pc);
666 	}
667 	thread_lazy_restore_ns_vfp();
668 
669 	thread_lock_global();
670 
671 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
672 	threads[ct].flags |= flags;
673 	threads[ct].regs.cpsr = cpsr;
674 	threads[ct].regs.pc = pc;
675 	threads[ct].state = THREAD_STATE_SUSPENDED;
676 
677 	threads[ct].have_user_map = core_mmu_user_mapping_is_active();
678 	if (threads[ct].have_user_map) {
679 		core_mmu_get_user_map(&threads[ct].user_map);
680 		core_mmu_set_user_map(NULL);
681 	}
682 
683 	l->curr_thread = -1;
684 
685 #ifdef CFG_VIRTUALIZATION
686 	virt_unset_guest();
687 #endif
688 
689 	thread_unlock_global();
690 
691 	return ct;
692 }
693 
694 #ifdef ARM32
695 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
696 {
697 	l->tmp_stack_va_end = sp;
698 	thread_set_irq_sp(sp);
699 	thread_set_fiq_sp(sp);
700 }
701 
702 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
703 {
704 	l->abt_stack_va_end = sp;
705 	thread_set_abt_sp((vaddr_t)l);
706 	thread_set_und_sp((vaddr_t)l);
707 }
708 #endif /*ARM32*/
709 
710 #ifdef ARM64
711 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
712 {
713 	/*
714 	 * We're already using the tmp stack when this function is called
715 	 * so there's no need to assign it to any stack pointer. However,
716 	 * we'll need to restore it at different times so store it here.
717 	 */
718 	l->tmp_stack_va_end = sp;
719 }
720 
721 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
722 {
723 	l->abt_stack_va_end = sp;
724 }
725 #endif /*ARM64*/
726 
727 bool thread_init_stack(uint32_t thread_id, vaddr_t sp)
728 {
729 	if (thread_id >= CFG_NUM_THREADS)
730 		return false;
731 	threads[thread_id].stack_va_end = sp;
732 	return true;
733 }
734 
735 int thread_get_id_may_fail(void)
736 {
737 	/*
738 	 * thread_get_core_local() requires foreign interrupts to be disabled
739 	 */
740 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
741 	struct thread_core_local *l = thread_get_core_local();
742 	int ct = l->curr_thread;
743 
744 	thread_unmask_exceptions(exceptions);
745 	return ct;
746 }
747 
748 int thread_get_id(void)
749 {
750 	int ct = thread_get_id_may_fail();
751 
752 	assert(ct >= 0 && ct < CFG_NUM_THREADS);
753 	return ct;
754 }
755 
756 static void init_handlers(const struct thread_handlers *handlers)
757 {
758 	thread_cpu_on_handler_ptr = handlers->cpu_on;
759 	thread_cpu_off_handler_ptr = handlers->cpu_off;
760 	thread_cpu_suspend_handler_ptr = handlers->cpu_suspend;
761 	thread_cpu_resume_handler_ptr = handlers->cpu_resume;
762 	thread_system_off_handler_ptr = handlers->system_off;
763 	thread_system_reset_handler_ptr = handlers->system_reset;
764 }
765 
766 #ifdef CFG_WITH_PAGER
767 static void init_thread_stacks(void)
768 {
769 	size_t n = 0;
770 
771 	/*
772 	 * Allocate virtual memory for thread stacks.
773 	 */
774 	for (n = 0; n < CFG_NUM_THREADS; n++) {
775 		tee_mm_entry_t *mm = NULL;
776 		vaddr_t sp = 0;
777 		size_t num_pages = 0;
778 		struct fobj *fobj = NULL;
779 
780 		/* Find vmem for thread stack and its protection gap */
781 		mm = tee_mm_alloc(&tee_mm_vcore,
782 				  SMALL_PAGE_SIZE + STACK_THREAD_SIZE);
783 		assert(mm);
784 
785 		/* Claim eventual physical page */
786 		tee_pager_add_pages(tee_mm_get_smem(mm), tee_mm_get_size(mm),
787 				    true);
788 
789 		num_pages = tee_mm_get_bytes(mm) / SMALL_PAGE_SIZE - 1;
790 		fobj = fobj_locked_paged_alloc(num_pages);
791 
792 		/* Add the area to the pager */
793 		tee_pager_add_core_area(tee_mm_get_smem(mm) + SMALL_PAGE_SIZE,
794 					PAGER_AREA_TYPE_LOCK, fobj);
795 		fobj_put(fobj);
796 
797 		/* init effective stack */
798 		sp = tee_mm_get_smem(mm) + tee_mm_get_bytes(mm);
799 		asan_tag_access((void *)tee_mm_get_smem(mm), (void *)sp);
800 		if (!thread_init_stack(n, sp))
801 			panic("init stack failed");
802 	}
803 }
804 #else
805 static void init_thread_stacks(void)
806 {
807 	size_t n;
808 
809 	/* Assign the thread stacks */
810 	for (n = 0; n < CFG_NUM_THREADS; n++) {
811 		if (!thread_init_stack(n, GET_STACK(stack_thread[n])))
812 			panic("thread_init_stack failed");
813 	}
814 }
815 #endif /*CFG_WITH_PAGER*/
816 
817 static void init_user_kcode(void)
818 {
819 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
820 	vaddr_t v = (vaddr_t)thread_excp_vect;
821 	vaddr_t ve = (vaddr_t)thread_excp_vect_end;
822 
823 	thread_user_kcode_va = ROUNDDOWN(v, CORE_MMU_USER_CODE_SIZE);
824 	ve = ROUNDUP(ve, CORE_MMU_USER_CODE_SIZE);
825 	thread_user_kcode_size = ve - thread_user_kcode_va;
826 
827 	core_mmu_get_user_va_range(&v, NULL);
828 	thread_user_kcode_offset = thread_user_kcode_va - v;
829 
830 #if defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
831 	/*
832 	 * When transitioning to EL0 subtract SP with this much to point to
833 	 * this special kdata page instead. SP is restored by add this much
834 	 * while transitioning back to EL1.
835 	 */
836 	v += thread_user_kcode_size;
837 	thread_user_kdata_sp_offset = (vaddr_t)thread_core_local - v;
838 #endif
839 #endif /*CFG_CORE_UNMAP_CORE_AT_EL0*/
840 }
841 
842 void thread_init_threads(void)
843 {
844 	size_t n;
845 
846 	init_thread_stacks();
847 	pgt_init();
848 
849 	mutex_lockdep_init();
850 
851 	for (n = 0; n < CFG_NUM_THREADS; n++) {
852 		TAILQ_INIT(&threads[n].tsd.sess_stack);
853 		SLIST_INIT(&threads[n].tsd.pgt_cache);
854 	}
855 
856 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++)
857 		thread_core_local[n].curr_thread = -1;
858 }
859 
860 void thread_init_primary(const struct thread_handlers *handlers)
861 {
862 	init_handlers(handlers);
863 
864 	/* Initialize canaries around the stacks */
865 	init_canaries();
866 
867 	init_user_kcode();
868 }
869 
870 static void init_sec_mon(size_t pos __maybe_unused)
871 {
872 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
873 	/* Initialize secure monitor */
874 	sm_init(GET_STACK(stack_tmp[pos]));
875 #endif
876 }
877 
878 static uint32_t __maybe_unused get_midr_implementer(uint32_t midr)
879 {
880 	return (midr >> MIDR_IMPLEMENTER_SHIFT) & MIDR_IMPLEMENTER_MASK;
881 }
882 
883 static uint32_t __maybe_unused get_midr_primary_part(uint32_t midr)
884 {
885 	return (midr >> MIDR_PRIMARY_PART_NUM_SHIFT) &
886 	       MIDR_PRIMARY_PART_NUM_MASK;
887 }
888 
889 #ifdef ARM64
890 static bool probe_workaround_available(void)
891 {
892 	int32_t r;
893 
894 	r = thread_smc(SMCCC_VERSION, 0, 0, 0);
895 	if (r < 0)
896 		return false;
897 	if (r < 0x10001)	/* compare with version 1.1 */
898 		return false;
899 
900 	/* Version >= 1.1, so SMCCC_ARCH_FEATURES is available */
901 	r = thread_smc(SMCCC_ARCH_FEATURES, SMCCC_ARCH_WORKAROUND_1, 0, 0);
902 	return r >= 0;
903 }
904 
905 static vaddr_t __maybe_unused select_vector(vaddr_t a)
906 {
907 	if (probe_workaround_available()) {
908 		DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") available",
909 		     SMCCC_ARCH_WORKAROUND_1);
910 		DMSG("SMC Workaround for CVE-2017-5715 used");
911 		return a;
912 	}
913 
914 	DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") unavailable",
915 	     SMCCC_ARCH_WORKAROUND_1);
916 	DMSG("SMC Workaround for CVE-2017-5715 not needed (if ARM-TF is up to date)");
917 	return (vaddr_t)thread_excp_vect;
918 }
919 #else
920 static vaddr_t __maybe_unused select_vector(vaddr_t a)
921 {
922 	return a;
923 }
924 #endif
925 
926 static vaddr_t get_excp_vect(void)
927 {
928 #ifdef CFG_CORE_WORKAROUND_SPECTRE_BP_SEC
929 	uint32_t midr = read_midr();
930 
931 	if (get_midr_implementer(midr) != MIDR_IMPLEMENTER_ARM)
932 		return (vaddr_t)thread_excp_vect;
933 
934 	switch (get_midr_primary_part(midr)) {
935 #ifdef ARM32
936 	case CORTEX_A8_PART_NUM:
937 	case CORTEX_A9_PART_NUM:
938 	case CORTEX_A17_PART_NUM:
939 #endif
940 	case CORTEX_A57_PART_NUM:
941 	case CORTEX_A72_PART_NUM:
942 	case CORTEX_A73_PART_NUM:
943 	case CORTEX_A75_PART_NUM:
944 		return select_vector((vaddr_t)thread_excp_vect_workaround);
945 #ifdef ARM32
946 	case CORTEX_A15_PART_NUM:
947 		return select_vector((vaddr_t)thread_excp_vect_workaround_a15);
948 #endif
949 	default:
950 		return (vaddr_t)thread_excp_vect;
951 	}
952 #endif /*CFG_CORE_WORKAROUND_SPECTRE_BP_SEC*/
953 
954 	return (vaddr_t)thread_excp_vect;
955 }
956 
957 void thread_init_per_cpu(void)
958 {
959 	size_t pos = get_core_pos();
960 	struct thread_core_local *l = thread_get_core_local();
961 
962 	init_sec_mon(pos);
963 
964 	set_tmp_stack(l, GET_STACK(stack_tmp[pos]) - STACK_TMP_OFFS);
965 	set_abt_stack(l, GET_STACK(stack_abt[pos]));
966 
967 	thread_init_vbar(get_excp_vect());
968 
969 #ifdef CFG_TA_FTRACE_SUPPORT
970 	/*
971 	 * Enable accesses to frequency register and physical counter
972 	 * register in EL0/PL0 required for timestamping during
973 	 * function tracing.
974 	 */
975 	write_cntkctl(read_cntkctl() | CNTKCTL_PL0PCTEN);
976 #endif
977 }
978 
979 struct thread_specific_data *thread_get_tsd(void)
980 {
981 	return &threads[thread_get_id()].tsd;
982 }
983 
984 struct thread_ctx_regs *thread_get_ctx_regs(void)
985 {
986 	struct thread_core_local *l = thread_get_core_local();
987 
988 	assert(l->curr_thread != -1);
989 	return &threads[l->curr_thread].regs;
990 }
991 
992 void thread_set_foreign_intr(bool enable)
993 {
994 	/* thread_get_core_local() requires foreign interrupts to be disabled */
995 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
996 	struct thread_core_local *l;
997 
998 	l = thread_get_core_local();
999 
1000 	assert(l->curr_thread != -1);
1001 
1002 	if (enable) {
1003 		threads[l->curr_thread].flags |=
1004 					THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1005 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1006 	} else {
1007 		/*
1008 		 * No need to disable foreign interrupts here since they're
1009 		 * already disabled above.
1010 		 */
1011 		threads[l->curr_thread].flags &=
1012 					~THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1013 	}
1014 }
1015 
1016 void thread_restore_foreign_intr(void)
1017 {
1018 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1019 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1020 	struct thread_core_local *l;
1021 
1022 	l = thread_get_core_local();
1023 
1024 	assert(l->curr_thread != -1);
1025 
1026 	if (threads[l->curr_thread].flags & THREAD_FLAGS_FOREIGN_INTR_ENABLE)
1027 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1028 }
1029 
1030 #ifdef CFG_WITH_VFP
1031 uint32_t thread_kernel_enable_vfp(void)
1032 {
1033 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1034 	struct thread_ctx *thr = threads + thread_get_id();
1035 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1036 
1037 	assert(!vfp_is_enabled());
1038 
1039 	if (!thr->vfp_state.ns_saved) {
1040 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1041 					  true /*force_save*/);
1042 		thr->vfp_state.ns_saved = true;
1043 	} else if (thr->vfp_state.sec_lazy_saved &&
1044 		   !thr->vfp_state.sec_saved) {
1045 		/*
1046 		 * This happens when we're handling an abort while the
1047 		 * thread was using the VFP state.
1048 		 */
1049 		vfp_lazy_save_state_final(&thr->vfp_state.sec,
1050 					  false /*!force_save*/);
1051 		thr->vfp_state.sec_saved = true;
1052 	} else if (tuv && tuv->lazy_saved && !tuv->saved) {
1053 		/*
1054 		 * This can happen either during syscall or abort
1055 		 * processing (while processing a syscall).
1056 		 */
1057 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
1058 		tuv->saved = true;
1059 	}
1060 
1061 	vfp_enable();
1062 	return exceptions;
1063 }
1064 
1065 void thread_kernel_disable_vfp(uint32_t state)
1066 {
1067 	uint32_t exceptions;
1068 
1069 	assert(vfp_is_enabled());
1070 
1071 	vfp_disable();
1072 	exceptions = thread_get_exceptions();
1073 	assert(exceptions & THREAD_EXCP_FOREIGN_INTR);
1074 	exceptions &= ~THREAD_EXCP_FOREIGN_INTR;
1075 	exceptions |= state & THREAD_EXCP_FOREIGN_INTR;
1076 	thread_set_exceptions(exceptions);
1077 }
1078 
1079 void thread_kernel_save_vfp(void)
1080 {
1081 	struct thread_ctx *thr = threads + thread_get_id();
1082 
1083 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1084 	if (vfp_is_enabled()) {
1085 		vfp_lazy_save_state_init(&thr->vfp_state.sec);
1086 		thr->vfp_state.sec_lazy_saved = true;
1087 	}
1088 }
1089 
1090 void thread_kernel_restore_vfp(void)
1091 {
1092 	struct thread_ctx *thr = threads + thread_get_id();
1093 
1094 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1095 	assert(!vfp_is_enabled());
1096 	if (thr->vfp_state.sec_lazy_saved) {
1097 		vfp_lazy_restore_state(&thr->vfp_state.sec,
1098 				       thr->vfp_state.sec_saved);
1099 		thr->vfp_state.sec_saved = false;
1100 		thr->vfp_state.sec_lazy_saved = false;
1101 	}
1102 }
1103 
1104 void thread_user_enable_vfp(struct thread_user_vfp_state *uvfp)
1105 {
1106 	struct thread_ctx *thr = threads + thread_get_id();
1107 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1108 
1109 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1110 	assert(!vfp_is_enabled());
1111 
1112 	if (!thr->vfp_state.ns_saved) {
1113 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1114 					  true /*force_save*/);
1115 		thr->vfp_state.ns_saved = true;
1116 	} else if (tuv && uvfp != tuv) {
1117 		if (tuv->lazy_saved && !tuv->saved) {
1118 			vfp_lazy_save_state_final(&tuv->vfp,
1119 						  false /*!force_save*/);
1120 			tuv->saved = true;
1121 		}
1122 	}
1123 
1124 	if (uvfp->lazy_saved)
1125 		vfp_lazy_restore_state(&uvfp->vfp, uvfp->saved);
1126 	uvfp->lazy_saved = false;
1127 	uvfp->saved = false;
1128 
1129 	thr->vfp_state.uvfp = uvfp;
1130 	vfp_enable();
1131 }
1132 
1133 void thread_user_save_vfp(void)
1134 {
1135 	struct thread_ctx *thr = threads + thread_get_id();
1136 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1137 
1138 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1139 	if (!vfp_is_enabled())
1140 		return;
1141 
1142 	assert(tuv && !tuv->lazy_saved && !tuv->saved);
1143 	vfp_lazy_save_state_init(&tuv->vfp);
1144 	tuv->lazy_saved = true;
1145 }
1146 
1147 void thread_user_clear_vfp(struct thread_user_vfp_state *uvfp)
1148 {
1149 	struct thread_ctx *thr = threads + thread_get_id();
1150 
1151 	if (uvfp == thr->vfp_state.uvfp)
1152 		thr->vfp_state.uvfp = NULL;
1153 	uvfp->lazy_saved = false;
1154 	uvfp->saved = false;
1155 }
1156 #endif /*CFG_WITH_VFP*/
1157 
1158 #ifdef ARM32
1159 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1160 {
1161 	uint32_t s;
1162 
1163 	if (!is_32bit)
1164 		return false;
1165 
1166 	s = read_spsr();
1167 	s &= ~(CPSR_MODE_MASK | CPSR_T | CPSR_IT_MASK1 | CPSR_IT_MASK2);
1168 	s |= CPSR_MODE_USR;
1169 	if (entry_func & 1)
1170 		s |= CPSR_T;
1171 	*spsr = s;
1172 	return true;
1173 }
1174 #endif
1175 
1176 #ifdef ARM64
1177 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1178 {
1179 	uint32_t s;
1180 
1181 	if (is_32bit) {
1182 		s = read_daif() & (SPSR_32_AIF_MASK << SPSR_32_AIF_SHIFT);
1183 		s |= SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT;
1184 		s |= (entry_func & SPSR_32_T_MASK) << SPSR_32_T_SHIFT;
1185 	} else {
1186 		s = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
1187 	}
1188 
1189 	*spsr = s;
1190 	return true;
1191 }
1192 #endif
1193 
1194 uint32_t thread_enter_user_mode(unsigned long a0, unsigned long a1,
1195 		unsigned long a2, unsigned long a3, unsigned long user_sp,
1196 		unsigned long entry_func, bool is_32bit,
1197 		uint32_t *exit_status0, uint32_t *exit_status1)
1198 {
1199 	uint32_t spsr;
1200 
1201 	tee_ta_update_session_utime_resume();
1202 
1203 	if (!get_spsr(is_32bit, entry_func, &spsr)) {
1204 		*exit_status0 = 1; /* panic */
1205 		*exit_status1 = 0xbadbadba;
1206 		return 0;
1207 	}
1208 	return __thread_enter_user_mode(a0, a1, a2, a3, user_sp, entry_func,
1209 					spsr, exit_status0, exit_status1);
1210 }
1211 
1212 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
1213 void thread_get_user_kcode(struct mobj **mobj, size_t *offset,
1214 			   vaddr_t *va, size_t *sz)
1215 {
1216 	core_mmu_get_user_va_range(va, NULL);
1217 	*mobj = mobj_tee_ram;
1218 	*offset = thread_user_kcode_va - TEE_RAM_START;
1219 	*sz = thread_user_kcode_size;
1220 }
1221 #endif
1222 
1223 #if defined(CFG_CORE_UNMAP_CORE_AT_EL0) && \
1224 	defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
1225 void thread_get_user_kdata(struct mobj **mobj, size_t *offset,
1226 			   vaddr_t *va, size_t *sz)
1227 {
1228 	vaddr_t v;
1229 
1230 	core_mmu_get_user_va_range(&v, NULL);
1231 	*va = v + thread_user_kcode_size;
1232 	*mobj = mobj_tee_ram;
1233 	*offset = (vaddr_t)thread_user_kdata_page - TEE_RAM_START;
1234 	*sz = sizeof(thread_user_kdata_page);
1235 }
1236 #endif
1237