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