xref: /optee_os/core/arch/arm/kernel/thread.c (revision c211d0a49ecf2673dfb90f29fa31840eda12a18d)
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 	size_t n;
397 
398 	mutex_lockdep_init();
399 
400 	for (n = 0; n < CFG_NUM_THREADS; n++) {
401 		TAILQ_INIT(&threads[n].tsd.sess_stack);
402 		SLIST_INIT(&threads[n].tsd.pgt_cache);
403 	}
404 
405 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++)
406 		thread_core_local[n].curr_thread = -1;
407 
408 	l->curr_thread = 0;
409 	threads[0].state = THREAD_STATE_ACTIVE;
410 }
411 
412 void thread_clr_boot_thread(void)
413 {
414 	struct thread_core_local *l = thread_get_core_local();
415 
416 	assert(l->curr_thread >= 0 && l->curr_thread < CFG_NUM_THREADS);
417 	assert(threads[l->curr_thread].state == THREAD_STATE_ACTIVE);
418 	threads[l->curr_thread].state = THREAD_STATE_FREE;
419 	l->curr_thread = -1;
420 }
421 
422 static void thread_alloc_and_run(struct thread_smc_args *args)
423 {
424 	size_t n;
425 	struct thread_core_local *l = thread_get_core_local();
426 	bool found_thread = false;
427 
428 	assert(l->curr_thread == -1);
429 
430 	lock_global();
431 
432 	for (n = 0; n < CFG_NUM_THREADS; n++) {
433 		if (threads[n].state == THREAD_STATE_FREE) {
434 			threads[n].state = THREAD_STATE_ACTIVE;
435 			found_thread = true;
436 			break;
437 		}
438 	}
439 
440 	unlock_global();
441 
442 	if (!found_thread) {
443 		args->a0 = OPTEE_SMC_RETURN_ETHREAD_LIMIT;
444 		return;
445 	}
446 
447 	l->curr_thread = n;
448 
449 	threads[n].flags = 0;
450 	init_regs(threads + n, args);
451 
452 	/* Save Hypervisor Client ID */
453 	threads[n].hyp_clnt_id = args->a7;
454 
455 	thread_lazy_save_ns_vfp();
456 	thread_resume(&threads[n].regs);
457 }
458 
459 #ifdef ARM32
460 static void copy_a0_to_a5(struct thread_ctx_regs *regs,
461 		struct thread_smc_args *args)
462 {
463 	/*
464 	 * Update returned values from RPC, values will appear in
465 	 * r0-r3 when thread is resumed.
466 	 */
467 	regs->r0 = args->a0;
468 	regs->r1 = args->a1;
469 	regs->r2 = args->a2;
470 	regs->r3 = args->a3;
471 	regs->r4 = args->a4;
472 	regs->r5 = args->a5;
473 }
474 #endif /*ARM32*/
475 
476 #ifdef ARM64
477 static void copy_a0_to_a5(struct thread_ctx_regs *regs,
478 		struct thread_smc_args *args)
479 {
480 	/*
481 	 * Update returned values from RPC, values will appear in
482 	 * x0-x3 when thread is resumed.
483 	 */
484 	regs->x[0] = args->a0;
485 	regs->x[1] = args->a1;
486 	regs->x[2] = args->a2;
487 	regs->x[3] = args->a3;
488 	regs->x[4] = args->a4;
489 	regs->x[5] = args->a5;
490 }
491 #endif /*ARM64*/
492 
493 #ifdef ARM32
494 static bool is_from_user(uint32_t cpsr)
495 {
496 	return (cpsr & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_USR;
497 }
498 #endif
499 
500 #ifdef ARM64
501 static bool is_from_user(uint32_t cpsr)
502 {
503 	if (cpsr & (SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT))
504 		return true;
505 	if (((cpsr >> SPSR_64_MODE_EL_SHIFT) & SPSR_64_MODE_EL_MASK) ==
506 	     SPSR_64_MODE_EL0)
507 		return true;
508 	return false;
509 }
510 #endif
511 
512 static bool is_user_mode(struct thread_ctx_regs *regs)
513 {
514 	return is_from_user((uint32_t)regs->cpsr);
515 }
516 
517 static void thread_resume_from_rpc(struct thread_smc_args *args)
518 {
519 	size_t n = args->a3; /* thread id */
520 	struct thread_core_local *l = thread_get_core_local();
521 	uint32_t rv = 0;
522 
523 	assert(l->curr_thread == -1);
524 
525 	lock_global();
526 
527 	if (n < CFG_NUM_THREADS &&
528 	    threads[n].state == THREAD_STATE_SUSPENDED &&
529 	    args->a7 == threads[n].hyp_clnt_id)
530 		threads[n].state = THREAD_STATE_ACTIVE;
531 	else
532 		rv = OPTEE_SMC_RETURN_ERESUME;
533 
534 	unlock_global();
535 
536 	if (rv) {
537 		args->a0 = rv;
538 		return;
539 	}
540 
541 	l->curr_thread = n;
542 
543 	if (is_user_mode(&threads[n].regs))
544 		tee_ta_update_session_utime_resume();
545 
546 	if (threads[n].have_user_map)
547 		core_mmu_set_user_map(&threads[n].user_map);
548 
549 	/*
550 	 * Return from RPC to request service of a foreign interrupt must not
551 	 * get parameters from non-secure world.
552 	 */
553 	if (threads[n].flags & THREAD_FLAGS_COPY_ARGS_ON_RETURN) {
554 		copy_a0_to_a5(&threads[n].regs, args);
555 		threads[n].flags &= ~THREAD_FLAGS_COPY_ARGS_ON_RETURN;
556 	}
557 
558 	thread_lazy_save_ns_vfp();
559 	thread_resume(&threads[n].regs);
560 }
561 
562 void thread_handle_fast_smc(struct thread_smc_args *args)
563 {
564 	thread_check_canaries();
565 	thread_fast_smc_handler_ptr(args);
566 	/* Fast handlers must not unmask any exceptions */
567 	assert(thread_get_exceptions() == THREAD_EXCP_ALL);
568 }
569 
570 void thread_handle_std_smc(struct thread_smc_args *args)
571 {
572 	thread_check_canaries();
573 
574 	if (args->a0 == OPTEE_SMC_CALL_RETURN_FROM_RPC)
575 		thread_resume_from_rpc(args);
576 	else
577 		thread_alloc_and_run(args);
578 }
579 
580 /**
581  * Free physical memory previously allocated with thread_rpc_alloc_arg()
582  *
583  * @cookie:	cookie received when allocating the buffer
584  */
585 static void thread_rpc_free_arg(uint64_t cookie)
586 {
587 	if (cookie) {
588 		uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
589 			OPTEE_SMC_RETURN_RPC_FREE
590 		};
591 
592 		reg_pair_from_64(cookie, rpc_args + 1, rpc_args + 2);
593 		thread_rpc(rpc_args);
594 	}
595 }
596 
597 /*
598  * Helper routine for the assembly function thread_std_smc_entry()
599  *
600  * Note: this function is weak just to make it possible to exclude it from
601  * the unpaged area.
602  */
603 void __weak __thread_std_smc_entry(struct thread_smc_args *args)
604 {
605 	thread_std_smc_handler_ptr(args);
606 
607 	if (args->a0 == OPTEE_SMC_RETURN_OK) {
608 		struct thread_ctx *thr = threads + thread_get_id();
609 
610 		tee_fs_rpc_cache_clear(&thr->tsd);
611 		if (!thread_prealloc_rpc_cache) {
612 			thread_rpc_free_arg(mobj_get_cookie(thr->rpc_mobj));
613 			mobj_free(thr->rpc_mobj);
614 			thr->rpc_arg = 0;
615 			thr->rpc_mobj = NULL;
616 		}
617 	}
618 }
619 
620 void *thread_get_tmp_sp(void)
621 {
622 	struct thread_core_local *l = thread_get_core_local();
623 
624 	return (void *)l->tmp_stack_va_end;
625 }
626 
627 #ifdef ARM64
628 vaddr_t thread_get_saved_thread_sp(void)
629 {
630 	struct thread_core_local *l = thread_get_core_local();
631 	int ct = l->curr_thread;
632 
633 	assert(ct != -1);
634 	return threads[ct].kern_sp;
635 }
636 #endif /*ARM64*/
637 
638 vaddr_t thread_stack_start(void)
639 {
640 	struct thread_ctx *thr;
641 	int ct = thread_get_id_may_fail();
642 
643 	if (ct == -1)
644 		return 0;
645 
646 	thr = threads + ct;
647 	return thr->stack_va_end - STACK_THREAD_SIZE;
648 }
649 
650 size_t thread_stack_size(void)
651 {
652 	return STACK_THREAD_SIZE;
653 }
654 
655 bool thread_is_from_abort_mode(void)
656 {
657 	struct thread_core_local *l = thread_get_core_local();
658 
659 	return (l->flags >> THREAD_CLF_SAVED_SHIFT) & THREAD_CLF_ABORT;
660 }
661 
662 #ifdef ARM32
663 bool thread_is_in_normal_mode(void)
664 {
665 	return (read_cpsr() & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_SVC;
666 }
667 #endif
668 
669 #ifdef ARM64
670 bool thread_is_in_normal_mode(void)
671 {
672 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
673 	struct thread_core_local *l = thread_get_core_local();
674 	bool ret;
675 
676 	/* If any bit in l->flags is set we're handling some exception. */
677 	ret = !l->flags;
678 	thread_unmask_exceptions(exceptions);
679 
680 	return ret;
681 }
682 #endif
683 
684 void thread_state_free(void)
685 {
686 	struct thread_core_local *l = thread_get_core_local();
687 	int ct = l->curr_thread;
688 
689 	assert(ct != -1);
690 
691 	thread_lazy_restore_ns_vfp();
692 	tee_pager_release_phys(
693 		(void *)(threads[ct].stack_va_end - STACK_THREAD_SIZE),
694 		STACK_THREAD_SIZE);
695 
696 	lock_global();
697 
698 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
699 	threads[ct].state = THREAD_STATE_FREE;
700 	threads[ct].flags = 0;
701 	l->curr_thread = -1;
702 
703 	unlock_global();
704 }
705 
706 #ifdef CFG_WITH_PAGER
707 static void release_unused_kernel_stack(struct thread_ctx *thr,
708 					uint32_t cpsr __maybe_unused)
709 {
710 #ifdef ARM64
711 	/*
712 	 * If we're from user mode then thr->regs.sp is the saved user
713 	 * stack pointer and thr->kern_sp holds the last kernel stack
714 	 * pointer. But if we're from kernel mode then thr->kern_sp isn't
715 	 * up to date so we need to read from thr->regs.sp instead.
716 	 */
717 	vaddr_t sp = is_from_user(cpsr) ?  thr->kern_sp : thr->regs.sp;
718 #else
719 	vaddr_t sp = thr->regs.svc_sp;
720 #endif
721 	vaddr_t base = thr->stack_va_end - STACK_THREAD_SIZE;
722 	size_t len = sp - base;
723 
724 	tee_pager_release_phys((void *)base, len);
725 }
726 #else
727 static void release_unused_kernel_stack(struct thread_ctx *thr __unused,
728 					uint32_t cpsr __unused)
729 {
730 }
731 #endif
732 
733 int thread_state_suspend(uint32_t flags, uint32_t cpsr, vaddr_t pc)
734 {
735 	struct thread_core_local *l = thread_get_core_local();
736 	int ct = l->curr_thread;
737 
738 	assert(ct != -1);
739 
740 	thread_check_canaries();
741 
742 	release_unused_kernel_stack(threads + ct, cpsr);
743 
744 	if (is_from_user(cpsr)) {
745 		thread_user_save_vfp();
746 		tee_ta_update_session_utime_suspend();
747 		tee_ta_gprof_sample_pc(pc);
748 	}
749 	thread_lazy_restore_ns_vfp();
750 
751 	lock_global();
752 
753 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
754 	threads[ct].flags |= flags;
755 	threads[ct].regs.cpsr = cpsr;
756 	threads[ct].regs.pc = pc;
757 	threads[ct].state = THREAD_STATE_SUSPENDED;
758 
759 	threads[ct].have_user_map = core_mmu_user_mapping_is_active();
760 	if (threads[ct].have_user_map) {
761 		core_mmu_get_user_map(&threads[ct].user_map);
762 		core_mmu_set_user_map(NULL);
763 	}
764 
765 	l->curr_thread = -1;
766 
767 	unlock_global();
768 
769 	return ct;
770 }
771 
772 #ifdef ARM32
773 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
774 {
775 	l->tmp_stack_va_end = sp;
776 	thread_set_irq_sp(sp);
777 	thread_set_fiq_sp(sp);
778 }
779 
780 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
781 {
782 	l->abt_stack_va_end = sp;
783 	thread_set_abt_sp((vaddr_t)l);
784 	thread_set_und_sp((vaddr_t)l);
785 }
786 #endif /*ARM32*/
787 
788 #ifdef ARM64
789 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
790 {
791 	/*
792 	 * We're already using the tmp stack when this function is called
793 	 * so there's no need to assign it to any stack pointer. However,
794 	 * we'll need to restore it at different times so store it here.
795 	 */
796 	l->tmp_stack_va_end = sp;
797 }
798 
799 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
800 {
801 	l->abt_stack_va_end = sp;
802 }
803 #endif /*ARM64*/
804 
805 bool thread_init_stack(uint32_t thread_id, vaddr_t sp)
806 {
807 	if (thread_id >= CFG_NUM_THREADS)
808 		return false;
809 	threads[thread_id].stack_va_end = sp;
810 	return true;
811 }
812 
813 int thread_get_id_may_fail(void)
814 {
815 	/*
816 	 * thread_get_core_local() requires foreign interrupts to be disabled
817 	 */
818 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
819 	struct thread_core_local *l = thread_get_core_local();
820 	int ct = l->curr_thread;
821 
822 	thread_unmask_exceptions(exceptions);
823 	return ct;
824 }
825 
826 int thread_get_id(void)
827 {
828 	int ct = thread_get_id_may_fail();
829 
830 	assert(ct >= 0 && ct < CFG_NUM_THREADS);
831 	return ct;
832 }
833 
834 static void init_handlers(const struct thread_handlers *handlers)
835 {
836 	thread_std_smc_handler_ptr = handlers->std_smc;
837 	thread_fast_smc_handler_ptr = handlers->fast_smc;
838 	thread_nintr_handler_ptr = handlers->nintr;
839 	thread_cpu_on_handler_ptr = handlers->cpu_on;
840 	thread_cpu_off_handler_ptr = handlers->cpu_off;
841 	thread_cpu_suspend_handler_ptr = handlers->cpu_suspend;
842 	thread_cpu_resume_handler_ptr = handlers->cpu_resume;
843 	thread_system_off_handler_ptr = handlers->system_off;
844 	thread_system_reset_handler_ptr = handlers->system_reset;
845 }
846 
847 #ifdef CFG_WITH_PAGER
848 static void init_thread_stacks(void)
849 {
850 	size_t n;
851 
852 	/*
853 	 * Allocate virtual memory for thread stacks.
854 	 */
855 	for (n = 0; n < CFG_NUM_THREADS; n++) {
856 		tee_mm_entry_t *mm;
857 		vaddr_t sp;
858 
859 		/* Find vmem for thread stack and its protection gap */
860 		mm = tee_mm_alloc(&tee_mm_vcore,
861 				  SMALL_PAGE_SIZE + STACK_THREAD_SIZE);
862 		assert(mm);
863 
864 		/* Claim eventual physical page */
865 		tee_pager_add_pages(tee_mm_get_smem(mm), tee_mm_get_size(mm),
866 				    true);
867 
868 		/* Add the area to the pager */
869 		tee_pager_add_core_area(tee_mm_get_smem(mm) + SMALL_PAGE_SIZE,
870 					tee_mm_get_bytes(mm) - SMALL_PAGE_SIZE,
871 					TEE_MATTR_PRW | TEE_MATTR_LOCKED,
872 					NULL, NULL);
873 
874 		/* init effective stack */
875 		sp = tee_mm_get_smem(mm) + tee_mm_get_bytes(mm);
876 		asan_tag_access((void *)tee_mm_get_smem(mm), (void *)sp);
877 		if (!thread_init_stack(n, sp))
878 			panic("init stack failed");
879 	}
880 }
881 #else
882 static void init_thread_stacks(void)
883 {
884 	size_t n;
885 
886 	/* Assign the thread stacks */
887 	for (n = 0; n < CFG_NUM_THREADS; n++) {
888 		if (!thread_init_stack(n, GET_STACK(stack_thread[n])))
889 			panic("thread_init_stack failed");
890 	}
891 }
892 #endif /*CFG_WITH_PAGER*/
893 
894 static void init_user_kcode(void)
895 {
896 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
897 	vaddr_t v = (vaddr_t)thread_excp_vect;
898 	vaddr_t ve = (vaddr_t)thread_excp_vect_end;
899 
900 	thread_user_kcode_va = ROUNDDOWN(v, CORE_MMU_USER_CODE_SIZE);
901 	ve = ROUNDUP(ve, CORE_MMU_USER_CODE_SIZE);
902 	thread_user_kcode_size = ve - thread_user_kcode_va;
903 
904 	core_mmu_get_user_va_range(&v, NULL);
905 	thread_user_kcode_offset = thread_user_kcode_va - v;
906 
907 #if defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
908 	/*
909 	 * When transitioning to EL0 subtract SP with this much to point to
910 	 * this special kdata page instead. SP is restored by add this much
911 	 * while transitioning back to EL1.
912 	 */
913 	v += thread_user_kcode_size;
914 	thread_user_kdata_sp_offset = (vaddr_t)thread_core_local - v;
915 #endif
916 #endif /*CFG_CORE_UNMAP_CORE_AT_EL0*/
917 }
918 
919 void thread_init_primary(const struct thread_handlers *handlers)
920 {
921 	init_handlers(handlers);
922 
923 	/* Initialize canaries around the stacks */
924 	init_canaries();
925 
926 	init_thread_stacks();
927 	pgt_init();
928 
929 	init_user_kcode();
930 }
931 
932 static void init_sec_mon(size_t pos __maybe_unused)
933 {
934 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
935 	/* Initialize secure monitor */
936 	sm_init(GET_STACK(stack_tmp[pos]));
937 #endif
938 }
939 
940 static uint32_t __maybe_unused get_midr_implementer(uint32_t midr)
941 {
942 	return (midr >> MIDR_IMPLEMENTER_SHIFT) & MIDR_IMPLEMENTER_MASK;
943 }
944 
945 static uint32_t __maybe_unused get_midr_primary_part(uint32_t midr)
946 {
947 	return (midr >> MIDR_PRIMARY_PART_NUM_SHIFT) &
948 	       MIDR_PRIMARY_PART_NUM_MASK;
949 }
950 
951 #ifdef ARM64
952 static bool probe_workaround_available(void)
953 {
954 	int32_t r;
955 
956 	r = thread_smc(SMCCC_VERSION, 0, 0, 0);
957 	if (r < 0)
958 		return false;
959 	if (r < 0x10001)	/* compare with version 1.1 */
960 		return false;
961 
962 	/* Version >= 1.1, so SMCCC_ARCH_FEATURES is available */
963 	r = thread_smc(SMCCC_ARCH_FEATURES, SMCCC_ARCH_WORKAROUND_1, 0, 0);
964 	return r >= 0;
965 }
966 
967 static vaddr_t __maybe_unused select_vector(vaddr_t a)
968 {
969 	if (probe_workaround_available()) {
970 		DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") available",
971 		     SMCCC_ARCH_WORKAROUND_1);
972 		DMSG("SMC Workaround for CVE-2017-5715 used");
973 		return a;
974 	}
975 
976 	DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") unavailable",
977 	     SMCCC_ARCH_WORKAROUND_1);
978 	DMSG("SMC Workaround for CVE-2017-5715 not needed (if ARM-TF is up to date)");
979 	return (vaddr_t)thread_excp_vect;
980 }
981 #else
982 static vaddr_t __maybe_unused select_vector(vaddr_t a)
983 {
984 	return a;
985 }
986 #endif
987 
988 static vaddr_t get_excp_vect(void)
989 {
990 #ifdef CFG_CORE_WORKAROUND_SPECTRE_BP_SEC
991 	uint32_t midr = read_midr();
992 
993 	if (get_midr_implementer(midr) != MIDR_IMPLEMENTER_ARM)
994 		return (vaddr_t)thread_excp_vect;
995 
996 	switch (get_midr_primary_part(midr)) {
997 #ifdef ARM32
998 	case CORTEX_A8_PART_NUM:
999 	case CORTEX_A9_PART_NUM:
1000 	case CORTEX_A17_PART_NUM:
1001 #endif
1002 	case CORTEX_A57_PART_NUM:
1003 	case CORTEX_A72_PART_NUM:
1004 	case CORTEX_A73_PART_NUM:
1005 	case CORTEX_A75_PART_NUM:
1006 		return select_vector((vaddr_t)thread_excp_vect_workaround);
1007 #ifdef ARM32
1008 	case CORTEX_A15_PART_NUM:
1009 		return select_vector((vaddr_t)thread_excp_vect_workaround_a15);
1010 #endif
1011 	default:
1012 		return (vaddr_t)thread_excp_vect;
1013 	}
1014 #endif /*CFG_CORE_WORKAROUND_SPECTRE_BP_SEC*/
1015 
1016 	return (vaddr_t)thread_excp_vect;
1017 }
1018 
1019 void thread_init_per_cpu(void)
1020 {
1021 	size_t pos = get_core_pos();
1022 	struct thread_core_local *l = thread_get_core_local();
1023 
1024 	init_sec_mon(pos);
1025 
1026 	set_tmp_stack(l, GET_STACK(stack_tmp[pos]) - STACK_TMP_OFFS);
1027 	set_abt_stack(l, GET_STACK(stack_abt[pos]));
1028 
1029 	thread_init_vbar(get_excp_vect());
1030 }
1031 
1032 struct thread_specific_data *thread_get_tsd(void)
1033 {
1034 	return &threads[thread_get_id()].tsd;
1035 }
1036 
1037 struct thread_ctx_regs *thread_get_ctx_regs(void)
1038 {
1039 	struct thread_core_local *l = thread_get_core_local();
1040 
1041 	assert(l->curr_thread != -1);
1042 	return &threads[l->curr_thread].regs;
1043 }
1044 
1045 void thread_set_foreign_intr(bool enable)
1046 {
1047 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1048 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1049 	struct thread_core_local *l;
1050 
1051 	l = thread_get_core_local();
1052 
1053 	assert(l->curr_thread != -1);
1054 
1055 	if (enable) {
1056 		threads[l->curr_thread].flags |=
1057 					THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1058 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1059 	} else {
1060 		/*
1061 		 * No need to disable foreign interrupts here since they're
1062 		 * already disabled above.
1063 		 */
1064 		threads[l->curr_thread].flags &=
1065 					~THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1066 	}
1067 }
1068 
1069 void thread_restore_foreign_intr(void)
1070 {
1071 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1072 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1073 	struct thread_core_local *l;
1074 
1075 	l = thread_get_core_local();
1076 
1077 	assert(l->curr_thread != -1);
1078 
1079 	if (threads[l->curr_thread].flags & THREAD_FLAGS_FOREIGN_INTR_ENABLE)
1080 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1081 }
1082 
1083 #ifdef CFG_WITH_VFP
1084 uint32_t thread_kernel_enable_vfp(void)
1085 {
1086 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1087 	struct thread_ctx *thr = threads + thread_get_id();
1088 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1089 
1090 	assert(!vfp_is_enabled());
1091 
1092 	if (!thr->vfp_state.ns_saved) {
1093 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1094 					  true /*force_save*/);
1095 		thr->vfp_state.ns_saved = true;
1096 	} else if (thr->vfp_state.sec_lazy_saved &&
1097 		   !thr->vfp_state.sec_saved) {
1098 		/*
1099 		 * This happens when we're handling an abort while the
1100 		 * thread was using the VFP state.
1101 		 */
1102 		vfp_lazy_save_state_final(&thr->vfp_state.sec,
1103 					  false /*!force_save*/);
1104 		thr->vfp_state.sec_saved = true;
1105 	} else if (tuv && tuv->lazy_saved && !tuv->saved) {
1106 		/*
1107 		 * This can happen either during syscall or abort
1108 		 * processing (while processing a syscall).
1109 		 */
1110 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
1111 		tuv->saved = true;
1112 	}
1113 
1114 	vfp_enable();
1115 	return exceptions;
1116 }
1117 
1118 void thread_kernel_disable_vfp(uint32_t state)
1119 {
1120 	uint32_t exceptions;
1121 
1122 	assert(vfp_is_enabled());
1123 
1124 	vfp_disable();
1125 	exceptions = thread_get_exceptions();
1126 	assert(exceptions & THREAD_EXCP_FOREIGN_INTR);
1127 	exceptions &= ~THREAD_EXCP_FOREIGN_INTR;
1128 	exceptions |= state & THREAD_EXCP_FOREIGN_INTR;
1129 	thread_set_exceptions(exceptions);
1130 }
1131 
1132 void thread_kernel_save_vfp(void)
1133 {
1134 	struct thread_ctx *thr = threads + thread_get_id();
1135 
1136 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1137 	if (vfp_is_enabled()) {
1138 		vfp_lazy_save_state_init(&thr->vfp_state.sec);
1139 		thr->vfp_state.sec_lazy_saved = true;
1140 	}
1141 }
1142 
1143 void thread_kernel_restore_vfp(void)
1144 {
1145 	struct thread_ctx *thr = threads + thread_get_id();
1146 
1147 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1148 	assert(!vfp_is_enabled());
1149 	if (thr->vfp_state.sec_lazy_saved) {
1150 		vfp_lazy_restore_state(&thr->vfp_state.sec,
1151 				       thr->vfp_state.sec_saved);
1152 		thr->vfp_state.sec_saved = false;
1153 		thr->vfp_state.sec_lazy_saved = false;
1154 	}
1155 }
1156 
1157 void thread_user_enable_vfp(struct thread_user_vfp_state *uvfp)
1158 {
1159 	struct thread_ctx *thr = threads + thread_get_id();
1160 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1161 
1162 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1163 	assert(!vfp_is_enabled());
1164 
1165 	if (!thr->vfp_state.ns_saved) {
1166 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1167 					  true /*force_save*/);
1168 		thr->vfp_state.ns_saved = true;
1169 	} else if (tuv && uvfp != tuv) {
1170 		if (tuv->lazy_saved && !tuv->saved) {
1171 			vfp_lazy_save_state_final(&tuv->vfp,
1172 						  false /*!force_save*/);
1173 			tuv->saved = true;
1174 		}
1175 	}
1176 
1177 	if (uvfp->lazy_saved)
1178 		vfp_lazy_restore_state(&uvfp->vfp, uvfp->saved);
1179 	uvfp->lazy_saved = false;
1180 	uvfp->saved = false;
1181 
1182 	thr->vfp_state.uvfp = uvfp;
1183 	vfp_enable();
1184 }
1185 
1186 void thread_user_save_vfp(void)
1187 {
1188 	struct thread_ctx *thr = threads + thread_get_id();
1189 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1190 
1191 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1192 	if (!vfp_is_enabled())
1193 		return;
1194 
1195 	assert(tuv && !tuv->lazy_saved && !tuv->saved);
1196 	vfp_lazy_save_state_init(&tuv->vfp);
1197 	tuv->lazy_saved = true;
1198 }
1199 
1200 void thread_user_clear_vfp(struct thread_user_vfp_state *uvfp)
1201 {
1202 	struct thread_ctx *thr = threads + thread_get_id();
1203 
1204 	if (uvfp == thr->vfp_state.uvfp)
1205 		thr->vfp_state.uvfp = NULL;
1206 	uvfp->lazy_saved = false;
1207 	uvfp->saved = false;
1208 }
1209 #endif /*CFG_WITH_VFP*/
1210 
1211 #ifdef ARM32
1212 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1213 {
1214 	uint32_t s;
1215 
1216 	if (!is_32bit)
1217 		return false;
1218 
1219 	s = read_spsr();
1220 	s &= ~(CPSR_MODE_MASK | CPSR_T | CPSR_IT_MASK1 | CPSR_IT_MASK2);
1221 	s |= CPSR_MODE_USR;
1222 	if (entry_func & 1)
1223 		s |= CPSR_T;
1224 	*spsr = s;
1225 	return true;
1226 }
1227 #endif
1228 
1229 #ifdef ARM64
1230 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1231 {
1232 	uint32_t s;
1233 
1234 	if (is_32bit) {
1235 		s = read_daif() & (SPSR_32_AIF_MASK << SPSR_32_AIF_SHIFT);
1236 		s |= SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT;
1237 		s |= (entry_func & SPSR_32_T_MASK) << SPSR_32_T_SHIFT;
1238 	} else {
1239 		s = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
1240 	}
1241 
1242 	*spsr = s;
1243 	return true;
1244 }
1245 #endif
1246 
1247 uint32_t thread_enter_user_mode(unsigned long a0, unsigned long a1,
1248 		unsigned long a2, unsigned long a3, unsigned long user_sp,
1249 		unsigned long entry_func, bool is_32bit,
1250 		uint32_t *exit_status0, uint32_t *exit_status1)
1251 {
1252 	uint32_t spsr;
1253 
1254 	tee_ta_update_session_utime_resume();
1255 
1256 	if (!get_spsr(is_32bit, entry_func, &spsr)) {
1257 		*exit_status0 = 1; /* panic */
1258 		*exit_status1 = 0xbadbadba;
1259 		return 0;
1260 	}
1261 	return __thread_enter_user_mode(a0, a1, a2, a3, user_sp, entry_func,
1262 					spsr, exit_status0, exit_status1);
1263 }
1264 
1265 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
1266 void thread_get_user_kcode(struct mobj **mobj, size_t *offset,
1267 			   vaddr_t *va, size_t *sz)
1268 {
1269 	core_mmu_get_user_va_range(va, NULL);
1270 	*mobj = mobj_tee_ram;
1271 	*offset = thread_user_kcode_va - TEE_RAM_START;
1272 	*sz = thread_user_kcode_size;
1273 }
1274 #endif
1275 
1276 #if defined(CFG_CORE_UNMAP_CORE_AT_EL0) && \
1277 	defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
1278 void thread_get_user_kdata(struct mobj **mobj, size_t *offset,
1279 			   vaddr_t *va, size_t *sz)
1280 {
1281 	vaddr_t v;
1282 
1283 	core_mmu_get_user_va_range(&v, NULL);
1284 	*va = v + thread_user_kcode_size;
1285 	*mobj = mobj_tee_ram;
1286 	*offset = (vaddr_t)thread_user_kdata_page - TEE_RAM_START;
1287 	*sz = sizeof(thread_user_kdata_page);
1288 }
1289 #endif
1290 
1291 bool thread_disable_prealloc_rpc_cache(uint64_t *cookie)
1292 {
1293 	bool rv;
1294 	size_t n;
1295 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1296 
1297 	lock_global();
1298 
1299 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1300 		if (threads[n].state != THREAD_STATE_FREE) {
1301 			rv = false;
1302 			goto out;
1303 		}
1304 	}
1305 
1306 	rv = true;
1307 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1308 		if (threads[n].rpc_arg) {
1309 			*cookie = mobj_get_cookie(threads[n].rpc_mobj);
1310 			mobj_free(threads[n].rpc_mobj);
1311 			threads[n].rpc_arg = NULL;
1312 			goto out;
1313 		}
1314 	}
1315 
1316 	*cookie = 0;
1317 	thread_prealloc_rpc_cache = false;
1318 out:
1319 	unlock_global();
1320 	thread_unmask_exceptions(exceptions);
1321 	return rv;
1322 }
1323 
1324 bool thread_enable_prealloc_rpc_cache(void)
1325 {
1326 	bool rv;
1327 	size_t n;
1328 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1329 
1330 	lock_global();
1331 
1332 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1333 		if (threads[n].state != THREAD_STATE_FREE) {
1334 			rv = false;
1335 			goto out;
1336 		}
1337 	}
1338 
1339 	rv = true;
1340 	thread_prealloc_rpc_cache = true;
1341 out:
1342 	unlock_global();
1343 	thread_unmask_exceptions(exceptions);
1344 	return rv;
1345 }
1346 
1347 /**
1348  * Allocates data for struct optee_msg_arg.
1349  *
1350  * @size:	size in bytes of struct optee_msg_arg
1351  *
1352  * @returns	mobj that describes allocated buffer or NULL on error
1353  */
1354 static struct mobj *thread_rpc_alloc_arg(size_t size)
1355 {
1356 	paddr_t pa;
1357 	uint64_t co;
1358 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
1359 		OPTEE_SMC_RETURN_RPC_ALLOC, size
1360 	};
1361 	struct mobj *mobj = NULL;
1362 
1363 	thread_rpc(rpc_args);
1364 
1365 	pa = reg_pair_to_64(rpc_args[1], rpc_args[2]);
1366 	co = reg_pair_to_64(rpc_args[4], rpc_args[5]);
1367 
1368 	if (!ALIGNMENT_IS_OK(pa, struct optee_msg_arg))
1369 		goto err;
1370 
1371 	/* Check if this region is in static shared space */
1372 	if (core_pbuf_is(CORE_MEM_NSEC_SHM, pa, size))
1373 		mobj = mobj_shm_alloc(pa, size, co);
1374 	else if ((!(pa & SMALL_PAGE_MASK)) && size <= SMALL_PAGE_SIZE)
1375 		mobj = mobj_mapped_shm_alloc(&pa, 1, 0, co);
1376 
1377 	if (!mobj)
1378 		goto err;
1379 
1380 	return mobj;
1381 err:
1382 	thread_rpc_free_arg(co);
1383 	mobj_free(mobj);
1384 	return NULL;
1385 }
1386 
1387 static bool set_rmem(struct optee_msg_param *param,
1388 		     struct thread_param *tpm)
1389 {
1390 	param->attr = tpm->attr - THREAD_PARAM_ATTR_MEMREF_IN +
1391 		      OPTEE_MSG_ATTR_TYPE_RMEM_INPUT;
1392 	param->u.rmem.offs = tpm->u.memref.offs;
1393 	param->u.rmem.size = tpm->u.memref.size;
1394 	if (tpm->u.memref.mobj) {
1395 		param->u.rmem.shm_ref = mobj_get_cookie(tpm->u.memref.mobj);
1396 		if (!param->u.rmem.shm_ref)
1397 			return false;
1398 	} else {
1399 		param->u.rmem.shm_ref = 0;
1400 	}
1401 
1402 	return true;
1403 }
1404 
1405 static bool set_tmem(struct optee_msg_param *param,
1406 		     struct thread_param *tpm)
1407 {
1408 	paddr_t pa = 0;
1409 	uint64_t shm_ref = 0;
1410 	struct mobj *mobj = tpm->u.memref.mobj;
1411 
1412 	param->attr = tpm->attr - THREAD_PARAM_ATTR_MEMREF_IN +
1413 		      OPTEE_MSG_ATTR_TYPE_TMEM_INPUT;
1414 	if (mobj) {
1415 		shm_ref = mobj_get_cookie(mobj);
1416 		if (!shm_ref)
1417 			return false;
1418 		if (mobj_get_pa(mobj, tpm->u.memref.offs, 0, &pa))
1419 			return false;
1420 	}
1421 
1422 	param->u.tmem.size = tpm->u.memref.size;
1423 	param->u.tmem.buf_ptr = pa;
1424 	param->u.tmem.shm_ref = shm_ref;
1425 
1426 	return true;
1427 }
1428 
1429 static uint32_t get_rpc_arg(uint32_t cmd, size_t num_params,
1430 			    struct thread_param *params, void **arg_ret,
1431 			    uint64_t *carg_ret)
1432 {
1433 	struct thread_ctx *thr = threads + thread_get_id();
1434 	struct optee_msg_arg *arg = thr->rpc_arg;
1435 	size_t sz = OPTEE_MSG_GET_ARG_SIZE(THREAD_RPC_MAX_NUM_PARAMS);
1436 
1437 	if (num_params > THREAD_RPC_MAX_NUM_PARAMS)
1438 		return TEE_ERROR_BAD_PARAMETERS;
1439 
1440 	if (!arg) {
1441 		struct mobj *mobj = thread_rpc_alloc_arg(sz);
1442 
1443 		if (!mobj)
1444 			return TEE_ERROR_OUT_OF_MEMORY;
1445 
1446 		arg = mobj_get_va(mobj, 0);
1447 		if (!arg) {
1448 			thread_rpc_free_arg(mobj_get_cookie(mobj));
1449 			return TEE_ERROR_OUT_OF_MEMORY;
1450 		}
1451 
1452 		thr->rpc_arg = arg;
1453 		thr->rpc_mobj = mobj;
1454 	}
1455 
1456 	memset(arg, 0, OPTEE_MSG_GET_ARG_SIZE(num_params));
1457 	arg->cmd = cmd;
1458 	arg->num_params = num_params;
1459 	arg->ret = TEE_ERROR_GENERIC; /* in case value isn't updated */
1460 
1461 	for (size_t n = 0; n < num_params; n++) {
1462 		switch (params[n].attr) {
1463 		case THREAD_PARAM_ATTR_NONE:
1464 			arg->params[n].attr = OPTEE_MSG_ATTR_TYPE_NONE;
1465 			break;
1466 		case THREAD_PARAM_ATTR_VALUE_IN:
1467 		case THREAD_PARAM_ATTR_VALUE_OUT:
1468 		case THREAD_PARAM_ATTR_VALUE_INOUT:
1469 			arg->params[n].attr = params[n].attr -
1470 					      THREAD_PARAM_ATTR_VALUE_IN +
1471 					      OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
1472 			arg->params[n].u.value.a = params[n].u.value.a;
1473 			arg->params[n].u.value.b = params[n].u.value.b;
1474 			arg->params[n].u.value.c = params[n].u.value.c;
1475 			break;
1476 		case THREAD_PARAM_ATTR_MEMREF_IN:
1477 		case THREAD_PARAM_ATTR_MEMREF_OUT:
1478 		case THREAD_PARAM_ATTR_MEMREF_INOUT:
1479 			if (!params[n].u.memref.mobj ||
1480 			    mobj_matches(params[n].u.memref.mobj,
1481 					 CORE_MEM_NSEC_SHM)) {
1482 				if (!set_tmem(arg->params + n, params + n))
1483 					return TEE_ERROR_BAD_PARAMETERS;
1484 			} else  if (mobj_matches(params[n].u.memref.mobj,
1485 						 CORE_MEM_REG_SHM)) {
1486 				if (!set_rmem(arg->params + n, params + n))
1487 					return TEE_ERROR_BAD_PARAMETERS;
1488 			} else {
1489 				return TEE_ERROR_BAD_PARAMETERS;
1490 			}
1491 			break;
1492 		default:
1493 			return TEE_ERROR_BAD_PARAMETERS;
1494 		}
1495 	}
1496 
1497 	*arg_ret = arg;
1498 	*carg_ret = mobj_get_cookie(thr->rpc_mobj);
1499 
1500 	return TEE_SUCCESS;
1501 }
1502 
1503 static uint32_t get_rpc_arg_res(struct optee_msg_arg *arg, size_t num_params,
1504 				struct thread_param *params)
1505 {
1506 	for (size_t n = 0; n < num_params; n++) {
1507 		switch (params[n].attr) {
1508 		case THREAD_PARAM_ATTR_VALUE_OUT:
1509 		case THREAD_PARAM_ATTR_VALUE_INOUT:
1510 			params[n].u.value.a = arg->params[n].u.value.a;
1511 			params[n].u.value.b = arg->params[n].u.value.b;
1512 			params[n].u.value.c = arg->params[n].u.value.c;
1513 			break;
1514 		case THREAD_PARAM_ATTR_MEMREF_OUT:
1515 		case THREAD_PARAM_ATTR_MEMREF_INOUT:
1516 			/*
1517 			 * rmem.size and tmem.size is the same type and
1518 			 * location.
1519 			 */
1520 			params[n].u.memref.size = arg->params[n].u.rmem.size;
1521 			break;
1522 		default:
1523 			break;
1524 		}
1525 	}
1526 
1527 	return arg->ret;
1528 }
1529 
1530 uint32_t thread_rpc_cmd(uint32_t cmd, size_t num_params,
1531 			struct thread_param *params)
1532 {
1533 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1534 	void *arg = NULL;
1535 	uint64_t carg = 0;
1536 	uint32_t ret = 0;
1537 
1538 	/* The source CRYPTO_RNG_SRC_JITTER_RPC is safe to use here */
1539 	plat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_RPC,
1540 				     &thread_rpc_pnum);
1541 
1542 	ret = get_rpc_arg(cmd, num_params, params, &arg, &carg);
1543 	if (ret)
1544 		return ret;
1545 
1546 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1547 	thread_rpc(rpc_args);
1548 
1549 	return get_rpc_arg_res(arg, num_params, params);
1550 }
1551 
1552 /**
1553  * Free physical memory previously allocated with thread_rpc_alloc()
1554  *
1555  * @cookie:	cookie received when allocating the buffer
1556  * @bt:		must be the same as supplied when allocating
1557  * @mobj:	mobj that describes allocated buffer
1558  *
1559  * This function also frees corresponding mobj.
1560  */
1561 static void thread_rpc_free(unsigned int bt, uint64_t cookie, struct mobj *mobj)
1562 {
1563 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1564 	void *arg = NULL;
1565 	uint64_t carg = 0;
1566 	struct thread_param param = THREAD_PARAM_VALUE(IN, bt, cookie, 0);
1567 	uint32_t ret = get_rpc_arg(OPTEE_RPC_CMD_SHM_FREE, 1, &param,
1568 				   &arg, &carg);
1569 
1570 	mobj_free(mobj);
1571 
1572 	if (!ret) {
1573 		reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1574 		thread_rpc(rpc_args);
1575 	}
1576 }
1577 
1578 static struct mobj *get_rpc_alloc_res(struct optee_msg_arg *arg,
1579 				      unsigned int bt)
1580 {
1581 	struct mobj *mobj = NULL;
1582 	uint64_t cookie = 0;
1583 
1584 	if (arg->ret || arg->num_params != 1)
1585 		return NULL;
1586 
1587 	if (arg->params[0].attr == OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT) {
1588 		cookie = arg->params[0].u.tmem.shm_ref;
1589 		mobj = mobj_shm_alloc(arg->params[0].u.tmem.buf_ptr,
1590 				      arg->params[0].u.tmem.size,
1591 				      cookie);
1592 	} else if (arg->params[0].attr == (OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT |
1593 					   OPTEE_MSG_ATTR_NONCONTIG)) {
1594 		cookie = arg->params[0].u.tmem.shm_ref;
1595 		mobj = msg_param_mobj_from_noncontig(
1596 			arg->params[0].u.tmem.buf_ptr,
1597 			arg->params[0].u.tmem.size,
1598 			cookie,
1599 			true);
1600 	} else {
1601 		return NULL;
1602 	}
1603 
1604 	if (!mobj) {
1605 		thread_rpc_free(bt, cookie, mobj);
1606 		return NULL;
1607 	}
1608 
1609 	assert(mobj_is_nonsec(mobj));
1610 
1611 	return mobj;
1612 }
1613 
1614 /**
1615  * Allocates shared memory buffer via RPC
1616  *
1617  * @size:	size in bytes of shared memory buffer
1618  * @align:	required alignment of buffer
1619  * @bt:		buffer type OPTEE_RPC_SHM_TYPE_*
1620  *
1621  * Returns a pointer to MOBJ for the memory on success, or NULL on failure.
1622  */
1623 static struct mobj *thread_rpc_alloc(size_t size, size_t align, unsigned int bt)
1624 {
1625 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1626 	void *arg = NULL;
1627 	uint64_t carg = 0;
1628 	struct thread_param param = THREAD_PARAM_VALUE(IN, bt, size, align);
1629 	uint32_t ret = get_rpc_arg(OPTEE_RPC_CMD_SHM_ALLOC, 1, &param,
1630 				   &arg, &carg);
1631 
1632 	if (ret)
1633 		return NULL;
1634 
1635 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1636 	thread_rpc(rpc_args);
1637 
1638 	return get_rpc_alloc_res(arg, bt);
1639 }
1640 
1641 struct mobj *thread_rpc_alloc_payload(size_t size)
1642 {
1643 	return thread_rpc_alloc(size, 8, OPTEE_RPC_SHM_TYPE_APPL);
1644 }
1645 
1646 void thread_rpc_free_payload(struct mobj *mobj)
1647 {
1648 	thread_rpc_free(OPTEE_RPC_SHM_TYPE_APPL, mobj_get_cookie(mobj),
1649 			mobj);
1650 }
1651 
1652 struct mobj *thread_rpc_alloc_global_payload(size_t size)
1653 {
1654 	return thread_rpc_alloc(size, 8, OPTEE_RPC_SHM_TYPE_GLOBAL);
1655 }
1656 
1657 void thread_rpc_free_global_payload(struct mobj *mobj)
1658 {
1659 	thread_rpc_free(OPTEE_RPC_SHM_TYPE_GLOBAL, mobj_get_cookie(mobj),
1660 			mobj);
1661 }
1662