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