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