xref: /optee_os/core/arch/arm/kernel/thread.c (revision 983d02116743476904b68d52ca432d0f79c38c43)
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/tee_ta_manager.h>
37 #include <kernel/thread.h>
38 #include <kernel/thread_defs.h>
39 #include <kernel/tz_proc.h>
40 #include <kernel/tz_proc_def.h>
41 #include <mm/core_memprot.h>
42 #include <mm/tee_mm.h>
43 #include <mm/tee_mmu.h>
44 #include <mm/tee_mmu_defs.h>
45 #include <mm/tee_pager.h>
46 #include <optee_msg.h>
47 #include <sm/optee_smc.h>
48 #include <sm/sm_defs.h>
49 #include <sm/sm.h>
50 #include <trace.h>
51 #include <util.h>
52 
53 #include "thread_private.h"
54 
55 #ifdef ARM32
56 #ifdef CFG_CORE_SANITIZE_KADDRESS
57 #define STACK_TMP_SIZE		3072
58 #else
59 #define STACK_TMP_SIZE		1024
60 #endif
61 #define STACK_THREAD_SIZE	8192
62 
63 #if TRACE_LEVEL > 0
64 #ifdef CFG_CORE_SANITIZE_KADDRESS
65 #define STACK_ABT_SIZE		3072
66 #else
67 #define STACK_ABT_SIZE		2048
68 #endif
69 #else
70 #define STACK_ABT_SIZE		1024
71 #endif
72 
73 #endif /*ARM32*/
74 
75 #ifdef ARM64
76 #define STACK_TMP_SIZE		2048
77 #define STACK_THREAD_SIZE	8192
78 
79 #if TRACE_LEVEL > 0
80 #define STACK_ABT_SIZE		3072
81 #else
82 #define STACK_ABT_SIZE		1024
83 #endif
84 #endif /*ARM64*/
85 
86 #define RPC_MAX_NUM_PARAMS	2
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 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
123 DECLARE_STACK(stack_sm, CFG_TEE_CORE_NB_CORE, SM_STACK_SIZE, static);
124 #endif
125 #ifndef CFG_WITH_PAGER
126 DECLARE_STACK(stack_thread, CFG_NUM_THREADS, STACK_THREAD_SIZE, static);
127 #endif
128 
129 const uint32_t stack_tmp_stride = STACK_SIZE(stack_tmp[0]);
130 
131 KEEP_PAGER(stack_tmp);
132 KEEP_PAGER(stack_tmp_stride);
133 
134 thread_smc_handler_t thread_std_smc_handler_ptr;
135 static thread_smc_handler_t thread_fast_smc_handler_ptr;
136 thread_fiq_handler_t thread_fiq_handler_ptr;
137 thread_pm_handler_t thread_cpu_on_handler_ptr;
138 thread_pm_handler_t thread_cpu_off_handler_ptr;
139 thread_pm_handler_t thread_cpu_suspend_handler_ptr;
140 thread_pm_handler_t thread_cpu_resume_handler_ptr;
141 thread_pm_handler_t thread_system_off_handler_ptr;
142 thread_pm_handler_t thread_system_reset_handler_ptr;
143 
144 
145 static unsigned int thread_global_lock = SPINLOCK_UNLOCK;
146 static bool thread_prealloc_rpc_cache;
147 
148 static void init_canaries(void)
149 {
150 #ifdef CFG_WITH_STACK_CANARIES
151 	size_t n;
152 #define INIT_CANARY(name)						\
153 	for (n = 0; n < ARRAY_SIZE(name); n++) {			\
154 		uint32_t *start_canary = &GET_START_CANARY(name, n);	\
155 		uint32_t *end_canary = &GET_END_CANARY(name, n);	\
156 									\
157 		*start_canary = START_CANARY_VALUE;			\
158 		*end_canary = END_CANARY_VALUE;				\
159 		DMSG("#Stack canaries for %s[%zu] with top at %p\n",	\
160 			#name, n, (void *)(end_canary - 1));		\
161 		DMSG("watch *%p\n", (void *)end_canary);		\
162 	}
163 
164 	INIT_CANARY(stack_tmp);
165 	INIT_CANARY(stack_abt);
166 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
167 	INIT_CANARY(stack_sm);
168 #endif
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 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
201 	for (n = 0; n < ARRAY_SIZE(stack_sm); n++) {
202 		if (GET_START_CANARY(stack_sm, n) != START_CANARY_VALUE)
203 			CANARY_DIED(stack_sm, start, n);
204 		if (GET_END_CANARY(stack_sm, n) != END_CANARY_VALUE)
205 			CANARY_DIED(stack_sm, end, n);
206 	}
207 #endif
208 #ifndef CFG_WITH_PAGER
209 	for (n = 0; n < ARRAY_SIZE(stack_thread); n++) {
210 		if (GET_START_CANARY(stack_thread, n) != START_CANARY_VALUE)
211 			CANARY_DIED(stack_thread, start, n);
212 		if (GET_END_CANARY(stack_thread, n) != END_CANARY_VALUE)
213 			CANARY_DIED(stack_thread, end, n);
214 	}
215 #endif
216 #endif/*CFG_WITH_STACK_CANARIES*/
217 }
218 
219 static void lock_global(void)
220 {
221 	cpu_spin_lock(&thread_global_lock);
222 }
223 
224 static void unlock_global(void)
225 {
226 	cpu_spin_unlock(&thread_global_lock);
227 }
228 
229 #ifdef ARM32
230 uint32_t thread_get_exceptions(void)
231 {
232 	uint32_t cpsr = read_cpsr();
233 
234 	return (cpsr >> CPSR_F_SHIFT) & THREAD_EXCP_ALL;
235 }
236 
237 void thread_set_exceptions(uint32_t exceptions)
238 {
239 	uint32_t cpsr = read_cpsr();
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 	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 	 * IRQs must be disabled before playing with core_local since
285 	 * we otherwise may be rescheduled to a different core in the
286 	 * middle of this function.
287 	 */
288 	assert(thread_get_exceptions() & THREAD_EXCP_IRQ);
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 IRQ, masked Asynchronous
338 	 * abort and unmasked FIQ.
339 	  */
340 	thread->regs.cpsr = read_cpsr() & ARM32_CPSR_E;
341 	thread->regs.cpsr |= CPSR_MODE_SVC | CPSR_I | CPSR_A;
342 	/* Enable thumb mode if it's a thumb instruction */
343 	if (thread->regs.pc & 1)
344 		thread->regs.cpsr |= CPSR_T;
345 	/* Reinitialize stack pointer */
346 	thread->regs.svc_sp = thread->stack_va_end;
347 
348 	/*
349 	 * Copy arguments into context. This will make the
350 	 * arguments appear in r0-r7 when thread is started.
351 	 */
352 	thread->regs.r0 = args->a0;
353 	thread->regs.r1 = args->a1;
354 	thread->regs.r2 = args->a2;
355 	thread->regs.r3 = args->a3;
356 	thread->regs.r4 = args->a4;
357 	thread->regs.r5 = args->a5;
358 	thread->regs.r6 = args->a6;
359 	thread->regs.r7 = args->a7;
360 }
361 #endif /*ARM32*/
362 
363 #ifdef ARM64
364 static void init_regs(struct thread_ctx *thread,
365 		struct thread_smc_args *args)
366 {
367 	thread->regs.pc = (uint64_t)thread_std_smc_entry;
368 
369 	/*
370 	 * Stdcalls starts in SVC mode with masked IRQ, masked Asynchronous
371 	 * abort and unmasked FIQ.
372 	  */
373 	thread->regs.cpsr = SPSR_64(SPSR_64_MODE_EL1, SPSR_64_MODE_SP_EL0,
374 				    DAIFBIT_IRQ | DAIFBIT_ABT);
375 	/* Reinitialize stack pointer */
376 	thread->regs.sp = thread->stack_va_end;
377 
378 	/*
379 	 * Copy arguments into context. This will make the
380 	 * arguments appear in x0-x7 when thread is started.
381 	 */
382 	thread->regs.x[0] = args->a0;
383 	thread->regs.x[1] = args->a1;
384 	thread->regs.x[2] = args->a2;
385 	thread->regs.x[3] = args->a3;
386 	thread->regs.x[4] = args->a4;
387 	thread->regs.x[5] = args->a5;
388 	thread->regs.x[6] = args->a6;
389 	thread->regs.x[7] = args->a7;
390 
391 	/* Set up frame pointer as per the Aarch64 AAPCS */
392 	thread->regs.x[29] = 0;
393 }
394 #endif /*ARM64*/
395 
396 void thread_init_boot_thread(void)
397 {
398 	struct thread_core_local *l = thread_get_core_local();
399 	size_t n;
400 
401 	for (n = 0; n < CFG_NUM_THREADS; n++) {
402 		TAILQ_INIT(&threads[n].mutexes);
403 		TAILQ_INIT(&threads[n].tsd.sess_stack);
404 #ifdef CFG_SMALL_PAGE_USER_TA
405 		SLIST_INIT(&threads[n].tsd.pgt_cache);
406 #endif
407 	}
408 
409 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++)
410 		thread_core_local[n].curr_thread = -1;
411 
412 	l->curr_thread = 0;
413 	threads[0].state = THREAD_STATE_ACTIVE;
414 }
415 
416 void thread_clr_boot_thread(void)
417 {
418 	struct thread_core_local *l = thread_get_core_local();
419 
420 	assert(l->curr_thread >= 0 && l->curr_thread < CFG_NUM_THREADS);
421 	assert(threads[l->curr_thread].state == THREAD_STATE_ACTIVE);
422 	assert(TAILQ_EMPTY(&threads[l->curr_thread].mutexes));
423 	threads[l->curr_thread].state = THREAD_STATE_FREE;
424 	l->curr_thread = -1;
425 }
426 
427 static void thread_alloc_and_run(struct thread_smc_args *args)
428 {
429 	size_t n;
430 	struct thread_core_local *l = thread_get_core_local();
431 	bool found_thread = false;
432 
433 	assert(l->curr_thread == -1);
434 
435 	lock_global();
436 
437 	for (n = 0; n < CFG_NUM_THREADS; n++) {
438 		if (threads[n].state == THREAD_STATE_FREE) {
439 			threads[n].state = THREAD_STATE_ACTIVE;
440 			found_thread = true;
441 			break;
442 		}
443 	}
444 
445 	unlock_global();
446 
447 	if (!found_thread) {
448 		args->a0 = OPTEE_SMC_RETURN_ETHREAD_LIMIT;
449 		return;
450 	}
451 
452 	l->curr_thread = n;
453 
454 	threads[n].flags = 0;
455 	init_regs(threads + n, args);
456 
457 	/* Save Hypervisor Client ID */
458 	threads[n].hyp_clnt_id = args->a7;
459 
460 	thread_lazy_save_ns_vfp();
461 	thread_resume(&threads[n].regs);
462 }
463 
464 #ifdef ARM32
465 static void copy_a0_to_a5(struct thread_ctx_regs *regs,
466 		struct thread_smc_args *args)
467 {
468 	/*
469 	 * Update returned values from RPC, values will appear in
470 	 * r0-r3 when thread is resumed.
471 	 */
472 	regs->r0 = args->a0;
473 	regs->r1 = args->a1;
474 	regs->r2 = args->a2;
475 	regs->r3 = args->a3;
476 	regs->r4 = args->a4;
477 	regs->r5 = args->a5;
478 }
479 #endif /*ARM32*/
480 
481 #ifdef ARM64
482 static void copy_a0_to_a5(struct thread_ctx_regs *regs,
483 		struct thread_smc_args *args)
484 {
485 	/*
486 	 * Update returned values from RPC, values will appear in
487 	 * x0-x3 when thread is resumed.
488 	 */
489 	regs->x[0] = args->a0;
490 	regs->x[1] = args->a1;
491 	regs->x[2] = args->a2;
492 	regs->x[3] = args->a3;
493 	regs->x[4] = args->a4;
494 	regs->x[5] = args->a5;
495 }
496 #endif /*ARM64*/
497 
498 static void thread_resume_from_rpc(struct thread_smc_args *args)
499 {
500 	size_t n = args->a3; /* thread id */
501 	struct thread_core_local *l = thread_get_core_local();
502 	uint32_t rv = 0;
503 
504 	assert(l->curr_thread == -1);
505 
506 	lock_global();
507 
508 	if (n < CFG_NUM_THREADS &&
509 	    threads[n].state == THREAD_STATE_SUSPENDED &&
510 	    args->a7 == threads[n].hyp_clnt_id)
511 		threads[n].state = THREAD_STATE_ACTIVE;
512 	else
513 		rv = OPTEE_SMC_RETURN_ERESUME;
514 
515 	unlock_global();
516 
517 	if (rv) {
518 		args->a0 = rv;
519 		return;
520 	}
521 
522 	l->curr_thread = n;
523 
524 	if (threads[n].have_user_map)
525 		core_mmu_set_user_map(&threads[n].user_map);
526 
527 	/*
528 	 * Return from RPC to request service of an IRQ must not
529 	 * get parameters from non-secure world.
530 	 */
531 	if (threads[n].flags & THREAD_FLAGS_COPY_ARGS_ON_RETURN) {
532 		copy_a0_to_a5(&threads[n].regs, args);
533 		threads[n].flags &= ~THREAD_FLAGS_COPY_ARGS_ON_RETURN;
534 	}
535 
536 	thread_lazy_save_ns_vfp();
537 	thread_resume(&threads[n].regs);
538 }
539 
540 void thread_handle_fast_smc(struct thread_smc_args *args)
541 {
542 	thread_check_canaries();
543 	thread_fast_smc_handler_ptr(args);
544 	/* Fast handlers must not unmask any exceptions */
545 	assert(thread_get_exceptions() == THREAD_EXCP_ALL);
546 }
547 
548 void thread_handle_std_smc(struct thread_smc_args *args)
549 {
550 	thread_check_canaries();
551 
552 	if (args->a0 == OPTEE_SMC_CALL_RETURN_FROM_RPC)
553 		thread_resume_from_rpc(args);
554 	else
555 		thread_alloc_and_run(args);
556 }
557 
558 /* Helper routine for the assembly function thread_std_smc_entry() */
559 void __thread_std_smc_entry(struct thread_smc_args *args)
560 {
561 	struct thread_ctx *thr = threads + thread_get_id();
562 
563 	if (!thr->rpc_arg) {
564 		paddr_t parg;
565 		uint64_t carg;
566 		void *arg;
567 
568 		thread_rpc_alloc_arg(
569 			OPTEE_MSG_GET_ARG_SIZE(RPC_MAX_NUM_PARAMS),
570 			&parg, &carg);
571 		if (!parg || !ALIGNMENT_IS_OK(parg, struct optee_msg_arg) ||
572 		    !(arg = phys_to_virt(parg, CORE_MEM_NSEC_SHM))) {
573 			thread_rpc_free_arg(carg);
574 			args->a0 = OPTEE_SMC_RETURN_ENOMEM;
575 			return;
576 		}
577 
578 		thr->rpc_arg = arg;
579 		thr->rpc_carg = carg;
580 	}
581 
582 	thread_std_smc_handler_ptr(args);
583 
584 	if (!thread_prealloc_rpc_cache) {
585 		thread_rpc_free_arg(thr->rpc_carg);
586 		thr->rpc_carg = 0;
587 		thr->rpc_arg = 0;
588 	}
589 }
590 
591 void *thread_get_tmp_sp(void)
592 {
593 	struct thread_core_local *l = thread_get_core_local();
594 
595 	return (void *)l->tmp_stack_va_end;
596 }
597 
598 #ifdef ARM64
599 vaddr_t thread_get_saved_thread_sp(void)
600 {
601 	struct thread_core_local *l = thread_get_core_local();
602 	int ct = l->curr_thread;
603 
604 	assert(ct != -1);
605 	return threads[ct].kern_sp;
606 }
607 #endif /*ARM64*/
608 
609 bool thread_addr_is_in_stack(vaddr_t va)
610 {
611 	struct thread_ctx *thr = threads + thread_get_id();
612 
613 	return va < thr->stack_va_end &&
614 	       va >= (thr->stack_va_end - STACK_THREAD_SIZE);
615 }
616 
617 void thread_state_free(void)
618 {
619 	struct thread_core_local *l = thread_get_core_local();
620 	int ct = l->curr_thread;
621 
622 	assert(ct != -1);
623 	assert(TAILQ_EMPTY(&threads[ct].mutexes));
624 
625 	thread_lazy_restore_ns_vfp();
626 	tee_pager_release_phys(
627 		(void *)(threads[ct].stack_va_end - STACK_THREAD_SIZE),
628 		STACK_THREAD_SIZE);
629 
630 	lock_global();
631 
632 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
633 	threads[ct].state = THREAD_STATE_FREE;
634 	threads[ct].flags = 0;
635 	l->curr_thread = -1;
636 
637 	unlock_global();
638 }
639 
640 #ifdef ARM32
641 static bool is_from_user(uint32_t cpsr)
642 {
643 	return (cpsr & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_USR;
644 }
645 #endif
646 
647 #ifdef ARM64
648 static bool is_from_user(uint32_t cpsr)
649 {
650 	if (cpsr & (SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT))
651 		return true;
652 	if (((cpsr >> SPSR_64_MODE_EL_SHIFT) & SPSR_64_MODE_EL_MASK) ==
653 	     SPSR_64_MODE_EL0)
654 		return true;
655 	return false;
656 }
657 #endif
658 
659 #ifdef CFG_WITH_PAGER
660 static void release_unused_kernel_stack(struct thread_ctx *thr)
661 {
662 	vaddr_t sp = thr->regs.svc_sp;
663 	vaddr_t base = thr->stack_va_end - STACK_THREAD_SIZE;
664 	size_t len = sp - base;
665 
666 	tee_pager_release_phys((void *)base, len);
667 }
668 #else
669 static void release_unused_kernel_stack(struct thread_ctx *thr __unused)
670 {
671 }
672 #endif
673 
674 int thread_state_suspend(uint32_t flags, uint32_t cpsr, vaddr_t pc)
675 {
676 	struct thread_core_local *l = thread_get_core_local();
677 	int ct = l->curr_thread;
678 
679 	assert(ct != -1);
680 
681 	thread_check_canaries();
682 
683 	release_unused_kernel_stack(threads + ct);
684 
685 	if (is_from_user(cpsr))
686 		thread_user_save_vfp();
687 	thread_lazy_restore_ns_vfp();
688 
689 	lock_global();
690 
691 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
692 	threads[ct].flags |= flags;
693 	threads[ct].regs.cpsr = cpsr;
694 	threads[ct].regs.pc = pc;
695 	threads[ct].state = THREAD_STATE_SUSPENDED;
696 
697 	threads[ct].have_user_map = core_mmu_user_mapping_is_active();
698 	if (threads[ct].have_user_map) {
699 		core_mmu_get_user_map(&threads[ct].user_map);
700 		core_mmu_set_user_map(NULL);
701 	}
702 
703 	l->curr_thread = -1;
704 
705 	unlock_global();
706 
707 	return ct;
708 }
709 
710 #ifdef ARM32
711 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
712 {
713 	l->tmp_stack_va_end = sp;
714 	thread_set_irq_sp(sp);
715 	thread_set_fiq_sp(sp);
716 }
717 
718 static void set_abt_stack(struct thread_core_local *l __unused, vaddr_t sp)
719 {
720 	thread_set_abt_sp(sp);
721 }
722 #endif /*ARM32*/
723 
724 #ifdef ARM64
725 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
726 {
727 	/*
728 	 * We're already using the tmp stack when this function is called
729 	 * so there's no need to assign it to any stack pointer. However,
730 	 * we'll need to restore it at different times so store it here.
731 	 */
732 	l->tmp_stack_va_end = sp;
733 }
734 
735 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
736 {
737 	l->abt_stack_va_end = sp;
738 }
739 #endif /*ARM64*/
740 
741 bool thread_init_stack(uint32_t thread_id, vaddr_t sp)
742 {
743 	if (thread_id >= CFG_NUM_THREADS)
744 		return false;
745 	threads[thread_id].stack_va_end = sp;
746 	return true;
747 }
748 
749 int thread_get_id_may_fail(void)
750 {
751 	/* thread_get_core_local() requires IRQs to be disabled */
752 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ);
753 	struct thread_core_local *l = thread_get_core_local();
754 	int ct = l->curr_thread;
755 
756 	thread_unmask_exceptions(exceptions);
757 	return ct;
758 }
759 
760 int thread_get_id(void)
761 {
762 	int ct = thread_get_id_may_fail();
763 
764 	assert(ct >= 0 && ct < CFG_NUM_THREADS);
765 	return ct;
766 }
767 
768 static void init_handlers(const struct thread_handlers *handlers)
769 {
770 	thread_std_smc_handler_ptr = handlers->std_smc;
771 	thread_fast_smc_handler_ptr = handlers->fast_smc;
772 	thread_fiq_handler_ptr = handlers->fiq;
773 	thread_cpu_on_handler_ptr = handlers->cpu_on;
774 	thread_cpu_off_handler_ptr = handlers->cpu_off;
775 	thread_cpu_suspend_handler_ptr = handlers->cpu_suspend;
776 	thread_cpu_resume_handler_ptr = handlers->cpu_resume;
777 	thread_system_off_handler_ptr = handlers->system_off;
778 	thread_system_reset_handler_ptr = handlers->system_reset;
779 }
780 
781 #ifdef CFG_WITH_PAGER
782 static void init_thread_stacks(void)
783 {
784 	size_t n;
785 
786 	/*
787 	 * Allocate virtual memory for thread stacks.
788 	 */
789 	for (n = 0; n < CFG_NUM_THREADS; n++) {
790 		tee_mm_entry_t *mm;
791 		vaddr_t sp;
792 
793 		/* Find vmem for thread stack and its protection gap */
794 		mm = tee_mm_alloc(&tee_mm_vcore,
795 				  SMALL_PAGE_SIZE + STACK_THREAD_SIZE);
796 		assert(mm);
797 
798 		/* Claim eventual physical page */
799 		tee_pager_add_pages(tee_mm_get_smem(mm), tee_mm_get_size(mm),
800 				    true);
801 
802 		/* Add the area to the pager */
803 		tee_pager_add_core_area(tee_mm_get_smem(mm) + SMALL_PAGE_SIZE,
804 					tee_mm_get_bytes(mm) - SMALL_PAGE_SIZE,
805 					TEE_MATTR_PRW | TEE_MATTR_LOCKED,
806 					NULL, NULL);
807 
808 		/* init effective stack */
809 		sp = tee_mm_get_smem(mm) + tee_mm_get_bytes(mm);
810 		if (!thread_init_stack(n, sp))
811 			panic("init stack failed");
812 	}
813 }
814 #else
815 static void init_thread_stacks(void)
816 {
817 	size_t n;
818 
819 	/* Assign the thread stacks */
820 	for (n = 0; n < CFG_NUM_THREADS; n++) {
821 		if (!thread_init_stack(n, GET_STACK(stack_thread[n])))
822 			panic("thread_init_stack failed");
823 	}
824 }
825 #endif /*CFG_WITH_PAGER*/
826 
827 void thread_init_primary(const struct thread_handlers *handlers)
828 {
829 	init_handlers(handlers);
830 
831 	/* Initialize canaries around the stacks */
832 	init_canaries();
833 
834 	init_thread_stacks();
835 	pgt_init();
836 }
837 
838 static void init_sec_mon(size_t pos __maybe_unused)
839 {
840 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
841 	/* Initialize secure monitor */
842 	sm_init(GET_STACK(stack_sm[pos]));
843 	sm_set_entry_vector(thread_vector_table);
844 #endif
845 }
846 
847 void thread_init_per_cpu(void)
848 {
849 	size_t pos = get_core_pos();
850 	struct thread_core_local *l = thread_get_core_local();
851 
852 	init_sec_mon(pos);
853 
854 	set_tmp_stack(l, GET_STACK(stack_tmp[pos]));
855 	set_abt_stack(l, GET_STACK(stack_abt[pos]));
856 
857 	thread_init_vbar();
858 }
859 
860 struct thread_specific_data *thread_get_tsd(void)
861 {
862 	return &threads[thread_get_id()].tsd;
863 }
864 
865 struct thread_ctx_regs *thread_get_ctx_regs(void)
866 {
867 	struct thread_core_local *l = thread_get_core_local();
868 
869 	assert(l->curr_thread != -1);
870 	return &threads[l->curr_thread].regs;
871 }
872 
873 void thread_set_irq(bool enable)
874 {
875 	/* thread_get_core_local() requires IRQs to be disabled */
876 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ);
877 	struct thread_core_local *l;
878 
879 	l = thread_get_core_local();
880 
881 	assert(l->curr_thread != -1);
882 
883 	if (enable) {
884 		threads[l->curr_thread].flags |= THREAD_FLAGS_IRQ_ENABLE;
885 		thread_set_exceptions(exceptions & ~THREAD_EXCP_IRQ);
886 	} else {
887 		/*
888 		 * No need to disable IRQ here since it's already disabled
889 		 * above.
890 		 */
891 		threads[l->curr_thread].flags &= ~THREAD_FLAGS_IRQ_ENABLE;
892 	}
893 }
894 
895 void thread_restore_irq(void)
896 {
897 	/* thread_get_core_local() requires IRQs to be disabled */
898 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ);
899 	struct thread_core_local *l;
900 
901 	l = thread_get_core_local();
902 
903 	assert(l->curr_thread != -1);
904 
905 	if (threads[l->curr_thread].flags & THREAD_FLAGS_IRQ_ENABLE)
906 		thread_set_exceptions(exceptions & ~THREAD_EXCP_IRQ);
907 }
908 
909 #ifdef CFG_WITH_VFP
910 uint32_t thread_kernel_enable_vfp(void)
911 {
912 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ);
913 	struct thread_ctx *thr = threads + thread_get_id();
914 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
915 
916 	assert(!vfp_is_enabled());
917 
918 	if (!thr->vfp_state.ns_saved) {
919 		vfp_lazy_save_state_final(&thr->vfp_state.ns);
920 		thr->vfp_state.ns_saved = true;
921 	} else if (thr->vfp_state.sec_lazy_saved &&
922 		   !thr->vfp_state.sec_saved) {
923 		/*
924 		 * This happens when we're handling an abort while the
925 		 * thread was using the VFP state.
926 		 */
927 		vfp_lazy_save_state_final(&thr->vfp_state.sec);
928 		thr->vfp_state.sec_saved = true;
929 	} else if (tuv && tuv->lazy_saved && !tuv->saved) {
930 		/*
931 		 * This can happen either during syscall or abort
932 		 * processing (while processing a syscall).
933 		 */
934 		vfp_lazy_save_state_final(&tuv->vfp);
935 		tuv->saved = true;
936 	}
937 
938 	vfp_enable();
939 	return exceptions;
940 }
941 
942 void thread_kernel_disable_vfp(uint32_t state)
943 {
944 	uint32_t exceptions;
945 
946 	assert(vfp_is_enabled());
947 
948 	vfp_disable();
949 	exceptions = thread_get_exceptions();
950 	assert(exceptions & THREAD_EXCP_IRQ);
951 	exceptions &= ~THREAD_EXCP_IRQ;
952 	exceptions |= state & THREAD_EXCP_IRQ;
953 	thread_set_exceptions(exceptions);
954 }
955 
956 void thread_kernel_save_vfp(void)
957 {
958 	struct thread_ctx *thr = threads + thread_get_id();
959 
960 	assert(thread_get_exceptions() & THREAD_EXCP_IRQ);
961 	if (vfp_is_enabled()) {
962 		vfp_lazy_save_state_init(&thr->vfp_state.sec);
963 		thr->vfp_state.sec_lazy_saved = true;
964 	}
965 }
966 
967 void thread_kernel_restore_vfp(void)
968 {
969 	struct thread_ctx *thr = threads + thread_get_id();
970 
971 	assert(thread_get_exceptions() & THREAD_EXCP_IRQ);
972 	assert(!vfp_is_enabled());
973 	if (thr->vfp_state.sec_lazy_saved) {
974 		vfp_lazy_restore_state(&thr->vfp_state.sec,
975 				       thr->vfp_state.sec_saved);
976 		thr->vfp_state.sec_saved = false;
977 		thr->vfp_state.sec_lazy_saved = false;
978 	}
979 }
980 
981 void thread_user_enable_vfp(struct thread_user_vfp_state *uvfp)
982 {
983 	struct thread_ctx *thr = threads + thread_get_id();
984 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
985 
986 	assert(thread_get_exceptions() & THREAD_EXCP_IRQ);
987 	assert(!vfp_is_enabled());
988 
989 	if (!thr->vfp_state.ns_saved) {
990 		vfp_lazy_save_state_final(&thr->vfp_state.ns);
991 		thr->vfp_state.ns_saved = true;
992 	} else if (tuv && uvfp != tuv) {
993 		if (tuv->lazy_saved && !tuv->saved) {
994 			vfp_lazy_save_state_final(&tuv->vfp);
995 			tuv->saved = true;
996 		}
997 	}
998 
999 	if (uvfp->lazy_saved)
1000 		vfp_lazy_restore_state(&uvfp->vfp, uvfp->saved);
1001 	uvfp->lazy_saved = false;
1002 	uvfp->saved = false;
1003 
1004 	thr->vfp_state.uvfp = uvfp;
1005 	vfp_enable();
1006 }
1007 
1008 void thread_user_save_vfp(void)
1009 {
1010 	struct thread_ctx *thr = threads + thread_get_id();
1011 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1012 
1013 	assert(thread_get_exceptions() & THREAD_EXCP_IRQ);
1014 	if (!vfp_is_enabled())
1015 		return;
1016 
1017 	assert(tuv && !tuv->lazy_saved && !tuv->saved);
1018 	vfp_lazy_save_state_init(&tuv->vfp);
1019 	tuv->lazy_saved = true;
1020 }
1021 
1022 void thread_user_clear_vfp(struct thread_user_vfp_state *uvfp)
1023 {
1024 	struct thread_ctx *thr = threads + thread_get_id();
1025 
1026 	if (uvfp == thr->vfp_state.uvfp)
1027 		thr->vfp_state.uvfp = NULL;
1028 	uvfp->lazy_saved = false;
1029 	uvfp->saved = false;
1030 }
1031 #endif /*CFG_WITH_VFP*/
1032 
1033 #ifdef ARM32
1034 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1035 {
1036 	uint32_t s;
1037 
1038 	if (!is_32bit)
1039 		return false;
1040 
1041 	s = read_spsr();
1042 	s &= ~(CPSR_MODE_MASK | CPSR_T | CPSR_IT_MASK1 | CPSR_IT_MASK2);
1043 	s |= CPSR_MODE_USR;
1044 	if (entry_func & 1)
1045 		s |= CPSR_T;
1046 	*spsr = s;
1047 	return true;
1048 }
1049 #endif
1050 
1051 #ifdef ARM64
1052 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1053 {
1054 	uint32_t s;
1055 
1056 	if (is_32bit) {
1057 		s = read_daif() & (SPSR_32_AIF_MASK << SPSR_32_AIF_SHIFT);
1058 		s |= SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT;
1059 		s |= (entry_func & SPSR_32_T_MASK) << SPSR_32_T_SHIFT;
1060 	} else {
1061 		s = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
1062 	}
1063 
1064 	*spsr = s;
1065 	return true;
1066 }
1067 #endif
1068 
1069 uint32_t thread_enter_user_mode(unsigned long a0, unsigned long a1,
1070 		unsigned long a2, unsigned long a3, unsigned long user_sp,
1071 		unsigned long entry_func, bool is_32bit,
1072 		uint32_t *exit_status0, uint32_t *exit_status1)
1073 {
1074 	uint32_t spsr;
1075 
1076 	if (!get_spsr(is_32bit, entry_func, &spsr)) {
1077 		*exit_status0 = 1; /* panic */
1078 		*exit_status1 = 0xbadbadba;
1079 		return 0;
1080 	}
1081 	return __thread_enter_user_mode(a0, a1, a2, a3, user_sp, entry_func,
1082 					spsr, exit_status0, exit_status1);
1083 }
1084 
1085 void thread_add_mutex(struct mutex *m)
1086 {
1087 	struct thread_core_local *l = thread_get_core_local();
1088 	int ct = l->curr_thread;
1089 
1090 	assert(ct != -1 && threads[ct].state == THREAD_STATE_ACTIVE);
1091 	assert(m->owner_id == -1);
1092 	m->owner_id = ct;
1093 	TAILQ_INSERT_TAIL(&threads[ct].mutexes, m, link);
1094 }
1095 
1096 void thread_rem_mutex(struct mutex *m)
1097 {
1098 	struct thread_core_local *l = thread_get_core_local();
1099 	int ct = l->curr_thread;
1100 
1101 	assert(ct != -1 && threads[ct].state == THREAD_STATE_ACTIVE);
1102 	assert(m->owner_id == ct);
1103 	m->owner_id = -1;
1104 	TAILQ_REMOVE(&threads[ct].mutexes, m, link);
1105 }
1106 
1107 bool thread_disable_prealloc_rpc_cache(uint64_t *cookie)
1108 {
1109 	bool rv;
1110 	size_t n;
1111 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ);
1112 
1113 	lock_global();
1114 
1115 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1116 		if (threads[n].state != THREAD_STATE_FREE) {
1117 			rv = false;
1118 			goto out;
1119 		}
1120 	}
1121 
1122 	rv = true;
1123 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1124 		if (threads[n].rpc_arg) {
1125 			*cookie = threads[n].rpc_carg;
1126 			threads[n].rpc_carg = 0;
1127 			threads[n].rpc_arg = NULL;
1128 			goto out;
1129 		}
1130 	}
1131 
1132 	*cookie = 0;
1133 	thread_prealloc_rpc_cache = false;
1134 out:
1135 	unlock_global();
1136 	thread_unmask_exceptions(exceptions);
1137 	return rv;
1138 }
1139 
1140 bool thread_enable_prealloc_rpc_cache(void)
1141 {
1142 	bool rv;
1143 	size_t n;
1144 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ);
1145 
1146 	lock_global();
1147 
1148 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1149 		if (threads[n].state != THREAD_STATE_FREE) {
1150 			rv = false;
1151 			goto out;
1152 		}
1153 	}
1154 
1155 	rv = true;
1156 	thread_prealloc_rpc_cache = true;
1157 out:
1158 	unlock_global();
1159 	thread_unmask_exceptions(exceptions);
1160 	return rv;
1161 }
1162 
1163 static uint32_t rpc_cmd_nolock(uint32_t cmd, size_t num_params,
1164 		struct optee_msg_param *params)
1165 {
1166 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1167 	struct thread_ctx *thr = threads + thread_get_id();
1168 	struct optee_msg_arg *arg = thr->rpc_arg;
1169 	uint64_t carg = thr->rpc_carg;
1170 	const size_t params_size = sizeof(struct optee_msg_param) * num_params;
1171 	size_t n;
1172 
1173 	assert(arg && carg && num_params <= RPC_MAX_NUM_PARAMS);
1174 
1175 	memset(arg, 0, OPTEE_MSG_GET_ARG_SIZE(RPC_MAX_NUM_PARAMS));
1176 	arg->cmd = cmd;
1177 	arg->ret = TEE_ERROR_GENERIC; /* in case value isn't updated */
1178 	arg->num_params = num_params;
1179 	memcpy(OPTEE_MSG_GET_PARAMS(arg), params, params_size);
1180 
1181 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1182 	thread_rpc(rpc_args);
1183 	for (n = 0; n < num_params; n++) {
1184 		switch (params[n].attr & OPTEE_MSG_ATTR_TYPE_MASK) {
1185 		case OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT:
1186 		case OPTEE_MSG_ATTR_TYPE_VALUE_INOUT:
1187 		case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:
1188 		case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:
1189 		case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:
1190 		case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:
1191 			memcpy(params + n, OPTEE_MSG_GET_PARAMS(arg) + n,
1192 			       sizeof(struct optee_msg_param));
1193 			break;
1194 		default:
1195 			break;
1196 		}
1197 	}
1198 	return arg->ret;
1199 }
1200 
1201 uint32_t thread_rpc_cmd(uint32_t cmd, size_t num_params,
1202 		struct optee_msg_param *params)
1203 {
1204 	uint32_t ret;
1205 
1206 	ret = rpc_cmd_nolock(cmd, num_params, params);
1207 
1208 	return ret;
1209 }
1210 
1211 static bool check_alloced_shm(paddr_t pa, size_t len, size_t align)
1212 {
1213 	if (pa & (align - 1))
1214 		return false;
1215 	return core_pbuf_is(CORE_MEM_NSEC_SHM, pa, len);
1216 }
1217 
1218 void thread_rpc_free_arg(uint64_t cookie)
1219 {
1220 	if (cookie) {
1221 		uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
1222 			OPTEE_SMC_RETURN_RPC_FREE
1223 		};
1224 
1225 		reg_pair_from_64(cookie, rpc_args + 1, rpc_args + 2);
1226 		thread_rpc(rpc_args);
1227 	}
1228 }
1229 
1230 void thread_rpc_alloc_arg(size_t size, paddr_t *arg, uint64_t *cookie)
1231 {
1232 	paddr_t pa;
1233 	uint64_t co;
1234 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
1235 		OPTEE_SMC_RETURN_RPC_ALLOC, size
1236 	};
1237 
1238 	thread_rpc(rpc_args);
1239 
1240 	pa = reg_pair_to_64(rpc_args[1], rpc_args[2]);
1241 	co = reg_pair_to_64(rpc_args[4], rpc_args[5]);
1242 	if (!check_alloced_shm(pa, size, sizeof(uint64_t))) {
1243 		thread_rpc_free_arg(co);
1244 		pa = 0;
1245 		co = 0;
1246 	}
1247 
1248 	*arg = pa;
1249 	*cookie = co;
1250 }
1251 
1252 /**
1253  * Free physical memory previously allocated with thread_rpc_alloc()
1254  *
1255  * @cookie:	cookie received when allocating the buffer
1256  * @bt:		 must be the same as supplied when allocating
1257  */
1258 static void thread_rpc_free(unsigned int bt, uint64_t cookie)
1259 {
1260 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1261 	struct thread_ctx *thr = threads + thread_get_id();
1262 	struct optee_msg_arg *arg = thr->rpc_arg;
1263 	uint64_t carg = thr->rpc_carg;
1264 	struct optee_msg_param *params = OPTEE_MSG_GET_PARAMS(arg);
1265 
1266 	memset(arg, 0, OPTEE_MSG_GET_ARG_SIZE(1));
1267 	arg->cmd = OPTEE_MSG_RPC_CMD_SHM_FREE;
1268 	arg->ret = TEE_ERROR_GENERIC; /* in case value isn't updated */
1269 	arg->num_params = 1;
1270 
1271 	params[0].attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
1272 	params[0].u.value.a = bt;
1273 	params[0].u.value.b = cookie;
1274 	params[0].u.value.c = 0;
1275 
1276 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1277 	thread_rpc(rpc_args);
1278 }
1279 
1280 /**
1281  * Allocates shared memory buffer via RPC
1282  *
1283  * @size:	size in bytes of shared memory buffer
1284  * @align:	required alignment of buffer
1285  * @bt:		buffer type OPTEE_MSG_RPC_SHM_TYPE_*
1286  * @payload:	returned physical pointer to buffer, 0 if allocation
1287  *		failed.
1288  * @cookie:	returned cookie used when freeing the buffer
1289  */
1290 static void thread_rpc_alloc(size_t size, size_t align, unsigned int bt,
1291 			paddr_t *payload, uint64_t *cookie)
1292 {
1293 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1294 	struct thread_ctx *thr = threads + thread_get_id();
1295 	struct optee_msg_arg *arg = thr->rpc_arg;
1296 	uint64_t carg = thr->rpc_carg;
1297 	struct optee_msg_param *params = OPTEE_MSG_GET_PARAMS(arg);
1298 
1299 	memset(arg, 0, OPTEE_MSG_GET_ARG_SIZE(1));
1300 	arg->cmd = OPTEE_MSG_RPC_CMD_SHM_ALLOC;
1301 	arg->ret = TEE_ERROR_GENERIC; /* in case value isn't updated */
1302 	arg->num_params = 1;
1303 
1304 	params[0].attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
1305 	params[0].u.value.a = bt;
1306 	params[0].u.value.b = size;
1307 	params[0].u.value.c = align;
1308 
1309 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1310 	thread_rpc(rpc_args);
1311 	if (arg->ret != TEE_SUCCESS)
1312 		goto fail;
1313 
1314 	if (arg->num_params != 1)
1315 		goto fail;
1316 
1317 	if (params[0].attr != OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT)
1318 		goto fail;
1319 
1320 	if (!check_alloced_shm(params[0].u.tmem.buf_ptr, size, align)) {
1321 		thread_rpc_free(bt, params[0].u.tmem.shm_ref);
1322 		goto fail;
1323 	}
1324 
1325 	*payload = params[0].u.tmem.buf_ptr;
1326 	*cookie = params[0].u.tmem.shm_ref;
1327 	return;
1328 fail:
1329 	*payload = 0;
1330 	*cookie = 0;
1331 }
1332 
1333 void thread_rpc_alloc_payload(size_t size, paddr_t *payload, uint64_t *cookie)
1334 {
1335 	thread_rpc_alloc(size, 8, OPTEE_MSG_RPC_SHM_TYPE_APPL, payload, cookie);
1336 }
1337 
1338 void thread_rpc_free_payload(uint64_t cookie)
1339 {
1340 	thread_rpc_free(OPTEE_MSG_RPC_SHM_TYPE_APPL, cookie);
1341 }
1342