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