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