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