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