xref: /optee_os/core/arch/arm/kernel/thread.c (revision c4e8be261d31dd4937f0ce93a94267a032aa4f0a)
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 <keep.h>
12 #include <kernel/asan.h>
13 #include <kernel/lockdep.h>
14 #include <kernel/misc.h>
15 #include <kernel/msg_param.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 <mm/core_memprot.h>
22 #include <mm/mobj.h>
23 #include <mm/tee_mm.h>
24 #include <mm/tee_mmu.h>
25 #include <mm/tee_pager.h>
26 #include <optee_msg.h>
27 #include <optee_rpc_cmd.h>
28 #include <smccc.h>
29 #include <sm/optee_smc.h>
30 #include <sm/sm.h>
31 #include <tee/tee_cryp_utl.h>
32 #include <tee/tee_fs_rpc.h>
33 #include <trace.h>
34 #include <util.h>
35 
36 #include "thread_private.h"
37 
38 #ifdef CFG_WITH_ARM_TRUSTED_FW
39 #define STACK_TMP_OFFS		0
40 #else
41 #define STACK_TMP_OFFS		SM_STACK_TMP_RESERVE_SIZE
42 #endif
43 
44 
45 #ifdef ARM32
46 #ifdef CFG_CORE_SANITIZE_KADDRESS
47 #define STACK_TMP_SIZE		(3072 + STACK_TMP_OFFS)
48 #else
49 #define STACK_TMP_SIZE		(1536 + STACK_TMP_OFFS)
50 #endif
51 #define STACK_THREAD_SIZE	8192
52 
53 #ifdef CFG_CORE_SANITIZE_KADDRESS
54 #define STACK_ABT_SIZE		3072
55 #else
56 #define STACK_ABT_SIZE		2048
57 #endif
58 
59 #endif /*ARM32*/
60 
61 #ifdef ARM64
62 #define STACK_TMP_SIZE		(2048 + STACK_TMP_OFFS)
63 #define STACK_THREAD_SIZE	8192
64 
65 #if TRACE_LEVEL > 0
66 #define STACK_ABT_SIZE		3072
67 #else
68 #define STACK_ABT_SIZE		1024
69 #endif
70 #endif /*ARM64*/
71 
72 struct thread_ctx threads[CFG_NUM_THREADS];
73 
74 struct thread_core_local thread_core_local[CFG_TEE_CORE_NB_CORE] __nex_bss;
75 
76 #ifdef CFG_WITH_STACK_CANARIES
77 #ifdef ARM32
78 #define STACK_CANARY_SIZE	(4 * sizeof(uint32_t))
79 #endif
80 #ifdef ARM64
81 #define STACK_CANARY_SIZE	(8 * sizeof(uint32_t))
82 #endif
83 #define START_CANARY_VALUE	0xdededede
84 #define END_CANARY_VALUE	0xabababab
85 #define GET_START_CANARY(name, stack_num) name[stack_num][0]
86 #define GET_END_CANARY(name, stack_num) \
87 	name[stack_num][sizeof(name[stack_num]) / sizeof(uint32_t) - 1]
88 #else
89 #define STACK_CANARY_SIZE	0
90 #endif
91 
92 #define DECLARE_STACK(name, num_stacks, stack_size, linkage) \
93 linkage uint32_t name[num_stacks] \
94 		[ROUNDUP(stack_size + STACK_CANARY_SIZE, STACK_ALIGNMENT) / \
95 		sizeof(uint32_t)] \
96 		__attribute__((section(".nozi_stack." # name), \
97 			       aligned(STACK_ALIGNMENT)))
98 
99 #define STACK_SIZE(stack) (sizeof(stack) - STACK_CANARY_SIZE / 2)
100 
101 #define GET_STACK(stack) \
102 	((vaddr_t)(stack) + STACK_SIZE(stack))
103 
104 DECLARE_STACK(stack_tmp, CFG_TEE_CORE_NB_CORE, STACK_TMP_SIZE, static);
105 DECLARE_STACK(stack_abt, CFG_TEE_CORE_NB_CORE, STACK_ABT_SIZE, static);
106 #ifndef CFG_WITH_PAGER
107 DECLARE_STACK(stack_thread, CFG_NUM_THREADS, STACK_THREAD_SIZE, static);
108 #endif
109 
110 const void *stack_tmp_export = (uint8_t *)stack_tmp + sizeof(stack_tmp[0]) -
111 			       (STACK_TMP_OFFS + STACK_CANARY_SIZE / 2);
112 const uint32_t stack_tmp_stride = sizeof(stack_tmp[0]);
113 
114 /*
115  * These stack setup info are required by secondary boot cores before they
116  * each locally enable the pager (the mmu). Hence kept in pager sections.
117  */
118 KEEP_PAGER(stack_tmp_export);
119 KEEP_PAGER(stack_tmp_stride);
120 
121 thread_smc_handler_t thread_std_smc_handler_ptr __nex_bss;
122 static thread_smc_handler_t thread_fast_smc_handler_ptr __nex_bss;
123 thread_nintr_handler_t thread_nintr_handler_ptr __nex_bss;
124 thread_pm_handler_t thread_cpu_on_handler_ptr __nex_bss;
125 thread_pm_handler_t thread_cpu_off_handler_ptr __nex_bss;
126 thread_pm_handler_t thread_cpu_suspend_handler_ptr __nex_bss;
127 thread_pm_handler_t thread_cpu_resume_handler_ptr __nex_bss;
128 thread_pm_handler_t thread_system_off_handler_ptr __nex_bss;
129 thread_pm_handler_t thread_system_reset_handler_ptr __nex_bss;
130 
131 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
132 static vaddr_t thread_user_kcode_va __nex_bss;
133 long thread_user_kcode_offset __nex_bss;
134 static size_t thread_user_kcode_size __nex_bss;
135 #endif
136 
137 #if defined(CFG_CORE_UNMAP_CORE_AT_EL0) && \
138 	defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
139 long thread_user_kdata_sp_offset __nex_bss;
140 static uint8_t thread_user_kdata_page[
141 	ROUNDUP(sizeof(thread_core_local), SMALL_PAGE_SIZE)]
142 	__aligned(SMALL_PAGE_SIZE)
143 #ifndef CFG_VIRTUALIZATION
144 	__section(".nozi.kdata_page");
145 #else
146 	__section(".nex_nozi.kdata_page");
147 #endif
148 #endif
149 
150 static unsigned int thread_global_lock __nex_bss = SPINLOCK_UNLOCK;
151 static bool thread_prealloc_rpc_cache;
152 
153 static unsigned int thread_rpc_pnum;
154 
155 static void init_canaries(void)
156 {
157 #ifdef CFG_WITH_STACK_CANARIES
158 	size_t n;
159 #define INIT_CANARY(name)						\
160 	for (n = 0; n < ARRAY_SIZE(name); n++) {			\
161 		uint32_t *start_canary = &GET_START_CANARY(name, n);	\
162 		uint32_t *end_canary = &GET_END_CANARY(name, n);	\
163 									\
164 		*start_canary = START_CANARY_VALUE;			\
165 		*end_canary = END_CANARY_VALUE;				\
166 		DMSG("#Stack canaries for %s[%zu] with top at %p\n",	\
167 			#name, n, (void *)(end_canary - 1));		\
168 		DMSG("watch *%p\n", (void *)end_canary);		\
169 	}
170 
171 	INIT_CANARY(stack_tmp);
172 	INIT_CANARY(stack_abt);
173 #ifndef CFG_WITH_PAGER
174 	INIT_CANARY(stack_thread);
175 #endif
176 #endif/*CFG_WITH_STACK_CANARIES*/
177 }
178 
179 #define CANARY_DIED(stack, loc, n) \
180 	do { \
181 		EMSG_RAW("Dead canary at %s of '%s[%zu]'", #loc, #stack, n); \
182 		panic(); \
183 	} while (0)
184 
185 void thread_check_canaries(void)
186 {
187 #ifdef CFG_WITH_STACK_CANARIES
188 	size_t n;
189 
190 	for (n = 0; n < ARRAY_SIZE(stack_tmp); n++) {
191 		if (GET_START_CANARY(stack_tmp, n) != START_CANARY_VALUE)
192 			CANARY_DIED(stack_tmp, start, n);
193 		if (GET_END_CANARY(stack_tmp, n) != END_CANARY_VALUE)
194 			CANARY_DIED(stack_tmp, end, n);
195 	}
196 
197 	for (n = 0; n < ARRAY_SIZE(stack_abt); n++) {
198 		if (GET_START_CANARY(stack_abt, n) != START_CANARY_VALUE)
199 			CANARY_DIED(stack_abt, start, n);
200 		if (GET_END_CANARY(stack_abt, n) != END_CANARY_VALUE)
201 			CANARY_DIED(stack_abt, end, n);
202 
203 	}
204 #ifndef CFG_WITH_PAGER
205 	for (n = 0; n < ARRAY_SIZE(stack_thread); n++) {
206 		if (GET_START_CANARY(stack_thread, n) != START_CANARY_VALUE)
207 			CANARY_DIED(stack_thread, start, n);
208 		if (GET_END_CANARY(stack_thread, n) != END_CANARY_VALUE)
209 			CANARY_DIED(stack_thread, end, n);
210 	}
211 #endif
212 #endif/*CFG_WITH_STACK_CANARIES*/
213 }
214 
215 static void lock_global(void)
216 {
217 	cpu_spin_lock(&thread_global_lock);
218 }
219 
220 static void unlock_global(void)
221 {
222 	cpu_spin_unlock(&thread_global_lock);
223 }
224 
225 #ifdef ARM32
226 uint32_t thread_get_exceptions(void)
227 {
228 	uint32_t cpsr = read_cpsr();
229 
230 	return (cpsr >> CPSR_F_SHIFT) & THREAD_EXCP_ALL;
231 }
232 
233 void thread_set_exceptions(uint32_t exceptions)
234 {
235 	uint32_t cpsr = read_cpsr();
236 
237 	/* Foreign interrupts must not be unmasked while holding a spinlock */
238 	if (!(exceptions & THREAD_EXCP_FOREIGN_INTR))
239 		assert_have_no_spinlock();
240 
241 	cpsr &= ~(THREAD_EXCP_ALL << CPSR_F_SHIFT);
242 	cpsr |= ((exceptions & THREAD_EXCP_ALL) << CPSR_F_SHIFT);
243 	write_cpsr(cpsr);
244 }
245 #endif /*ARM32*/
246 
247 #ifdef ARM64
248 uint32_t thread_get_exceptions(void)
249 {
250 	uint32_t daif = read_daif();
251 
252 	return (daif >> DAIF_F_SHIFT) & THREAD_EXCP_ALL;
253 }
254 
255 void thread_set_exceptions(uint32_t exceptions)
256 {
257 	uint32_t daif = read_daif();
258 
259 	/* Foreign interrupts must not be unmasked while holding a spinlock */
260 	if (!(exceptions & THREAD_EXCP_FOREIGN_INTR))
261 		assert_have_no_spinlock();
262 
263 	daif &= ~(THREAD_EXCP_ALL << DAIF_F_SHIFT);
264 	daif |= ((exceptions & THREAD_EXCP_ALL) << DAIF_F_SHIFT);
265 	write_daif(daif);
266 }
267 #endif /*ARM64*/
268 
269 uint32_t thread_mask_exceptions(uint32_t exceptions)
270 {
271 	uint32_t state = thread_get_exceptions();
272 
273 	thread_set_exceptions(state | (exceptions & THREAD_EXCP_ALL));
274 	return state;
275 }
276 
277 void thread_unmask_exceptions(uint32_t state)
278 {
279 	thread_set_exceptions(state & THREAD_EXCP_ALL);
280 }
281 
282 
283 struct thread_core_local *thread_get_core_local(void)
284 {
285 	uint32_t cpu_id = get_core_pos();
286 
287 	/*
288 	 * Foreign interrupts must be disabled before playing with core_local
289 	 * since we otherwise may be rescheduled to a different core in the
290 	 * middle of this function.
291 	 */
292 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
293 
294 	assert(cpu_id < CFG_TEE_CORE_NB_CORE);
295 	return &thread_core_local[cpu_id];
296 }
297 
298 static void thread_lazy_save_ns_vfp(void)
299 {
300 #ifdef CFG_WITH_VFP
301 	struct thread_ctx *thr = threads + thread_get_id();
302 
303 	thr->vfp_state.ns_saved = false;
304 	vfp_lazy_save_state_init(&thr->vfp_state.ns);
305 #endif /*CFG_WITH_VFP*/
306 }
307 
308 static void thread_lazy_restore_ns_vfp(void)
309 {
310 #ifdef CFG_WITH_VFP
311 	struct thread_ctx *thr = threads + thread_get_id();
312 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
313 
314 	assert(!thr->vfp_state.sec_lazy_saved && !thr->vfp_state.sec_saved);
315 
316 	if (tuv && tuv->lazy_saved && !tuv->saved) {
317 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
318 		tuv->saved = true;
319 	}
320 
321 	vfp_lazy_restore_state(&thr->vfp_state.ns, thr->vfp_state.ns_saved);
322 	thr->vfp_state.ns_saved = false;
323 #endif /*CFG_WITH_VFP*/
324 }
325 
326 #ifdef ARM32
327 static void init_regs(struct thread_ctx *thread,
328 		struct thread_smc_args *args)
329 {
330 	thread->regs.pc = (uint32_t)thread_std_smc_entry;
331 
332 	/*
333 	 * Stdcalls starts in SVC mode with masked foreign interrupts, masked
334 	 * Asynchronous abort and unmasked native interrupts.
335 	 */
336 	thread->regs.cpsr = read_cpsr() & ARM32_CPSR_E;
337 	thread->regs.cpsr |= CPSR_MODE_SVC | CPSR_A |
338 			(THREAD_EXCP_FOREIGN_INTR << ARM32_CPSR_F_SHIFT);
339 	/* Enable thumb mode if it's a thumb instruction */
340 	if (thread->regs.pc & 1)
341 		thread->regs.cpsr |= CPSR_T;
342 	/* Reinitialize stack pointer */
343 	thread->regs.svc_sp = thread->stack_va_end;
344 
345 	/*
346 	 * Copy arguments into context. This will make the
347 	 * arguments appear in r0-r7 when thread is started.
348 	 */
349 	thread->regs.r0 = args->a0;
350 	thread->regs.r1 = args->a1;
351 	thread->regs.r2 = args->a2;
352 	thread->regs.r3 = args->a3;
353 	thread->regs.r4 = args->a4;
354 	thread->regs.r5 = args->a5;
355 	thread->regs.r6 = args->a6;
356 	thread->regs.r7 = args->a7;
357 }
358 #endif /*ARM32*/
359 
360 #ifdef ARM64
361 static void init_regs(struct thread_ctx *thread,
362 		struct thread_smc_args *args)
363 {
364 	thread->regs.pc = (uint64_t)thread_std_smc_entry;
365 
366 	/*
367 	 * Stdcalls starts in SVC mode with masked foreign interrupts, masked
368 	 * Asynchronous abort and unmasked native interrupts.
369 	 */
370 	thread->regs.cpsr = SPSR_64(SPSR_64_MODE_EL1, SPSR_64_MODE_SP_EL0,
371 				THREAD_EXCP_FOREIGN_INTR | DAIFBIT_ABT);
372 	/* Reinitialize stack pointer */
373 	thread->regs.sp = thread->stack_va_end;
374 
375 	/*
376 	 * Copy arguments into context. This will make the
377 	 * arguments appear in x0-x7 when thread is started.
378 	 */
379 	thread->regs.x[0] = args->a0;
380 	thread->regs.x[1] = args->a1;
381 	thread->regs.x[2] = args->a2;
382 	thread->regs.x[3] = args->a3;
383 	thread->regs.x[4] = args->a4;
384 	thread->regs.x[5] = args->a5;
385 	thread->regs.x[6] = args->a6;
386 	thread->regs.x[7] = args->a7;
387 
388 	/* Set up frame pointer as per the Aarch64 AAPCS */
389 	thread->regs.x[29] = 0;
390 }
391 #endif /*ARM64*/
392 
393 void thread_init_boot_thread(void)
394 {
395 	struct thread_core_local *l = thread_get_core_local();
396 
397 	thread_init_threads();
398 
399 	l->curr_thread = 0;
400 	threads[0].state = THREAD_STATE_ACTIVE;
401 }
402 
403 void thread_clr_boot_thread(void)
404 {
405 	struct thread_core_local *l = thread_get_core_local();
406 
407 	assert(l->curr_thread >= 0 && l->curr_thread < CFG_NUM_THREADS);
408 	assert(threads[l->curr_thread].state == THREAD_STATE_ACTIVE);
409 	threads[l->curr_thread].state = THREAD_STATE_FREE;
410 	l->curr_thread = -1;
411 }
412 
413 static void thread_alloc_and_run(struct thread_smc_args *args)
414 {
415 	size_t n;
416 	struct thread_core_local *l = thread_get_core_local();
417 	bool found_thread = false;
418 
419 	assert(l->curr_thread == -1);
420 
421 	lock_global();
422 
423 	for (n = 0; n < CFG_NUM_THREADS; n++) {
424 		if (threads[n].state == THREAD_STATE_FREE) {
425 			threads[n].state = THREAD_STATE_ACTIVE;
426 			found_thread = true;
427 			break;
428 		}
429 	}
430 
431 	unlock_global();
432 
433 	if (!found_thread) {
434 		args->a0 = OPTEE_SMC_RETURN_ETHREAD_LIMIT;
435 		return;
436 	}
437 
438 	l->curr_thread = n;
439 
440 	threads[n].flags = 0;
441 	init_regs(threads + n, args);
442 
443 	/* Save Hypervisor Client ID */
444 	threads[n].hyp_clnt_id = args->a7;
445 
446 	thread_lazy_save_ns_vfp();
447 	thread_resume(&threads[n].regs);
448 }
449 
450 #ifdef ARM32
451 static void copy_a0_to_a5(struct thread_ctx_regs *regs,
452 		struct thread_smc_args *args)
453 {
454 	/*
455 	 * Update returned values from RPC, values will appear in
456 	 * r0-r3 when thread is resumed.
457 	 */
458 	regs->r0 = args->a0;
459 	regs->r1 = args->a1;
460 	regs->r2 = args->a2;
461 	regs->r3 = args->a3;
462 	regs->r4 = args->a4;
463 	regs->r5 = args->a5;
464 }
465 #endif /*ARM32*/
466 
467 #ifdef ARM64
468 static void copy_a0_to_a5(struct thread_ctx_regs *regs,
469 		struct thread_smc_args *args)
470 {
471 	/*
472 	 * Update returned values from RPC, values will appear in
473 	 * x0-x3 when thread is resumed.
474 	 */
475 	regs->x[0] = args->a0;
476 	regs->x[1] = args->a1;
477 	regs->x[2] = args->a2;
478 	regs->x[3] = args->a3;
479 	regs->x[4] = args->a4;
480 	regs->x[5] = args->a5;
481 }
482 #endif /*ARM64*/
483 
484 #ifdef ARM32
485 static bool is_from_user(uint32_t cpsr)
486 {
487 	return (cpsr & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_USR;
488 }
489 #endif
490 
491 #ifdef ARM64
492 static bool is_from_user(uint32_t cpsr)
493 {
494 	if (cpsr & (SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT))
495 		return true;
496 	if (((cpsr >> SPSR_64_MODE_EL_SHIFT) & SPSR_64_MODE_EL_MASK) ==
497 	     SPSR_64_MODE_EL0)
498 		return true;
499 	return false;
500 }
501 #endif
502 
503 static bool is_user_mode(struct thread_ctx_regs *regs)
504 {
505 	return is_from_user((uint32_t)regs->cpsr);
506 }
507 
508 static void thread_resume_from_rpc(struct thread_smc_args *args)
509 {
510 	size_t n = args->a3; /* thread id */
511 	struct thread_core_local *l = thread_get_core_local();
512 	uint32_t rv = 0;
513 
514 	assert(l->curr_thread == -1);
515 
516 	lock_global();
517 
518 	if (n < CFG_NUM_THREADS &&
519 	    threads[n].state == THREAD_STATE_SUSPENDED &&
520 	    args->a7 == threads[n].hyp_clnt_id)
521 		threads[n].state = THREAD_STATE_ACTIVE;
522 	else
523 		rv = OPTEE_SMC_RETURN_ERESUME;
524 
525 	unlock_global();
526 
527 	if (rv) {
528 		args->a0 = rv;
529 		return;
530 	}
531 
532 	l->curr_thread = n;
533 
534 	if (is_user_mode(&threads[n].regs))
535 		tee_ta_update_session_utime_resume();
536 
537 	if (threads[n].have_user_map)
538 		core_mmu_set_user_map(&threads[n].user_map);
539 
540 	/*
541 	 * Return from RPC to request service of a foreign interrupt must not
542 	 * get parameters from non-secure world.
543 	 */
544 	if (threads[n].flags & THREAD_FLAGS_COPY_ARGS_ON_RETURN) {
545 		copy_a0_to_a5(&threads[n].regs, args);
546 		threads[n].flags &= ~THREAD_FLAGS_COPY_ARGS_ON_RETURN;
547 	}
548 
549 	thread_lazy_save_ns_vfp();
550 	thread_resume(&threads[n].regs);
551 }
552 
553 void thread_handle_fast_smc(struct thread_smc_args *args)
554 {
555 	thread_check_canaries();
556 	thread_fast_smc_handler_ptr(args);
557 	/* Fast handlers must not unmask any exceptions */
558 	assert(thread_get_exceptions() == THREAD_EXCP_ALL);
559 }
560 
561 void thread_handle_std_smc(struct thread_smc_args *args)
562 {
563 	thread_check_canaries();
564 
565 	if (args->a0 == OPTEE_SMC_CALL_RETURN_FROM_RPC)
566 		thread_resume_from_rpc(args);
567 	else
568 		thread_alloc_and_run(args);
569 }
570 
571 /**
572  * Free physical memory previously allocated with thread_rpc_alloc_arg()
573  *
574  * @cookie:	cookie received when allocating the buffer
575  */
576 static void thread_rpc_free_arg(uint64_t cookie)
577 {
578 	if (cookie) {
579 		uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
580 			OPTEE_SMC_RETURN_RPC_FREE
581 		};
582 
583 		reg_pair_from_64(cookie, rpc_args + 1, rpc_args + 2);
584 		thread_rpc(rpc_args);
585 	}
586 }
587 
588 /*
589  * Helper routine for the assembly function thread_std_smc_entry()
590  *
591  * Note: this function is weak just to make it possible to exclude it from
592  * the unpaged area.
593  */
594 void __weak __thread_std_smc_entry(struct thread_smc_args *args)
595 {
596 	thread_std_smc_handler_ptr(args);
597 
598 	if (args->a0 == OPTEE_SMC_RETURN_OK) {
599 		struct thread_ctx *thr = threads + thread_get_id();
600 
601 		tee_fs_rpc_cache_clear(&thr->tsd);
602 		if (!thread_prealloc_rpc_cache) {
603 			thread_rpc_free_arg(mobj_get_cookie(thr->rpc_mobj));
604 			mobj_free(thr->rpc_mobj);
605 			thr->rpc_arg = 0;
606 			thr->rpc_mobj = NULL;
607 		}
608 	}
609 }
610 
611 void *thread_get_tmp_sp(void)
612 {
613 	struct thread_core_local *l = thread_get_core_local();
614 
615 	return (void *)l->tmp_stack_va_end;
616 }
617 
618 #ifdef ARM64
619 vaddr_t thread_get_saved_thread_sp(void)
620 {
621 	struct thread_core_local *l = thread_get_core_local();
622 	int ct = l->curr_thread;
623 
624 	assert(ct != -1);
625 	return threads[ct].kern_sp;
626 }
627 #endif /*ARM64*/
628 
629 vaddr_t thread_stack_start(void)
630 {
631 	struct thread_ctx *thr;
632 	int ct = thread_get_id_may_fail();
633 
634 	if (ct == -1)
635 		return 0;
636 
637 	thr = threads + ct;
638 	return thr->stack_va_end - STACK_THREAD_SIZE;
639 }
640 
641 size_t thread_stack_size(void)
642 {
643 	return STACK_THREAD_SIZE;
644 }
645 
646 bool thread_is_from_abort_mode(void)
647 {
648 	struct thread_core_local *l = thread_get_core_local();
649 
650 	return (l->flags >> THREAD_CLF_SAVED_SHIFT) & THREAD_CLF_ABORT;
651 }
652 
653 #ifdef ARM32
654 bool thread_is_in_normal_mode(void)
655 {
656 	return (read_cpsr() & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_SVC;
657 }
658 #endif
659 
660 #ifdef ARM64
661 bool thread_is_in_normal_mode(void)
662 {
663 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
664 	struct thread_core_local *l = thread_get_core_local();
665 	bool ret;
666 
667 	/* If any bit in l->flags is set we're handling some exception. */
668 	ret = !l->flags;
669 	thread_unmask_exceptions(exceptions);
670 
671 	return ret;
672 }
673 #endif
674 
675 void thread_state_free(void)
676 {
677 	struct thread_core_local *l = thread_get_core_local();
678 	int ct = l->curr_thread;
679 
680 	assert(ct != -1);
681 
682 	thread_lazy_restore_ns_vfp();
683 	tee_pager_release_phys(
684 		(void *)(threads[ct].stack_va_end - STACK_THREAD_SIZE),
685 		STACK_THREAD_SIZE);
686 
687 	lock_global();
688 
689 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
690 	threads[ct].state = THREAD_STATE_FREE;
691 	threads[ct].flags = 0;
692 	l->curr_thread = -1;
693 
694 	unlock_global();
695 }
696 
697 #ifdef CFG_WITH_PAGER
698 static void release_unused_kernel_stack(struct thread_ctx *thr,
699 					uint32_t cpsr __maybe_unused)
700 {
701 #ifdef ARM64
702 	/*
703 	 * If we're from user mode then thr->regs.sp is the saved user
704 	 * stack pointer and thr->kern_sp holds the last kernel stack
705 	 * pointer. But if we're from kernel mode then thr->kern_sp isn't
706 	 * up to date so we need to read from thr->regs.sp instead.
707 	 */
708 	vaddr_t sp = is_from_user(cpsr) ?  thr->kern_sp : thr->regs.sp;
709 #else
710 	vaddr_t sp = thr->regs.svc_sp;
711 #endif
712 	vaddr_t base = thr->stack_va_end - STACK_THREAD_SIZE;
713 	size_t len = sp - base;
714 
715 	tee_pager_release_phys((void *)base, len);
716 }
717 #else
718 static void release_unused_kernel_stack(struct thread_ctx *thr __unused,
719 					uint32_t cpsr __unused)
720 {
721 }
722 #endif
723 
724 int thread_state_suspend(uint32_t flags, uint32_t cpsr, vaddr_t pc)
725 {
726 	struct thread_core_local *l = thread_get_core_local();
727 	int ct = l->curr_thread;
728 
729 	assert(ct != -1);
730 
731 	thread_check_canaries();
732 
733 	release_unused_kernel_stack(threads + ct, cpsr);
734 
735 	if (is_from_user(cpsr)) {
736 		thread_user_save_vfp();
737 		tee_ta_update_session_utime_suspend();
738 		tee_ta_gprof_sample_pc(pc);
739 	}
740 	thread_lazy_restore_ns_vfp();
741 
742 	lock_global();
743 
744 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
745 	threads[ct].flags |= flags;
746 	threads[ct].regs.cpsr = cpsr;
747 	threads[ct].regs.pc = pc;
748 	threads[ct].state = THREAD_STATE_SUSPENDED;
749 
750 	threads[ct].have_user_map = core_mmu_user_mapping_is_active();
751 	if (threads[ct].have_user_map) {
752 		core_mmu_get_user_map(&threads[ct].user_map);
753 		core_mmu_set_user_map(NULL);
754 	}
755 
756 	l->curr_thread = -1;
757 
758 	unlock_global();
759 
760 	return ct;
761 }
762 
763 #ifdef ARM32
764 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
765 {
766 	l->tmp_stack_va_end = sp;
767 	thread_set_irq_sp(sp);
768 	thread_set_fiq_sp(sp);
769 }
770 
771 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
772 {
773 	l->abt_stack_va_end = sp;
774 	thread_set_abt_sp((vaddr_t)l);
775 	thread_set_und_sp((vaddr_t)l);
776 }
777 #endif /*ARM32*/
778 
779 #ifdef ARM64
780 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
781 {
782 	/*
783 	 * We're already using the tmp stack when this function is called
784 	 * so there's no need to assign it to any stack pointer. However,
785 	 * we'll need to restore it at different times so store it here.
786 	 */
787 	l->tmp_stack_va_end = sp;
788 }
789 
790 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
791 {
792 	l->abt_stack_va_end = sp;
793 }
794 #endif /*ARM64*/
795 
796 bool thread_init_stack(uint32_t thread_id, vaddr_t sp)
797 {
798 	if (thread_id >= CFG_NUM_THREADS)
799 		return false;
800 	threads[thread_id].stack_va_end = sp;
801 	return true;
802 }
803 
804 int thread_get_id_may_fail(void)
805 {
806 	/*
807 	 * thread_get_core_local() requires foreign interrupts to be disabled
808 	 */
809 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
810 	struct thread_core_local *l = thread_get_core_local();
811 	int ct = l->curr_thread;
812 
813 	thread_unmask_exceptions(exceptions);
814 	return ct;
815 }
816 
817 int thread_get_id(void)
818 {
819 	int ct = thread_get_id_may_fail();
820 
821 	assert(ct >= 0 && ct < CFG_NUM_THREADS);
822 	return ct;
823 }
824 
825 static void init_handlers(const struct thread_handlers *handlers)
826 {
827 	thread_std_smc_handler_ptr = handlers->std_smc;
828 	thread_fast_smc_handler_ptr = handlers->fast_smc;
829 	thread_nintr_handler_ptr = handlers->nintr;
830 	thread_cpu_on_handler_ptr = handlers->cpu_on;
831 	thread_cpu_off_handler_ptr = handlers->cpu_off;
832 	thread_cpu_suspend_handler_ptr = handlers->cpu_suspend;
833 	thread_cpu_resume_handler_ptr = handlers->cpu_resume;
834 	thread_system_off_handler_ptr = handlers->system_off;
835 	thread_system_reset_handler_ptr = handlers->system_reset;
836 }
837 
838 #ifdef CFG_WITH_PAGER
839 static void init_thread_stacks(void)
840 {
841 	size_t n;
842 
843 	/*
844 	 * Allocate virtual memory for thread stacks.
845 	 */
846 	for (n = 0; n < CFG_NUM_THREADS; n++) {
847 		tee_mm_entry_t *mm;
848 		vaddr_t sp;
849 
850 		/* Find vmem for thread stack and its protection gap */
851 		mm = tee_mm_alloc(&tee_mm_vcore,
852 				  SMALL_PAGE_SIZE + STACK_THREAD_SIZE);
853 		assert(mm);
854 
855 		/* Claim eventual physical page */
856 		tee_pager_add_pages(tee_mm_get_smem(mm), tee_mm_get_size(mm),
857 				    true);
858 
859 		/* Add the area to the pager */
860 		tee_pager_add_core_area(tee_mm_get_smem(mm) + SMALL_PAGE_SIZE,
861 					tee_mm_get_bytes(mm) - SMALL_PAGE_SIZE,
862 					TEE_MATTR_PRW | TEE_MATTR_LOCKED,
863 					NULL, NULL);
864 
865 		/* init effective stack */
866 		sp = tee_mm_get_smem(mm) + tee_mm_get_bytes(mm);
867 		asan_tag_access((void *)tee_mm_get_smem(mm), (void *)sp);
868 		if (!thread_init_stack(n, sp))
869 			panic("init stack failed");
870 	}
871 }
872 #else
873 static void init_thread_stacks(void)
874 {
875 	size_t n;
876 
877 	/* Assign the thread stacks */
878 	for (n = 0; n < CFG_NUM_THREADS; n++) {
879 		if (!thread_init_stack(n, GET_STACK(stack_thread[n])))
880 			panic("thread_init_stack failed");
881 	}
882 }
883 #endif /*CFG_WITH_PAGER*/
884 
885 static void init_user_kcode(void)
886 {
887 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
888 	vaddr_t v = (vaddr_t)thread_excp_vect;
889 	vaddr_t ve = (vaddr_t)thread_excp_vect_end;
890 
891 	thread_user_kcode_va = ROUNDDOWN(v, CORE_MMU_USER_CODE_SIZE);
892 	ve = ROUNDUP(ve, CORE_MMU_USER_CODE_SIZE);
893 	thread_user_kcode_size = ve - thread_user_kcode_va;
894 
895 	core_mmu_get_user_va_range(&v, NULL);
896 	thread_user_kcode_offset = thread_user_kcode_va - v;
897 
898 #if defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
899 	/*
900 	 * When transitioning to EL0 subtract SP with this much to point to
901 	 * this special kdata page instead. SP is restored by add this much
902 	 * while transitioning back to EL1.
903 	 */
904 	v += thread_user_kcode_size;
905 	thread_user_kdata_sp_offset = (vaddr_t)thread_core_local - v;
906 #endif
907 #endif /*CFG_CORE_UNMAP_CORE_AT_EL0*/
908 }
909 
910 void thread_init_threads(void)
911 {
912 	size_t n;
913 
914 	init_thread_stacks();
915 	pgt_init();
916 
917 	mutex_lockdep_init();
918 
919 	for (n = 0; n < CFG_NUM_THREADS; n++) {
920 		TAILQ_INIT(&threads[n].tsd.sess_stack);
921 		SLIST_INIT(&threads[n].tsd.pgt_cache);
922 	}
923 
924 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++)
925 		thread_core_local[n].curr_thread = -1;
926 }
927 
928 void thread_init_primary(const struct thread_handlers *handlers)
929 {
930 	init_handlers(handlers);
931 
932 	/* Initialize canaries around the stacks */
933 	init_canaries();
934 
935 	init_user_kcode();
936 }
937 
938 static void init_sec_mon(size_t pos __maybe_unused)
939 {
940 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
941 	/* Initialize secure monitor */
942 	sm_init(GET_STACK(stack_tmp[pos]));
943 #endif
944 }
945 
946 static uint32_t __maybe_unused get_midr_implementer(uint32_t midr)
947 {
948 	return (midr >> MIDR_IMPLEMENTER_SHIFT) & MIDR_IMPLEMENTER_MASK;
949 }
950 
951 static uint32_t __maybe_unused get_midr_primary_part(uint32_t midr)
952 {
953 	return (midr >> MIDR_PRIMARY_PART_NUM_SHIFT) &
954 	       MIDR_PRIMARY_PART_NUM_MASK;
955 }
956 
957 #ifdef ARM64
958 static bool probe_workaround_available(void)
959 {
960 	int32_t r;
961 
962 	r = thread_smc(SMCCC_VERSION, 0, 0, 0);
963 	if (r < 0)
964 		return false;
965 	if (r < 0x10001)	/* compare with version 1.1 */
966 		return false;
967 
968 	/* Version >= 1.1, so SMCCC_ARCH_FEATURES is available */
969 	r = thread_smc(SMCCC_ARCH_FEATURES, SMCCC_ARCH_WORKAROUND_1, 0, 0);
970 	return r >= 0;
971 }
972 
973 static vaddr_t __maybe_unused select_vector(vaddr_t a)
974 {
975 	if (probe_workaround_available()) {
976 		DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") available",
977 		     SMCCC_ARCH_WORKAROUND_1);
978 		DMSG("SMC Workaround for CVE-2017-5715 used");
979 		return a;
980 	}
981 
982 	DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") unavailable",
983 	     SMCCC_ARCH_WORKAROUND_1);
984 	DMSG("SMC Workaround for CVE-2017-5715 not needed (if ARM-TF is up to date)");
985 	return (vaddr_t)thread_excp_vect;
986 }
987 #else
988 static vaddr_t __maybe_unused select_vector(vaddr_t a)
989 {
990 	return a;
991 }
992 #endif
993 
994 static vaddr_t get_excp_vect(void)
995 {
996 #ifdef CFG_CORE_WORKAROUND_SPECTRE_BP_SEC
997 	uint32_t midr = read_midr();
998 
999 	if (get_midr_implementer(midr) != MIDR_IMPLEMENTER_ARM)
1000 		return (vaddr_t)thread_excp_vect;
1001 
1002 	switch (get_midr_primary_part(midr)) {
1003 #ifdef ARM32
1004 	case CORTEX_A8_PART_NUM:
1005 	case CORTEX_A9_PART_NUM:
1006 	case CORTEX_A17_PART_NUM:
1007 #endif
1008 	case CORTEX_A57_PART_NUM:
1009 	case CORTEX_A72_PART_NUM:
1010 	case CORTEX_A73_PART_NUM:
1011 	case CORTEX_A75_PART_NUM:
1012 		return select_vector((vaddr_t)thread_excp_vect_workaround);
1013 #ifdef ARM32
1014 	case CORTEX_A15_PART_NUM:
1015 		return select_vector((vaddr_t)thread_excp_vect_workaround_a15);
1016 #endif
1017 	default:
1018 		return (vaddr_t)thread_excp_vect;
1019 	}
1020 #endif /*CFG_CORE_WORKAROUND_SPECTRE_BP_SEC*/
1021 
1022 	return (vaddr_t)thread_excp_vect;
1023 }
1024 
1025 void thread_init_per_cpu(void)
1026 {
1027 	size_t pos = get_core_pos();
1028 	struct thread_core_local *l = thread_get_core_local();
1029 
1030 	init_sec_mon(pos);
1031 
1032 	set_tmp_stack(l, GET_STACK(stack_tmp[pos]) - STACK_TMP_OFFS);
1033 	set_abt_stack(l, GET_STACK(stack_abt[pos]));
1034 
1035 	thread_init_vbar(get_excp_vect());
1036 }
1037 
1038 struct thread_specific_data *thread_get_tsd(void)
1039 {
1040 	return &threads[thread_get_id()].tsd;
1041 }
1042 
1043 struct thread_ctx_regs *thread_get_ctx_regs(void)
1044 {
1045 	struct thread_core_local *l = thread_get_core_local();
1046 
1047 	assert(l->curr_thread != -1);
1048 	return &threads[l->curr_thread].regs;
1049 }
1050 
1051 void thread_set_foreign_intr(bool enable)
1052 {
1053 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1054 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1055 	struct thread_core_local *l;
1056 
1057 	l = thread_get_core_local();
1058 
1059 	assert(l->curr_thread != -1);
1060 
1061 	if (enable) {
1062 		threads[l->curr_thread].flags |=
1063 					THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1064 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1065 	} else {
1066 		/*
1067 		 * No need to disable foreign interrupts here since they're
1068 		 * already disabled above.
1069 		 */
1070 		threads[l->curr_thread].flags &=
1071 					~THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1072 	}
1073 }
1074 
1075 void thread_restore_foreign_intr(void)
1076 {
1077 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1078 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1079 	struct thread_core_local *l;
1080 
1081 	l = thread_get_core_local();
1082 
1083 	assert(l->curr_thread != -1);
1084 
1085 	if (threads[l->curr_thread].flags & THREAD_FLAGS_FOREIGN_INTR_ENABLE)
1086 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1087 }
1088 
1089 #ifdef CFG_WITH_VFP
1090 uint32_t thread_kernel_enable_vfp(void)
1091 {
1092 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1093 	struct thread_ctx *thr = threads + thread_get_id();
1094 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1095 
1096 	assert(!vfp_is_enabled());
1097 
1098 	if (!thr->vfp_state.ns_saved) {
1099 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1100 					  true /*force_save*/);
1101 		thr->vfp_state.ns_saved = true;
1102 	} else if (thr->vfp_state.sec_lazy_saved &&
1103 		   !thr->vfp_state.sec_saved) {
1104 		/*
1105 		 * This happens when we're handling an abort while the
1106 		 * thread was using the VFP state.
1107 		 */
1108 		vfp_lazy_save_state_final(&thr->vfp_state.sec,
1109 					  false /*!force_save*/);
1110 		thr->vfp_state.sec_saved = true;
1111 	} else if (tuv && tuv->lazy_saved && !tuv->saved) {
1112 		/*
1113 		 * This can happen either during syscall or abort
1114 		 * processing (while processing a syscall).
1115 		 */
1116 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
1117 		tuv->saved = true;
1118 	}
1119 
1120 	vfp_enable();
1121 	return exceptions;
1122 }
1123 
1124 void thread_kernel_disable_vfp(uint32_t state)
1125 {
1126 	uint32_t exceptions;
1127 
1128 	assert(vfp_is_enabled());
1129 
1130 	vfp_disable();
1131 	exceptions = thread_get_exceptions();
1132 	assert(exceptions & THREAD_EXCP_FOREIGN_INTR);
1133 	exceptions &= ~THREAD_EXCP_FOREIGN_INTR;
1134 	exceptions |= state & THREAD_EXCP_FOREIGN_INTR;
1135 	thread_set_exceptions(exceptions);
1136 }
1137 
1138 void thread_kernel_save_vfp(void)
1139 {
1140 	struct thread_ctx *thr = threads + thread_get_id();
1141 
1142 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1143 	if (vfp_is_enabled()) {
1144 		vfp_lazy_save_state_init(&thr->vfp_state.sec);
1145 		thr->vfp_state.sec_lazy_saved = true;
1146 	}
1147 }
1148 
1149 void thread_kernel_restore_vfp(void)
1150 {
1151 	struct thread_ctx *thr = threads + thread_get_id();
1152 
1153 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1154 	assert(!vfp_is_enabled());
1155 	if (thr->vfp_state.sec_lazy_saved) {
1156 		vfp_lazy_restore_state(&thr->vfp_state.sec,
1157 				       thr->vfp_state.sec_saved);
1158 		thr->vfp_state.sec_saved = false;
1159 		thr->vfp_state.sec_lazy_saved = false;
1160 	}
1161 }
1162 
1163 void thread_user_enable_vfp(struct thread_user_vfp_state *uvfp)
1164 {
1165 	struct thread_ctx *thr = threads + thread_get_id();
1166 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1167 
1168 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1169 	assert(!vfp_is_enabled());
1170 
1171 	if (!thr->vfp_state.ns_saved) {
1172 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1173 					  true /*force_save*/);
1174 		thr->vfp_state.ns_saved = true;
1175 	} else if (tuv && uvfp != tuv) {
1176 		if (tuv->lazy_saved && !tuv->saved) {
1177 			vfp_lazy_save_state_final(&tuv->vfp,
1178 						  false /*!force_save*/);
1179 			tuv->saved = true;
1180 		}
1181 	}
1182 
1183 	if (uvfp->lazy_saved)
1184 		vfp_lazy_restore_state(&uvfp->vfp, uvfp->saved);
1185 	uvfp->lazy_saved = false;
1186 	uvfp->saved = false;
1187 
1188 	thr->vfp_state.uvfp = uvfp;
1189 	vfp_enable();
1190 }
1191 
1192 void thread_user_save_vfp(void)
1193 {
1194 	struct thread_ctx *thr = threads + thread_get_id();
1195 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1196 
1197 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1198 	if (!vfp_is_enabled())
1199 		return;
1200 
1201 	assert(tuv && !tuv->lazy_saved && !tuv->saved);
1202 	vfp_lazy_save_state_init(&tuv->vfp);
1203 	tuv->lazy_saved = true;
1204 }
1205 
1206 void thread_user_clear_vfp(struct thread_user_vfp_state *uvfp)
1207 {
1208 	struct thread_ctx *thr = threads + thread_get_id();
1209 
1210 	if (uvfp == thr->vfp_state.uvfp)
1211 		thr->vfp_state.uvfp = NULL;
1212 	uvfp->lazy_saved = false;
1213 	uvfp->saved = false;
1214 }
1215 #endif /*CFG_WITH_VFP*/
1216 
1217 #ifdef ARM32
1218 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1219 {
1220 	uint32_t s;
1221 
1222 	if (!is_32bit)
1223 		return false;
1224 
1225 	s = read_spsr();
1226 	s &= ~(CPSR_MODE_MASK | CPSR_T | CPSR_IT_MASK1 | CPSR_IT_MASK2);
1227 	s |= CPSR_MODE_USR;
1228 	if (entry_func & 1)
1229 		s |= CPSR_T;
1230 	*spsr = s;
1231 	return true;
1232 }
1233 #endif
1234 
1235 #ifdef ARM64
1236 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1237 {
1238 	uint32_t s;
1239 
1240 	if (is_32bit) {
1241 		s = read_daif() & (SPSR_32_AIF_MASK << SPSR_32_AIF_SHIFT);
1242 		s |= SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT;
1243 		s |= (entry_func & SPSR_32_T_MASK) << SPSR_32_T_SHIFT;
1244 	} else {
1245 		s = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
1246 	}
1247 
1248 	*spsr = s;
1249 	return true;
1250 }
1251 #endif
1252 
1253 uint32_t thread_enter_user_mode(unsigned long a0, unsigned long a1,
1254 		unsigned long a2, unsigned long a3, unsigned long user_sp,
1255 		unsigned long entry_func, bool is_32bit,
1256 		uint32_t *exit_status0, uint32_t *exit_status1)
1257 {
1258 	uint32_t spsr;
1259 
1260 	tee_ta_update_session_utime_resume();
1261 
1262 	if (!get_spsr(is_32bit, entry_func, &spsr)) {
1263 		*exit_status0 = 1; /* panic */
1264 		*exit_status1 = 0xbadbadba;
1265 		return 0;
1266 	}
1267 	return __thread_enter_user_mode(a0, a1, a2, a3, user_sp, entry_func,
1268 					spsr, exit_status0, exit_status1);
1269 }
1270 
1271 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
1272 void thread_get_user_kcode(struct mobj **mobj, size_t *offset,
1273 			   vaddr_t *va, size_t *sz)
1274 {
1275 	core_mmu_get_user_va_range(va, NULL);
1276 	*mobj = mobj_tee_ram;
1277 	*offset = thread_user_kcode_va - TEE_RAM_START;
1278 	*sz = thread_user_kcode_size;
1279 }
1280 #endif
1281 
1282 #if defined(CFG_CORE_UNMAP_CORE_AT_EL0) && \
1283 	defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
1284 void thread_get_user_kdata(struct mobj **mobj, size_t *offset,
1285 			   vaddr_t *va, size_t *sz)
1286 {
1287 	vaddr_t v;
1288 
1289 	core_mmu_get_user_va_range(&v, NULL);
1290 	*va = v + thread_user_kcode_size;
1291 	*mobj = mobj_tee_ram;
1292 	*offset = (vaddr_t)thread_user_kdata_page - TEE_RAM_START;
1293 	*sz = sizeof(thread_user_kdata_page);
1294 }
1295 #endif
1296 
1297 bool thread_disable_prealloc_rpc_cache(uint64_t *cookie)
1298 {
1299 	bool rv;
1300 	size_t n;
1301 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1302 
1303 	lock_global();
1304 
1305 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1306 		if (threads[n].state != THREAD_STATE_FREE) {
1307 			rv = false;
1308 			goto out;
1309 		}
1310 	}
1311 
1312 	rv = true;
1313 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1314 		if (threads[n].rpc_arg) {
1315 			*cookie = mobj_get_cookie(threads[n].rpc_mobj);
1316 			mobj_free(threads[n].rpc_mobj);
1317 			threads[n].rpc_arg = NULL;
1318 			goto out;
1319 		}
1320 	}
1321 
1322 	*cookie = 0;
1323 	thread_prealloc_rpc_cache = false;
1324 out:
1325 	unlock_global();
1326 	thread_unmask_exceptions(exceptions);
1327 	return rv;
1328 }
1329 
1330 bool thread_enable_prealloc_rpc_cache(void)
1331 {
1332 	bool rv;
1333 	size_t n;
1334 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1335 
1336 	lock_global();
1337 
1338 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1339 		if (threads[n].state != THREAD_STATE_FREE) {
1340 			rv = false;
1341 			goto out;
1342 		}
1343 	}
1344 
1345 	rv = true;
1346 	thread_prealloc_rpc_cache = true;
1347 out:
1348 	unlock_global();
1349 	thread_unmask_exceptions(exceptions);
1350 	return rv;
1351 }
1352 
1353 /**
1354  * Allocates data for struct optee_msg_arg.
1355  *
1356  * @size:	size in bytes of struct optee_msg_arg
1357  *
1358  * @returns	mobj that describes allocated buffer or NULL on error
1359  */
1360 static struct mobj *thread_rpc_alloc_arg(size_t size)
1361 {
1362 	paddr_t pa;
1363 	uint64_t co;
1364 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
1365 		OPTEE_SMC_RETURN_RPC_ALLOC, size
1366 	};
1367 	struct mobj *mobj = NULL;
1368 
1369 	thread_rpc(rpc_args);
1370 
1371 	pa = reg_pair_to_64(rpc_args[1], rpc_args[2]);
1372 	co = reg_pair_to_64(rpc_args[4], rpc_args[5]);
1373 
1374 	if (!ALIGNMENT_IS_OK(pa, struct optee_msg_arg))
1375 		goto err;
1376 
1377 	/* Check if this region is in static shared space */
1378 	if (core_pbuf_is(CORE_MEM_NSEC_SHM, pa, size))
1379 		mobj = mobj_shm_alloc(pa, size, co);
1380 	else if ((!(pa & SMALL_PAGE_MASK)) && size <= SMALL_PAGE_SIZE)
1381 		mobj = mobj_mapped_shm_alloc(&pa, 1, 0, co);
1382 
1383 	if (!mobj)
1384 		goto err;
1385 
1386 	return mobj;
1387 err:
1388 	thread_rpc_free_arg(co);
1389 	mobj_free(mobj);
1390 	return NULL;
1391 }
1392 
1393 static bool set_rmem(struct optee_msg_param *param,
1394 		     struct thread_param *tpm)
1395 {
1396 	param->attr = tpm->attr - THREAD_PARAM_ATTR_MEMREF_IN +
1397 		      OPTEE_MSG_ATTR_TYPE_RMEM_INPUT;
1398 	param->u.rmem.offs = tpm->u.memref.offs;
1399 	param->u.rmem.size = tpm->u.memref.size;
1400 	if (tpm->u.memref.mobj) {
1401 		param->u.rmem.shm_ref = mobj_get_cookie(tpm->u.memref.mobj);
1402 		if (!param->u.rmem.shm_ref)
1403 			return false;
1404 	} else {
1405 		param->u.rmem.shm_ref = 0;
1406 	}
1407 
1408 	return true;
1409 }
1410 
1411 static bool set_tmem(struct optee_msg_param *param,
1412 		     struct thread_param *tpm)
1413 {
1414 	paddr_t pa = 0;
1415 	uint64_t shm_ref = 0;
1416 	struct mobj *mobj = tpm->u.memref.mobj;
1417 
1418 	param->attr = tpm->attr - THREAD_PARAM_ATTR_MEMREF_IN +
1419 		      OPTEE_MSG_ATTR_TYPE_TMEM_INPUT;
1420 	if (mobj) {
1421 		shm_ref = mobj_get_cookie(mobj);
1422 		if (!shm_ref)
1423 			return false;
1424 		if (mobj_get_pa(mobj, tpm->u.memref.offs, 0, &pa))
1425 			return false;
1426 	}
1427 
1428 	param->u.tmem.size = tpm->u.memref.size;
1429 	param->u.tmem.buf_ptr = pa;
1430 	param->u.tmem.shm_ref = shm_ref;
1431 
1432 	return true;
1433 }
1434 
1435 static uint32_t get_rpc_arg(uint32_t cmd, size_t num_params,
1436 			    struct thread_param *params, void **arg_ret,
1437 			    uint64_t *carg_ret)
1438 {
1439 	struct thread_ctx *thr = threads + thread_get_id();
1440 	struct optee_msg_arg *arg = thr->rpc_arg;
1441 	size_t sz = OPTEE_MSG_GET_ARG_SIZE(THREAD_RPC_MAX_NUM_PARAMS);
1442 
1443 	if (num_params > THREAD_RPC_MAX_NUM_PARAMS)
1444 		return TEE_ERROR_BAD_PARAMETERS;
1445 
1446 	if (!arg) {
1447 		struct mobj *mobj = thread_rpc_alloc_arg(sz);
1448 
1449 		if (!mobj)
1450 			return TEE_ERROR_OUT_OF_MEMORY;
1451 
1452 		arg = mobj_get_va(mobj, 0);
1453 		if (!arg) {
1454 			thread_rpc_free_arg(mobj_get_cookie(mobj));
1455 			return TEE_ERROR_OUT_OF_MEMORY;
1456 		}
1457 
1458 		thr->rpc_arg = arg;
1459 		thr->rpc_mobj = mobj;
1460 	}
1461 
1462 	memset(arg, 0, OPTEE_MSG_GET_ARG_SIZE(num_params));
1463 	arg->cmd = cmd;
1464 	arg->num_params = num_params;
1465 	arg->ret = TEE_ERROR_GENERIC; /* in case value isn't updated */
1466 
1467 	for (size_t n = 0; n < num_params; n++) {
1468 		switch (params[n].attr) {
1469 		case THREAD_PARAM_ATTR_NONE:
1470 			arg->params[n].attr = OPTEE_MSG_ATTR_TYPE_NONE;
1471 			break;
1472 		case THREAD_PARAM_ATTR_VALUE_IN:
1473 		case THREAD_PARAM_ATTR_VALUE_OUT:
1474 		case THREAD_PARAM_ATTR_VALUE_INOUT:
1475 			arg->params[n].attr = params[n].attr -
1476 					      THREAD_PARAM_ATTR_VALUE_IN +
1477 					      OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
1478 			arg->params[n].u.value.a = params[n].u.value.a;
1479 			arg->params[n].u.value.b = params[n].u.value.b;
1480 			arg->params[n].u.value.c = params[n].u.value.c;
1481 			break;
1482 		case THREAD_PARAM_ATTR_MEMREF_IN:
1483 		case THREAD_PARAM_ATTR_MEMREF_OUT:
1484 		case THREAD_PARAM_ATTR_MEMREF_INOUT:
1485 			if (!params[n].u.memref.mobj ||
1486 			    mobj_matches(params[n].u.memref.mobj,
1487 					 CORE_MEM_NSEC_SHM)) {
1488 				if (!set_tmem(arg->params + n, params + n))
1489 					return TEE_ERROR_BAD_PARAMETERS;
1490 			} else  if (mobj_matches(params[n].u.memref.mobj,
1491 						 CORE_MEM_REG_SHM)) {
1492 				if (!set_rmem(arg->params + n, params + n))
1493 					return TEE_ERROR_BAD_PARAMETERS;
1494 			} else {
1495 				return TEE_ERROR_BAD_PARAMETERS;
1496 			}
1497 			break;
1498 		default:
1499 			return TEE_ERROR_BAD_PARAMETERS;
1500 		}
1501 	}
1502 
1503 	*arg_ret = arg;
1504 	*carg_ret = mobj_get_cookie(thr->rpc_mobj);
1505 
1506 	return TEE_SUCCESS;
1507 }
1508 
1509 static uint32_t get_rpc_arg_res(struct optee_msg_arg *arg, size_t num_params,
1510 				struct thread_param *params)
1511 {
1512 	for (size_t n = 0; n < num_params; n++) {
1513 		switch (params[n].attr) {
1514 		case THREAD_PARAM_ATTR_VALUE_OUT:
1515 		case THREAD_PARAM_ATTR_VALUE_INOUT:
1516 			params[n].u.value.a = arg->params[n].u.value.a;
1517 			params[n].u.value.b = arg->params[n].u.value.b;
1518 			params[n].u.value.c = arg->params[n].u.value.c;
1519 			break;
1520 		case THREAD_PARAM_ATTR_MEMREF_OUT:
1521 		case THREAD_PARAM_ATTR_MEMREF_INOUT:
1522 			/*
1523 			 * rmem.size and tmem.size is the same type and
1524 			 * location.
1525 			 */
1526 			params[n].u.memref.size = arg->params[n].u.rmem.size;
1527 			break;
1528 		default:
1529 			break;
1530 		}
1531 	}
1532 
1533 	return arg->ret;
1534 }
1535 
1536 uint32_t thread_rpc_cmd(uint32_t cmd, size_t num_params,
1537 			struct thread_param *params)
1538 {
1539 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1540 	void *arg = NULL;
1541 	uint64_t carg = 0;
1542 	uint32_t ret = 0;
1543 
1544 	/* The source CRYPTO_RNG_SRC_JITTER_RPC is safe to use here */
1545 	plat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_RPC,
1546 				     &thread_rpc_pnum);
1547 
1548 	ret = get_rpc_arg(cmd, num_params, params, &arg, &carg);
1549 	if (ret)
1550 		return ret;
1551 
1552 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1553 	thread_rpc(rpc_args);
1554 
1555 	return get_rpc_arg_res(arg, num_params, params);
1556 }
1557 
1558 /**
1559  * Free physical memory previously allocated with thread_rpc_alloc()
1560  *
1561  * @cookie:	cookie received when allocating the buffer
1562  * @bt:		must be the same as supplied when allocating
1563  * @mobj:	mobj that describes allocated buffer
1564  *
1565  * This function also frees corresponding mobj.
1566  */
1567 static void thread_rpc_free(unsigned int bt, uint64_t cookie, struct mobj *mobj)
1568 {
1569 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1570 	void *arg = NULL;
1571 	uint64_t carg = 0;
1572 	struct thread_param param = THREAD_PARAM_VALUE(IN, bt, cookie, 0);
1573 	uint32_t ret = get_rpc_arg(OPTEE_RPC_CMD_SHM_FREE, 1, &param,
1574 				   &arg, &carg);
1575 
1576 	mobj_free(mobj);
1577 
1578 	if (!ret) {
1579 		reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1580 		thread_rpc(rpc_args);
1581 	}
1582 }
1583 
1584 static struct mobj *get_rpc_alloc_res(struct optee_msg_arg *arg,
1585 				      unsigned int bt)
1586 {
1587 	struct mobj *mobj = NULL;
1588 	uint64_t cookie = 0;
1589 
1590 	if (arg->ret || arg->num_params != 1)
1591 		return NULL;
1592 
1593 	if (arg->params[0].attr == OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT) {
1594 		cookie = arg->params[0].u.tmem.shm_ref;
1595 		mobj = mobj_shm_alloc(arg->params[0].u.tmem.buf_ptr,
1596 				      arg->params[0].u.tmem.size,
1597 				      cookie);
1598 	} else if (arg->params[0].attr == (OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT |
1599 					   OPTEE_MSG_ATTR_NONCONTIG)) {
1600 		cookie = arg->params[0].u.tmem.shm_ref;
1601 		mobj = msg_param_mobj_from_noncontig(
1602 			arg->params[0].u.tmem.buf_ptr,
1603 			arg->params[0].u.tmem.size,
1604 			cookie,
1605 			true);
1606 	} else {
1607 		return NULL;
1608 	}
1609 
1610 	if (!mobj) {
1611 		thread_rpc_free(bt, cookie, mobj);
1612 		return NULL;
1613 	}
1614 
1615 	assert(mobj_is_nonsec(mobj));
1616 
1617 	return mobj;
1618 }
1619 
1620 /**
1621  * Allocates shared memory buffer via RPC
1622  *
1623  * @size:	size in bytes of shared memory buffer
1624  * @align:	required alignment of buffer
1625  * @bt:		buffer type OPTEE_RPC_SHM_TYPE_*
1626  *
1627  * Returns a pointer to MOBJ for the memory on success, or NULL on failure.
1628  */
1629 static struct mobj *thread_rpc_alloc(size_t size, size_t align, unsigned int bt)
1630 {
1631 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1632 	void *arg = NULL;
1633 	uint64_t carg = 0;
1634 	struct thread_param param = THREAD_PARAM_VALUE(IN, bt, size, align);
1635 	uint32_t ret = get_rpc_arg(OPTEE_RPC_CMD_SHM_ALLOC, 1, &param,
1636 				   &arg, &carg);
1637 
1638 	if (ret)
1639 		return NULL;
1640 
1641 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1642 	thread_rpc(rpc_args);
1643 
1644 	return get_rpc_alloc_res(arg, bt);
1645 }
1646 
1647 struct mobj *thread_rpc_alloc_payload(size_t size)
1648 {
1649 	return thread_rpc_alloc(size, 8, OPTEE_RPC_SHM_TYPE_APPL);
1650 }
1651 
1652 void thread_rpc_free_payload(struct mobj *mobj)
1653 {
1654 	thread_rpc_free(OPTEE_RPC_SHM_TYPE_APPL, mobj_get_cookie(mobj),
1655 			mobj);
1656 }
1657 
1658 struct mobj *thread_rpc_alloc_global_payload(size_t size)
1659 {
1660 	return thread_rpc_alloc(size, 8, OPTEE_RPC_SHM_TYPE_GLOBAL);
1661 }
1662 
1663 void thread_rpc_free_global_payload(struct mobj *mobj)
1664 {
1665 	thread_rpc_free(OPTEE_RPC_SHM_TYPE_GLOBAL, mobj_get_cookie(mobj),
1666 			mobj);
1667 }
1668