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