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