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