xref: /optee_os/core/arch/arm/kernel/thread.c (revision 4e154320e47c319a658f27a0a8dcd0e59971da83)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2016-2022, Linaro Limited
4  * Copyright (c) 2014, STMicroelectronics International N.V.
5  * Copyright (c) 2020-2021, Arm Limited
6  */
7 
8 #include <platform_config.h>
9 
10 #include <arm.h>
11 #include <assert.h>
12 #include <config.h>
13 #include <io.h>
14 #include <keep.h>
15 #include <kernel/asan.h>
16 #include <kernel/boot.h>
17 #include <kernel/linker.h>
18 #include <kernel/lockdep.h>
19 #include <kernel/misc.h>
20 #include <kernel/panic.h>
21 #include <kernel/spinlock.h>
22 #include <kernel/spmc_sp_handler.h>
23 #include <kernel/tee_ta_manager.h>
24 #include <kernel/thread.h>
25 #include <kernel/thread_private.h>
26 #include <kernel/user_access.h>
27 #include <kernel/user_mode_ctx_struct.h>
28 #include <kernel/virtualization.h>
29 #include <mm/core_memprot.h>
30 #include <mm/mobj.h>
31 #include <mm/tee_mm.h>
32 #include <mm/tee_pager.h>
33 #include <mm/vm.h>
34 #include <smccc.h>
35 #include <sm/sm.h>
36 #include <trace.h>
37 #include <util.h>
38 
39 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
40 static vaddr_t thread_user_kcode_va __nex_bss;
41 long thread_user_kcode_offset __nex_bss;
42 static size_t thread_user_kcode_size __nex_bss;
43 #endif
44 
45 #if defined(CFG_CORE_UNMAP_CORE_AT_EL0) && \
46 	defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
47 long thread_user_kdata_sp_offset __nex_bss;
48 static uint8_t thread_user_kdata_page[
49 	ROUNDUP(sizeof(struct thread_core_local) * CFG_TEE_CORE_NB_CORE,
50 		SMALL_PAGE_SIZE)]
51 	__aligned(SMALL_PAGE_SIZE)
52 #ifndef CFG_NS_VIRTUALIZATION
53 	__section(".nozi.kdata_page");
54 #else
55 	__section(".nex_nozi.kdata_page");
56 #endif
57 #endif
58 
59 #ifdef ARM32
60 uint32_t __nostackcheck thread_get_exceptions(void)
61 {
62 	uint32_t cpsr = read_cpsr();
63 
64 	return (cpsr >> CPSR_F_SHIFT) & THREAD_EXCP_ALL;
65 }
66 
67 void __nostackcheck thread_set_exceptions(uint32_t exceptions)
68 {
69 	uint32_t cpsr = read_cpsr();
70 
71 	/* Foreign interrupts must not be unmasked while holding a spinlock */
72 	if (!(exceptions & THREAD_EXCP_FOREIGN_INTR))
73 		assert_have_no_spinlock();
74 
75 	cpsr &= ~(THREAD_EXCP_ALL << CPSR_F_SHIFT);
76 	cpsr |= ((exceptions & THREAD_EXCP_ALL) << CPSR_F_SHIFT);
77 
78 	barrier();
79 	write_cpsr(cpsr);
80 	barrier();
81 }
82 #endif /*ARM32*/
83 
84 #ifdef ARM64
85 uint32_t __nostackcheck thread_get_exceptions(void)
86 {
87 	uint32_t daif = read_daif();
88 
89 	return (daif >> DAIF_F_SHIFT) & THREAD_EXCP_ALL;
90 }
91 
92 void __nostackcheck thread_set_exceptions(uint32_t exceptions)
93 {
94 	uint32_t daif = read_daif();
95 
96 	/* Foreign interrupts must not be unmasked while holding a spinlock */
97 	if (!(exceptions & THREAD_EXCP_FOREIGN_INTR))
98 		assert_have_no_spinlock();
99 
100 	daif &= ~(THREAD_EXCP_ALL << DAIF_F_SHIFT);
101 	daif |= ((exceptions & THREAD_EXCP_ALL) << DAIF_F_SHIFT);
102 
103 	barrier();
104 	write_daif(daif);
105 	barrier();
106 }
107 #endif /*ARM64*/
108 
109 uint32_t __nostackcheck thread_mask_exceptions(uint32_t exceptions)
110 {
111 	uint32_t state = thread_get_exceptions();
112 
113 	thread_set_exceptions(state | (exceptions & THREAD_EXCP_ALL));
114 	return state;
115 }
116 
117 void __nostackcheck thread_unmask_exceptions(uint32_t state)
118 {
119 	thread_set_exceptions(state & THREAD_EXCP_ALL);
120 }
121 
122 static void thread_lazy_save_ns_vfp(void)
123 {
124 #ifdef CFG_WITH_VFP
125 	struct thread_ctx *thr = threads + thread_get_id();
126 
127 	thr->vfp_state.ns_saved = false;
128 	vfp_lazy_save_state_init(&thr->vfp_state.ns);
129 #endif /*CFG_WITH_VFP*/
130 }
131 
132 static void thread_lazy_restore_ns_vfp(void)
133 {
134 #ifdef CFG_WITH_VFP
135 	struct thread_ctx *thr = threads + thread_get_id();
136 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
137 
138 	assert(!thr->vfp_state.sec_lazy_saved && !thr->vfp_state.sec_saved);
139 
140 	if (tuv && tuv->lazy_saved && !tuv->saved) {
141 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
142 		tuv->saved = true;
143 	}
144 
145 	vfp_lazy_restore_state(&thr->vfp_state.ns, thr->vfp_state.ns_saved);
146 	thr->vfp_state.ns_saved = false;
147 #endif /*CFG_WITH_VFP*/
148 }
149 
150 #ifdef ARM32
151 static void init_regs(struct thread_ctx *thread, uint32_t a0, uint32_t a1,
152 		      uint32_t a2, uint32_t a3, uint32_t a4, uint32_t a5,
153 		      uint32_t a6, uint32_t a7, void *pc)
154 {
155 	thread->regs.pc = (uint32_t)pc;
156 
157 	/*
158 	 * Stdcalls starts in SVC mode with masked foreign interrupts, masked
159 	 * Asynchronous abort and unmasked native interrupts.
160 	 */
161 	thread->regs.cpsr = read_cpsr() & ARM32_CPSR_E;
162 	thread->regs.cpsr |= CPSR_MODE_SVC | CPSR_A |
163 			(THREAD_EXCP_FOREIGN_INTR << ARM32_CPSR_F_SHIFT);
164 	/* Enable thumb mode if it's a thumb instruction */
165 	if (thread->regs.pc & 1)
166 		thread->regs.cpsr |= CPSR_T;
167 	/* Reinitialize stack pointer */
168 	thread->regs.svc_sp = thread->stack_va_end;
169 
170 	/*
171 	 * Copy arguments into context. This will make the
172 	 * arguments appear in r0-r7 when thread is started.
173 	 */
174 	thread->regs.r0 = a0;
175 	thread->regs.r1 = a1;
176 	thread->regs.r2 = a2;
177 	thread->regs.r3 = a3;
178 	thread->regs.r4 = a4;
179 	thread->regs.r5 = a5;
180 	thread->regs.r6 = a6;
181 	thread->regs.r7 = a7;
182 }
183 #endif /*ARM32*/
184 
185 #ifdef ARM64
186 static void init_regs(struct thread_ctx *thread, uint32_t a0, uint32_t a1,
187 		      uint32_t a2, uint32_t a3, uint32_t a4, uint32_t a5,
188 		      uint32_t a6, uint32_t a7, void *pc)
189 {
190 	thread->regs.pc = (uint64_t)pc;
191 
192 	/*
193 	 * Stdcalls starts in SVC mode with masked foreign interrupts, masked
194 	 * Asynchronous abort and unmasked native interrupts.
195 	 */
196 	thread->regs.cpsr = SPSR_64(SPSR_64_MODE_EL1, SPSR_64_MODE_SP_EL0,
197 				THREAD_EXCP_FOREIGN_INTR | DAIFBIT_ABT);
198 	/* Reinitialize stack pointer */
199 	thread->regs.sp = thread->stack_va_end;
200 
201 	/*
202 	 * Copy arguments into context. This will make the
203 	 * arguments appear in x0-x7 when thread is started.
204 	 */
205 	thread->regs.x[0] = a0;
206 	thread->regs.x[1] = a1;
207 	thread->regs.x[2] = a2;
208 	thread->regs.x[3] = a3;
209 	thread->regs.x[4] = a4;
210 	thread->regs.x[5] = a5;
211 	thread->regs.x[6] = a6;
212 	thread->regs.x[7] = a7;
213 
214 	/* Set up frame pointer as per the Aarch64 AAPCS */
215 	thread->regs.x[29] = 0;
216 }
217 #endif /*ARM64*/
218 
219 static void __thread_alloc_and_run(uint32_t a0, uint32_t a1, uint32_t a2,
220 				   uint32_t a3, uint32_t a4, uint32_t a5,
221 				   uint32_t a6, uint32_t a7,
222 				   void *pc, uint32_t flags)
223 {
224 	struct thread_core_local *l = thread_get_core_local();
225 	bool found_thread = false;
226 	size_t n = 0;
227 
228 	assert(l->curr_thread == THREAD_ID_INVALID);
229 
230 	thread_lock_global();
231 
232 	for (n = 0; n < CFG_NUM_THREADS; n++) {
233 		if (threads[n].state == THREAD_STATE_FREE) {
234 			threads[n].state = THREAD_STATE_ACTIVE;
235 			found_thread = true;
236 			break;
237 		}
238 	}
239 
240 	thread_unlock_global();
241 
242 	if (!found_thread)
243 		return;
244 
245 	l->curr_thread = n;
246 
247 	threads[n].flags = flags;
248 	init_regs(threads + n, a0, a1, a2, a3, a4, a5, a6, a7, pc);
249 #ifdef CFG_CORE_PAUTH
250 	/*
251 	 * Copy the APIA key into the registers to be restored with
252 	 * thread_resume().
253 	 */
254 	threads[n].regs.apiakey_hi = threads[n].keys.apia_hi;
255 	threads[n].regs.apiakey_lo = threads[n].keys.apia_lo;
256 #endif
257 
258 	thread_lazy_save_ns_vfp();
259 
260 	l->flags &= ~THREAD_CLF_TMP;
261 	thread_resume(&threads[n].regs);
262 	/*NOTREACHED*/
263 	panic();
264 }
265 
266 void thread_alloc_and_run(uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3,
267 			  uint32_t a4, uint32_t a5)
268 {
269 	__thread_alloc_and_run(a0, a1, a2, a3, a4, a5, 0, 0,
270 			       thread_std_smc_entry, 0);
271 }
272 
273 #ifdef CFG_SECURE_PARTITION
274 void thread_sp_alloc_and_run(struct thread_smc_args *args __maybe_unused)
275 {
276 	__thread_alloc_and_run(args->a0, args->a1, args->a2, args->a3, args->a4,
277 			       args->a5, args->a6, args->a7,
278 			       spmc_sp_thread_entry, THREAD_FLAGS_FFA_ONLY);
279 }
280 #endif
281 
282 #ifdef ARM32
283 static void copy_a0_to_a3(struct thread_ctx_regs *regs, uint32_t a0,
284 			  uint32_t a1, uint32_t a2, uint32_t a3)
285 {
286 	/*
287 	 * Update returned values from RPC, values will appear in
288 	 * r0-r3 when thread is resumed.
289 	 */
290 	regs->r0 = a0;
291 	regs->r1 = a1;
292 	regs->r2 = a2;
293 	regs->r3 = a3;
294 }
295 #endif /*ARM32*/
296 
297 #ifdef ARM64
298 static void copy_a0_to_a3(struct thread_ctx_regs *regs, uint32_t a0,
299 			  uint32_t a1, uint32_t a2, uint32_t a3)
300 {
301 	/*
302 	 * Update returned values from RPC, values will appear in
303 	 * x0-x3 when thread is resumed.
304 	 */
305 	regs->x[0] = a0;
306 	regs->x[1] = a1;
307 	regs->x[2] = a2;
308 	regs->x[3] = a3;
309 }
310 #endif /*ARM64*/
311 
312 #ifdef ARM32
313 static bool is_from_user(uint32_t cpsr)
314 {
315 	return (cpsr & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_USR;
316 }
317 #endif
318 
319 #ifdef ARM64
320 static bool is_from_user(uint32_t cpsr)
321 {
322 	if (cpsr & (SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT))
323 		return true;
324 	if (((cpsr >> SPSR_64_MODE_EL_SHIFT) & SPSR_64_MODE_EL_MASK) ==
325 	     SPSR_64_MODE_EL0)
326 		return true;
327 	return false;
328 }
329 #endif
330 
331 #ifdef CFG_SYSCALL_FTRACE
332 static void __noprof ftrace_suspend(void)
333 {
334 	struct ts_session *s = TAILQ_FIRST(&thread_get_tsd()->sess_stack);
335 
336 	if (s && s->fbuf)
337 		s->fbuf->syscall_trace_suspended = true;
338 }
339 
340 static void __noprof ftrace_resume(void)
341 {
342 	struct ts_session *s = TAILQ_FIRST(&thread_get_tsd()->sess_stack);
343 
344 	if (s && s->fbuf)
345 		s->fbuf->syscall_trace_suspended = false;
346 }
347 #else
348 static void __noprof ftrace_suspend(void)
349 {
350 }
351 
352 static void __noprof ftrace_resume(void)
353 {
354 }
355 #endif
356 
357 static bool is_user_mode(struct thread_ctx_regs *regs)
358 {
359 	return is_from_user((uint32_t)regs->cpsr);
360 }
361 
362 void thread_resume_from_rpc(uint32_t thread_id, uint32_t a0, uint32_t a1,
363 			    uint32_t a2, uint32_t a3)
364 {
365 	size_t n = thread_id;
366 	struct thread_core_local *l = thread_get_core_local();
367 	bool found_thread = false;
368 
369 	assert(l->curr_thread == THREAD_ID_INVALID);
370 
371 	thread_lock_global();
372 
373 	if (n < CFG_NUM_THREADS && threads[n].state == THREAD_STATE_SUSPENDED) {
374 		threads[n].state = THREAD_STATE_ACTIVE;
375 		found_thread = true;
376 	}
377 
378 	thread_unlock_global();
379 
380 	if (!found_thread)
381 		return;
382 
383 	l->curr_thread = n;
384 
385 	if (threads[n].have_user_map) {
386 		core_mmu_set_user_map(&threads[n].user_map);
387 		if (threads[n].flags & THREAD_FLAGS_EXIT_ON_FOREIGN_INTR)
388 			tee_ta_ftrace_update_times_resume();
389 	}
390 
391 	if (is_user_mode(&threads[n].regs))
392 		tee_ta_update_session_utime_resume();
393 
394 	/*
395 	 * Return from RPC to request service of a foreign interrupt must not
396 	 * get parameters from non-secure world.
397 	 */
398 	if (threads[n].flags & THREAD_FLAGS_COPY_ARGS_ON_RETURN) {
399 		copy_a0_to_a3(&threads[n].regs, a0, a1, a2, a3);
400 		threads[n].flags &= ~THREAD_FLAGS_COPY_ARGS_ON_RETURN;
401 	}
402 
403 	thread_lazy_save_ns_vfp();
404 
405 	if (threads[n].have_user_map)
406 		ftrace_resume();
407 
408 	l->flags &= ~THREAD_CLF_TMP;
409 	thread_resume(&threads[n].regs);
410 	/*NOTREACHED*/
411 	panic();
412 }
413 
414 #ifdef ARM64
415 vaddr_t thread_get_saved_thread_sp(void)
416 {
417 	struct thread_core_local *l = thread_get_core_local();
418 	int ct = l->curr_thread;
419 
420 	assert(ct != THREAD_ID_INVALID);
421 	return threads[ct].kern_sp;
422 }
423 #endif /*ARM64*/
424 
425 #ifdef ARM32
426 bool thread_is_in_normal_mode(void)
427 {
428 	return (read_cpsr() & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_SVC;
429 }
430 #endif
431 
432 void thread_state_free(void)
433 {
434 	struct thread_core_local *l = thread_get_core_local();
435 	int ct = l->curr_thread;
436 
437 	assert(ct != THREAD_ID_INVALID);
438 
439 	thread_lazy_restore_ns_vfp();
440 	tee_pager_release_phys(
441 		(void *)(threads[ct].stack_va_end - STACK_THREAD_SIZE),
442 		STACK_THREAD_SIZE);
443 
444 	thread_lock_global();
445 
446 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
447 	threads[ct].state = THREAD_STATE_FREE;
448 	threads[ct].flags = 0;
449 	l->curr_thread = THREAD_ID_INVALID;
450 
451 	if (IS_ENABLED(CFG_NS_VIRTUALIZATION))
452 		virt_unset_guest();
453 	thread_unlock_global();
454 }
455 
456 #ifdef CFG_WITH_PAGER
457 static void release_unused_kernel_stack(struct thread_ctx *thr,
458 					uint32_t cpsr __maybe_unused)
459 {
460 #ifdef ARM64
461 	/*
462 	 * If we're from user mode then thr->regs.sp is the saved user
463 	 * stack pointer and thr->kern_sp holds the last kernel stack
464 	 * pointer. But if we're from kernel mode then thr->kern_sp isn't
465 	 * up to date so we need to read from thr->regs.sp instead.
466 	 */
467 	vaddr_t sp = is_from_user(cpsr) ?  thr->kern_sp : thr->regs.sp;
468 #else
469 	vaddr_t sp = thr->regs.svc_sp;
470 #endif
471 	vaddr_t base = thr->stack_va_end - STACK_THREAD_SIZE;
472 	size_t len = sp - base;
473 
474 	tee_pager_release_phys((void *)base, len);
475 }
476 #else
477 static void release_unused_kernel_stack(struct thread_ctx *thr __unused,
478 					uint32_t cpsr __unused)
479 {
480 }
481 #endif
482 
483 int thread_state_suspend(uint32_t flags, uint32_t cpsr, vaddr_t pc)
484 {
485 	struct thread_core_local *l = thread_get_core_local();
486 	int ct = l->curr_thread;
487 
488 	assert(ct != THREAD_ID_INVALID);
489 
490 	if (core_mmu_user_mapping_is_active())
491 		ftrace_suspend();
492 
493 	thread_check_canaries();
494 
495 	release_unused_kernel_stack(threads + ct, cpsr);
496 
497 	if (is_from_user(cpsr)) {
498 		thread_user_save_vfp();
499 		tee_ta_update_session_utime_suspend();
500 		tee_ta_gprof_sample_pc(pc);
501 	}
502 	thread_lazy_restore_ns_vfp();
503 
504 	thread_lock_global();
505 
506 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
507 	threads[ct].flags |= flags;
508 	threads[ct].regs.cpsr = cpsr;
509 	threads[ct].regs.pc = pc;
510 	threads[ct].state = THREAD_STATE_SUSPENDED;
511 
512 	threads[ct].have_user_map = core_mmu_user_mapping_is_active();
513 	if (threads[ct].have_user_map) {
514 		if (threads[ct].flags & THREAD_FLAGS_EXIT_ON_FOREIGN_INTR)
515 			tee_ta_ftrace_update_times_suspend();
516 		core_mmu_get_user_map(&threads[ct].user_map);
517 		core_mmu_set_user_map(NULL);
518 	}
519 
520 	if (IS_ENABLED(CFG_SECURE_PARTITION)) {
521 		struct ts_session *ts_sess =
522 			TAILQ_FIRST(&threads[ct].tsd.sess_stack);
523 
524 		spmc_sp_set_to_preempted(ts_sess);
525 	}
526 
527 	l->curr_thread = THREAD_ID_INVALID;
528 
529 	if (IS_ENABLED(CFG_NS_VIRTUALIZATION))
530 		virt_unset_guest();
531 
532 	thread_unlock_global();
533 
534 	return ct;
535 }
536 
537 bool thread_init_stack(uint32_t thread_id, vaddr_t sp)
538 {
539 	if (thread_id >= CFG_NUM_THREADS)
540 		return false;
541 	threads[thread_id].stack_va_end = sp;
542 	return true;
543 }
544 
545 static void __maybe_unused
546 set_core_local_kcode_offset(struct thread_core_local *cls, long offset)
547 {
548 	size_t n = 0;
549 
550 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++)
551 		cls[n].kcode_offset = offset;
552 }
553 
554 static void init_user_kcode(void)
555 {
556 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
557 	vaddr_t v = (vaddr_t)thread_excp_vect;
558 	vaddr_t ve = (vaddr_t)thread_excp_vect_end;
559 
560 	thread_user_kcode_va = ROUNDDOWN(v, CORE_MMU_USER_CODE_SIZE);
561 	ve = ROUNDUP(ve, CORE_MMU_USER_CODE_SIZE);
562 	thread_user_kcode_size = ve - thread_user_kcode_va;
563 
564 	core_mmu_get_user_va_range(&v, NULL);
565 	thread_user_kcode_offset = thread_user_kcode_va - v;
566 
567 	set_core_local_kcode_offset(thread_core_local,
568 				    thread_user_kcode_offset);
569 #if defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
570 	set_core_local_kcode_offset((void *)thread_user_kdata_page,
571 				    thread_user_kcode_offset);
572 	/*
573 	 * When transitioning to EL0 subtract SP with this much to point to
574 	 * this special kdata page instead. SP is restored by add this much
575 	 * while transitioning back to EL1.
576 	 */
577 	v += thread_user_kcode_size;
578 	thread_user_kdata_sp_offset = (vaddr_t)thread_core_local - v;
579 #endif
580 #endif /*CFG_CORE_UNMAP_CORE_AT_EL0*/
581 }
582 
583 void thread_init_primary(void)
584 {
585 	/* Initialize canaries around the stacks */
586 	thread_init_canaries();
587 
588 	init_user_kcode();
589 }
590 
591 static uint32_t __maybe_unused get_midr_implementer(uint32_t midr)
592 {
593 	return (midr >> MIDR_IMPLEMENTER_SHIFT) & MIDR_IMPLEMENTER_MASK;
594 }
595 
596 static uint32_t __maybe_unused get_midr_primary_part(uint32_t midr)
597 {
598 	return (midr >> MIDR_PRIMARY_PART_NUM_SHIFT) &
599 	       MIDR_PRIMARY_PART_NUM_MASK;
600 }
601 
602 static uint32_t __maybe_unused get_midr_variant(uint32_t midr)
603 {
604 	return (midr >> MIDR_VARIANT_SHIFT) & MIDR_VARIANT_MASK;
605 }
606 
607 static uint32_t __maybe_unused get_midr_revision(uint32_t midr)
608 {
609 	return (midr >> MIDR_REVISION_SHIFT) & MIDR_REVISION_MASK;
610 }
611 
612 #ifdef CFG_CORE_WORKAROUND_SPECTRE_BP_SEC
613 #ifdef ARM64
614 static bool probe_workaround_available(uint32_t wa_id)
615 {
616 	int32_t r;
617 
618 	r = thread_smc(SMCCC_VERSION, 0, 0, 0);
619 	if (r < 0)
620 		return false;
621 	if (r < 0x10001)	/* compare with version 1.1 */
622 		return false;
623 
624 	/* Version >= 1.1, so SMCCC_ARCH_FEATURES is available */
625 	r = thread_smc(SMCCC_ARCH_FEATURES, wa_id, 0, 0);
626 	return r >= 0;
627 }
628 
629 static vaddr_t __maybe_unused select_vector_wa_spectre_v2(void)
630 {
631 	if (probe_workaround_available(SMCCC_ARCH_WORKAROUND_1)) {
632 		DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") available",
633 		     SMCCC_ARCH_WORKAROUND_1);
634 		DMSG("SMC Workaround for CVE-2017-5715 used");
635 		return (vaddr_t)thread_excp_vect_wa_spectre_v2;
636 	}
637 
638 	DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") unavailable",
639 	     SMCCC_ARCH_WORKAROUND_1);
640 	DMSG("SMC Workaround for CVE-2017-5715 not needed (if ARM-TF is up to date)");
641 	return (vaddr_t)thread_excp_vect;
642 }
643 #else
644 static vaddr_t __maybe_unused select_vector_wa_spectre_v2(void)
645 {
646 	return (vaddr_t)thread_excp_vect_wa_spectre_v2;
647 }
648 #endif
649 #endif
650 
651 #ifdef CFG_CORE_WORKAROUND_SPECTRE_BP_SEC
652 static vaddr_t select_vector_wa_spectre_bhb(uint8_t loop_count __maybe_unused)
653 {
654 	/*
655 	 * Spectre-BHB has only been analyzed for AArch64 so far. For
656 	 * AArch32 fall back to the Spectre-V2 workaround which is likely
657 	 * to work even if perhaps a bit more expensive than a more
658 	 * optimized workaround.
659 	 */
660 #ifdef ARM64
661 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
662 	struct thread_core_local *cl = (void *)thread_user_kdata_page;
663 
664 	cl[get_core_pos()].bhb_loop_count = loop_count;
665 #endif
666 	thread_get_core_local()->bhb_loop_count = loop_count;
667 
668 	DMSG("Spectre-BHB CVE-2022-23960 workaround enabled with \"K\" = %u",
669 	     loop_count);
670 
671 	return (vaddr_t)thread_excp_vect_wa_spectre_bhb;
672 #else
673 	return select_vector_wa_spectre_v2();
674 #endif
675 }
676 #endif
677 
678 static vaddr_t get_excp_vect(void)
679 {
680 #ifdef CFG_CORE_WORKAROUND_SPECTRE_BP_SEC
681 	uint32_t midr = read_midr();
682 	uint8_t vers = 0;
683 
684 	if (get_midr_implementer(midr) != MIDR_IMPLEMENTER_ARM)
685 		return (vaddr_t)thread_excp_vect;
686 	/*
687 	 * Variant rx, Revision py, for instance
688 	 * Variant 2 Revision 0 = r2p0 = 0x20
689 	 */
690 	vers = (get_midr_variant(midr) << 4) | get_midr_revision(midr);
691 
692 	/*
693 	 * Spectre-V2 (CVE-2017-5715) software workarounds covers what's
694 	 * needed for Spectre-BHB (CVE-2022-23960) too. The workaround for
695 	 * Spectre-V2 is more expensive than the one for Spectre-BHB so if
696 	 * possible select the workaround for Spectre-BHB.
697 	 */
698 	switch (get_midr_primary_part(midr)) {
699 #ifdef ARM32
700 	/* Spectre-V2 */
701 	case CORTEX_A8_PART_NUM:
702 	case CORTEX_A9_PART_NUM:
703 	case CORTEX_A17_PART_NUM:
704 #endif
705 	/* Spectre-V2 */
706 	case CORTEX_A57_PART_NUM:
707 	case CORTEX_A73_PART_NUM:
708 	case CORTEX_A75_PART_NUM:
709 		return select_vector_wa_spectre_v2();
710 #ifdef ARM32
711 	/* Spectre-V2 */
712 	case CORTEX_A15_PART_NUM:
713 		return (vaddr_t)thread_excp_vect_wa_a15_spectre_v2;
714 #endif
715 	/*
716 	 * Spectre-V2 for vers < r1p0
717 	 * Spectre-BHB for vers >= r1p0
718 	 */
719 	case CORTEX_A72_PART_NUM:
720 		if (vers < 0x10)
721 			return select_vector_wa_spectre_v2();
722 		return select_vector_wa_spectre_bhb(8);
723 
724 	/*
725 	 * Doing the more safe but expensive Spectre-V2 workaround for CPUs
726 	 * still being researched on the best mitigation sequence.
727 	 */
728 	case CORTEX_A65_PART_NUM:
729 	case CORTEX_A65AE_PART_NUM:
730 	case NEOVERSE_E1_PART_NUM:
731 		return select_vector_wa_spectre_v2();
732 
733 	/* Spectre-BHB */
734 	case CORTEX_A76_PART_NUM:
735 	case CORTEX_A76AE_PART_NUM:
736 	case CORTEX_A77_PART_NUM:
737 		return select_vector_wa_spectre_bhb(24);
738 	case CORTEX_A78_PART_NUM:
739 	case CORTEX_A78AE_PART_NUM:
740 	case CORTEX_A78C_PART_NUM:
741 	case CORTEX_A710_PART_NUM:
742 	case CORTEX_X1_PART_NUM:
743 	case CORTEX_X2_PART_NUM:
744 		return select_vector_wa_spectre_bhb(32);
745 	case NEOVERSE_N1_PART_NUM:
746 		return select_vector_wa_spectre_bhb(24);
747 	case NEOVERSE_N2_PART_NUM:
748 	case NEOVERSE_V1_PART_NUM:
749 		return select_vector_wa_spectre_bhb(32);
750 
751 	default:
752 		return (vaddr_t)thread_excp_vect;
753 	}
754 #endif /*CFG_CORE_WORKAROUND_SPECTRE_BP_SEC*/
755 
756 	return (vaddr_t)thread_excp_vect;
757 }
758 
759 void thread_init_per_cpu(void)
760 {
761 #ifdef ARM32
762 	struct thread_core_local *l = thread_get_core_local();
763 
764 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
765 	/* Initialize secure monitor */
766 	sm_init(l->tmp_stack_va_end + STACK_TMP_OFFS);
767 #endif
768 	thread_set_irq_sp(l->tmp_stack_va_end);
769 	thread_set_fiq_sp(l->tmp_stack_va_end);
770 	thread_set_abt_sp((vaddr_t)l);
771 	thread_set_und_sp((vaddr_t)l);
772 #endif
773 
774 	thread_init_vbar(get_excp_vect());
775 
776 #ifdef CFG_FTRACE_SUPPORT
777 	/*
778 	 * Enable accesses to frequency register and physical counter
779 	 * register in EL0/PL0 required for timestamping during
780 	 * function tracing.
781 	 */
782 	write_cntkctl(read_cntkctl() | CNTKCTL_PL0PCTEN);
783 #endif
784 }
785 
786 #ifdef CFG_WITH_VFP
787 uint32_t thread_kernel_enable_vfp(void)
788 {
789 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
790 	struct thread_ctx *thr = threads + thread_get_id();
791 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
792 
793 	assert(!vfp_is_enabled());
794 
795 	if (!thr->vfp_state.ns_saved) {
796 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
797 					  true /*force_save*/);
798 		thr->vfp_state.ns_saved = true;
799 	} else if (thr->vfp_state.sec_lazy_saved &&
800 		   !thr->vfp_state.sec_saved) {
801 		/*
802 		 * This happens when we're handling an abort while the
803 		 * thread was using the VFP state.
804 		 */
805 		vfp_lazy_save_state_final(&thr->vfp_state.sec,
806 					  false /*!force_save*/);
807 		thr->vfp_state.sec_saved = true;
808 	} else if (tuv && tuv->lazy_saved && !tuv->saved) {
809 		/*
810 		 * This can happen either during syscall or abort
811 		 * processing (while processing a syscall).
812 		 */
813 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
814 		tuv->saved = true;
815 	}
816 
817 	vfp_enable();
818 	return exceptions;
819 }
820 
821 void thread_kernel_disable_vfp(uint32_t state)
822 {
823 	uint32_t exceptions;
824 
825 	assert(vfp_is_enabled());
826 
827 	vfp_disable();
828 	exceptions = thread_get_exceptions();
829 	assert(exceptions & THREAD_EXCP_FOREIGN_INTR);
830 	exceptions &= ~THREAD_EXCP_FOREIGN_INTR;
831 	exceptions |= state & THREAD_EXCP_FOREIGN_INTR;
832 	thread_set_exceptions(exceptions);
833 }
834 
835 void thread_kernel_save_vfp(void)
836 {
837 	struct thread_ctx *thr = threads + thread_get_id();
838 
839 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
840 	if (vfp_is_enabled()) {
841 		vfp_lazy_save_state_init(&thr->vfp_state.sec);
842 		thr->vfp_state.sec_lazy_saved = true;
843 	}
844 }
845 
846 void thread_kernel_restore_vfp(void)
847 {
848 	struct thread_ctx *thr = threads + thread_get_id();
849 
850 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
851 	assert(!vfp_is_enabled());
852 	if (thr->vfp_state.sec_lazy_saved) {
853 		vfp_lazy_restore_state(&thr->vfp_state.sec,
854 				       thr->vfp_state.sec_saved);
855 		thr->vfp_state.sec_saved = false;
856 		thr->vfp_state.sec_lazy_saved = false;
857 	}
858 }
859 
860 void thread_user_enable_vfp(struct thread_user_vfp_state *uvfp)
861 {
862 	struct thread_ctx *thr = threads + thread_get_id();
863 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
864 
865 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
866 	assert(!vfp_is_enabled());
867 
868 	if (!thr->vfp_state.ns_saved) {
869 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
870 					  true /*force_save*/);
871 		thr->vfp_state.ns_saved = true;
872 	} else if (tuv && uvfp != tuv) {
873 		if (tuv->lazy_saved && !tuv->saved) {
874 			vfp_lazy_save_state_final(&tuv->vfp,
875 						  false /*!force_save*/);
876 			tuv->saved = true;
877 		}
878 	}
879 
880 	if (uvfp->lazy_saved)
881 		vfp_lazy_restore_state(&uvfp->vfp, uvfp->saved);
882 	uvfp->lazy_saved = false;
883 	uvfp->saved = false;
884 
885 	thr->vfp_state.uvfp = uvfp;
886 	vfp_enable();
887 }
888 
889 void thread_user_save_vfp(void)
890 {
891 	struct thread_ctx *thr = threads + thread_get_id();
892 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
893 
894 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
895 	if (!vfp_is_enabled())
896 		return;
897 
898 	assert(tuv && !tuv->lazy_saved && !tuv->saved);
899 	vfp_lazy_save_state_init(&tuv->vfp);
900 	tuv->lazy_saved = true;
901 }
902 
903 void thread_user_clear_vfp(struct user_mode_ctx *uctx)
904 {
905 	struct thread_user_vfp_state *uvfp = &uctx->vfp;
906 	struct thread_ctx *thr = threads + thread_get_id();
907 
908 	if (uvfp == thr->vfp_state.uvfp)
909 		thr->vfp_state.uvfp = NULL;
910 	uvfp->lazy_saved = false;
911 	uvfp->saved = false;
912 }
913 #endif /*CFG_WITH_VFP*/
914 
915 #ifdef ARM32
916 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
917 {
918 	uint32_t s;
919 
920 	if (!is_32bit)
921 		return false;
922 
923 	s = read_cpsr();
924 	s &= ~(CPSR_MODE_MASK | CPSR_T | CPSR_IT_MASK1 | CPSR_IT_MASK2);
925 	s |= CPSR_MODE_USR;
926 	if (entry_func & 1)
927 		s |= CPSR_T;
928 	*spsr = s;
929 	return true;
930 }
931 #endif
932 
933 #ifdef ARM64
934 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
935 {
936 	uint32_t s;
937 
938 	if (is_32bit) {
939 		s = read_daif() & (SPSR_32_AIF_MASK << SPSR_32_AIF_SHIFT);
940 		s |= SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT;
941 		s |= (entry_func & SPSR_32_T_MASK) << SPSR_32_T_SHIFT;
942 	} else {
943 		s = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
944 	}
945 
946 	*spsr = s;
947 	return true;
948 }
949 #endif
950 
951 static void set_ctx_regs(struct thread_ctx_regs *regs, unsigned long a0,
952 			 unsigned long a1, unsigned long a2, unsigned long a3,
953 			 unsigned long user_sp, unsigned long entry_func,
954 			 uint32_t spsr,
955 			 struct thread_pauth_keys *keys __maybe_unused)
956 {
957 	/*
958 	 * First clear all registers to avoid leaking information from
959 	 * other TAs or even the Core itself.
960 	 */
961 	*regs = (struct thread_ctx_regs){ };
962 #ifdef ARM32
963 	regs->r0 = a0;
964 	regs->r1 = a1;
965 	regs->r2 = a2;
966 	regs->r3 = a3;
967 	regs->usr_sp = user_sp;
968 	regs->pc = entry_func;
969 	regs->cpsr = spsr;
970 #endif
971 #ifdef ARM64
972 	regs->x[0] = a0;
973 	regs->x[1] = a1;
974 	regs->x[2] = a2;
975 	regs->x[3] = a3;
976 	regs->sp = user_sp;
977 	regs->pc = entry_func;
978 	regs->cpsr = spsr;
979 	regs->x[13] = user_sp;	/* Used when running TA in Aarch32 */
980 	regs->sp = user_sp;	/* Used when running TA in Aarch64 */
981 #ifdef CFG_TA_PAUTH
982 	assert(keys);
983 	regs->apiakey_hi = keys->apia_hi;
984 	regs->apiakey_lo = keys->apia_lo;
985 #endif
986 	/* Set frame pointer (user stack can't be unwound past this point) */
987 	regs->x[29] = 0;
988 #endif
989 }
990 
991 static struct thread_pauth_keys *thread_get_pauth_keys(void)
992 {
993 #if defined(CFG_TA_PAUTH)
994 	struct ts_session *s = ts_get_current_session();
995 	/* Only user TA's support the PAUTH keys */
996 	struct user_ta_ctx *utc = to_user_ta_ctx(s->ctx);
997 
998 	return &utc->uctx.keys;
999 #else
1000 	return NULL;
1001 #endif
1002 }
1003 
1004 uint32_t thread_enter_user_mode(unsigned long a0, unsigned long a1,
1005 		unsigned long a2, unsigned long a3, unsigned long user_sp,
1006 		unsigned long entry_func, bool is_32bit,
1007 		uint32_t *exit_status0, uint32_t *exit_status1)
1008 {
1009 	uint32_t spsr = 0;
1010 	uint32_t exceptions = 0;
1011 	uint32_t rc = 0;
1012 	struct thread_ctx_regs *regs = NULL;
1013 	struct thread_pauth_keys *keys = NULL;
1014 
1015 	tee_ta_update_session_utime_resume();
1016 
1017 	keys = thread_get_pauth_keys();
1018 
1019 	/* Derive SPSR from current CPSR/PSTATE readout. */
1020 	if (!get_spsr(is_32bit, entry_func, &spsr)) {
1021 		*exit_status0 = 1; /* panic */
1022 		*exit_status1 = 0xbadbadba;
1023 		return 0;
1024 	}
1025 
1026 	exceptions = thread_mask_exceptions(THREAD_EXCP_ALL);
1027 	/*
1028 	 * We're using the per thread location of saved context registers
1029 	 * for temporary storage. Now that exceptions are masked they will
1030 	 * not be used for any thing else until they are eventually
1031 	 * unmasked when user mode has been entered.
1032 	 */
1033 	regs = thread_get_ctx_regs();
1034 	set_ctx_regs(regs, a0, a1, a2, a3, user_sp, entry_func, spsr, keys);
1035 	rc = __thread_enter_user_mode(regs, exit_status0, exit_status1);
1036 	thread_unmask_exceptions(exceptions);
1037 	return rc;
1038 }
1039 
1040 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
1041 void thread_get_user_kcode(struct mobj **mobj, size_t *offset,
1042 			   vaddr_t *va, size_t *sz)
1043 {
1044 	core_mmu_get_user_va_range(va, NULL);
1045 	*mobj = mobj_tee_ram_rx;
1046 	*sz = thread_user_kcode_size;
1047 	*offset = thread_user_kcode_va - (vaddr_t)mobj_get_va(*mobj, 0, *sz);
1048 }
1049 #endif
1050 
1051 #if defined(CFG_CORE_UNMAP_CORE_AT_EL0) && \
1052 	defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
1053 void thread_get_user_kdata(struct mobj **mobj, size_t *offset,
1054 			   vaddr_t *va, size_t *sz)
1055 {
1056 	vaddr_t v;
1057 
1058 	core_mmu_get_user_va_range(&v, NULL);
1059 	*va = v + thread_user_kcode_size;
1060 	*mobj = mobj_tee_ram_rw;
1061 	*sz = sizeof(thread_user_kdata_page);
1062 	*offset = (vaddr_t)thread_user_kdata_page -
1063 		  (vaddr_t)mobj_get_va(*mobj, 0, *sz);
1064 }
1065 #endif
1066 
1067 static void setup_unwind_user_mode(struct thread_scall_regs *regs)
1068 {
1069 #ifdef ARM32
1070 	regs->lr = (uintptr_t)thread_unwind_user_mode;
1071 	regs->spsr = read_cpsr();
1072 #endif
1073 #ifdef ARM64
1074 	regs->elr = (uintptr_t)thread_unwind_user_mode;
1075 	regs->spsr = SPSR_64(SPSR_64_MODE_EL1, SPSR_64_MODE_SP_EL0, 0);
1076 	regs->spsr |= read_daif();
1077 	/*
1078 	 * Regs is the value of stack pointer before calling the SVC
1079 	 * handler.  By the addition matches for the reserved space at the
1080 	 * beginning of el0_sync_svc(). This prepares the stack when
1081 	 * returning to thread_unwind_user_mode instead of a normal
1082 	 * exception return.
1083 	 */
1084 	regs->sp_el0 = (uint64_t)(regs + 1);
1085 #endif
1086 }
1087 
1088 static void gprof_set_status(struct ts_session *s __maybe_unused,
1089 			     enum ts_gprof_status status __maybe_unused)
1090 {
1091 #ifdef CFG_TA_GPROF_SUPPORT
1092 	if (s->ctx->ops->gprof_set_status)
1093 		s->ctx->ops->gprof_set_status(status);
1094 #endif
1095 }
1096 
1097 /*
1098  * Note: this function is weak just to make it possible to exclude it from
1099  * the unpaged area.
1100  */
1101 void __weak thread_scall_handler(struct thread_scall_regs *regs)
1102 {
1103 	struct ts_session *sess = NULL;
1104 	uint32_t state = 0;
1105 
1106 	/* Enable native interrupts */
1107 	state = thread_get_exceptions();
1108 	thread_unmask_exceptions(state & ~THREAD_EXCP_NATIVE_INTR);
1109 
1110 	thread_user_save_vfp();
1111 
1112 	sess = ts_get_current_session();
1113 	/*
1114 	 * User mode service has just entered kernel mode, suspend gprof
1115 	 * collection until we're about to switch back again.
1116 	 */
1117 	gprof_set_status(sess, TS_GPROF_SUSPEND);
1118 
1119 	/* Restore foreign interrupts which are disabled on exception entry */
1120 	thread_restore_foreign_intr();
1121 
1122 	assert(sess && sess->handle_scall);
1123 	if (sess->handle_scall(regs)) {
1124 		/* We're about to switch back to user mode */
1125 		gprof_set_status(sess, TS_GPROF_RESUME);
1126 	} else {
1127 		/* We're returning from __thread_enter_user_mode() */
1128 		setup_unwind_user_mode(regs);
1129 	}
1130 }
1131 
1132 #ifdef CFG_WITH_ARM_TRUSTED_FW
1133 /*
1134  * These five functions are __weak to allow platforms to override them if
1135  * needed.
1136  */
1137 unsigned long __weak thread_cpu_off_handler(unsigned long a0 __unused,
1138 					    unsigned long a1 __unused)
1139 {
1140 	return 0;
1141 }
1142 DECLARE_KEEP_PAGER(thread_cpu_off_handler);
1143 
1144 unsigned long __weak thread_cpu_suspend_handler(unsigned long a0 __unused,
1145 						unsigned long a1 __unused)
1146 {
1147 	return 0;
1148 }
1149 DECLARE_KEEP_PAGER(thread_cpu_suspend_handler);
1150 
1151 unsigned long __weak thread_cpu_resume_handler(unsigned long a0 __unused,
1152 					       unsigned long a1 __unused)
1153 {
1154 	return 0;
1155 }
1156 DECLARE_KEEP_PAGER(thread_cpu_resume_handler);
1157 
1158 unsigned long __weak thread_system_off_handler(unsigned long a0 __unused,
1159 					       unsigned long a1 __unused)
1160 {
1161 	return 0;
1162 }
1163 DECLARE_KEEP_PAGER(thread_system_off_handler);
1164 
1165 unsigned long __weak thread_system_reset_handler(unsigned long a0 __unused,
1166 						 unsigned long a1 __unused)
1167 {
1168 	return 0;
1169 }
1170 DECLARE_KEEP_PAGER(thread_system_reset_handler);
1171 #endif /*CFG_WITH_ARM_TRUSTED_FW*/
1172 
1173 #ifdef CFG_CORE_WORKAROUND_ARM_NMFI
1174 void __noreturn interrupt_main_handler(void)
1175 {
1176 	/*
1177 	 * Note: overrides the default implementation of this function so that
1178 	 * if there would be another handler defined there would be duplicate
1179 	 * symbol error during linking.
1180 	 */
1181 	panic("Secure interrupt received but it is not supported");
1182 }
1183 #endif
1184