xref: /optee_os/core/arch/arm/kernel/thread.c (revision ef4bc451c262f007562867ea4e5f4ca9f26459fd)
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_defs.h>
43 #include <mm/tee_mmu.h>
44 #include <mm/tee_pager.h>
45 #include <optee_msg.h>
46 #include <sm/optee_smc.h>
47 #include <sm/sm.h>
48 #include <tee/tee_fs_rpc.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_fiq_handler_t thread_fiq_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 	/* IRQ must not be unmasked while holding a spinlock */
238 	if (!(exceptions & THREAD_EXCP_IRQ))
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 	/* IRQ must not be unmasked while holding a spinlock */
260 	if (!(exceptions & THREAD_EXCP_IRQ))
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 	 * IRQs must be disabled before playing with core_local since
289 	 * we otherwise may be rescheduled to a different core in the
290 	 * middle of this function.
291 	 */
292 	assert(thread_get_exceptions() & THREAD_EXCP_IRQ);
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 IRQ, masked Asynchronous
342 	 * abort and unmasked FIQ.
343 	  */
344 	thread->regs.cpsr = read_cpsr() & ARM32_CPSR_E;
345 	thread->regs.cpsr |= CPSR_MODE_SVC | CPSR_I | CPSR_A;
346 	/* Enable thumb mode if it's a thumb instruction */
347 	if (thread->regs.pc & 1)
348 		thread->regs.cpsr |= CPSR_T;
349 	/* Reinitialize stack pointer */
350 	thread->regs.svc_sp = thread->stack_va_end;
351 
352 	/*
353 	 * Copy arguments into context. This will make the
354 	 * arguments appear in r0-r7 when thread is started.
355 	 */
356 	thread->regs.r0 = args->a0;
357 	thread->regs.r1 = args->a1;
358 	thread->regs.r2 = args->a2;
359 	thread->regs.r3 = args->a3;
360 	thread->regs.r4 = args->a4;
361 	thread->regs.r5 = args->a5;
362 	thread->regs.r6 = args->a6;
363 	thread->regs.r7 = args->a7;
364 }
365 #endif /*ARM32*/
366 
367 #ifdef ARM64
368 static void init_regs(struct thread_ctx *thread,
369 		struct thread_smc_args *args)
370 {
371 	thread->regs.pc = (uint64_t)thread_std_smc_entry;
372 
373 	/*
374 	 * Stdcalls starts in SVC mode with masked IRQ, masked Asynchronous
375 	 * abort and unmasked FIQ.
376 	  */
377 	thread->regs.cpsr = SPSR_64(SPSR_64_MODE_EL1, SPSR_64_MODE_SP_EL0,
378 				    DAIFBIT_IRQ | DAIFBIT_ABT);
379 	/* Reinitialize stack pointer */
380 	thread->regs.sp = thread->stack_va_end;
381 
382 	/*
383 	 * Copy arguments into context. This will make the
384 	 * arguments appear in x0-x7 when thread is started.
385 	 */
386 	thread->regs.x[0] = args->a0;
387 	thread->regs.x[1] = args->a1;
388 	thread->regs.x[2] = args->a2;
389 	thread->regs.x[3] = args->a3;
390 	thread->regs.x[4] = args->a4;
391 	thread->regs.x[5] = args->a5;
392 	thread->regs.x[6] = args->a6;
393 	thread->regs.x[7] = args->a7;
394 
395 	/* Set up frame pointer as per the Aarch64 AAPCS */
396 	thread->regs.x[29] = 0;
397 }
398 #endif /*ARM64*/
399 
400 void thread_init_boot_thread(void)
401 {
402 	struct thread_core_local *l = thread_get_core_local();
403 	size_t n;
404 
405 	for (n = 0; n < CFG_NUM_THREADS; n++) {
406 		TAILQ_INIT(&threads[n].mutexes);
407 		TAILQ_INIT(&threads[n].tsd.sess_stack);
408 #ifdef CFG_SMALL_PAGE_USER_TA
409 		SLIST_INIT(&threads[n].tsd.pgt_cache);
410 #endif
411 	}
412 
413 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++)
414 		thread_core_local[n].curr_thread = -1;
415 
416 	l->curr_thread = 0;
417 	threads[0].state = THREAD_STATE_ACTIVE;
418 }
419 
420 void thread_clr_boot_thread(void)
421 {
422 	struct thread_core_local *l = thread_get_core_local();
423 
424 	assert(l->curr_thread >= 0 && l->curr_thread < CFG_NUM_THREADS);
425 	assert(threads[l->curr_thread].state == THREAD_STATE_ACTIVE);
426 	assert(TAILQ_EMPTY(&threads[l->curr_thread].mutexes));
427 	threads[l->curr_thread].state = THREAD_STATE_FREE;
428 	l->curr_thread = -1;
429 }
430 
431 static void thread_alloc_and_run(struct thread_smc_args *args)
432 {
433 	size_t n;
434 	struct thread_core_local *l = thread_get_core_local();
435 	bool found_thread = false;
436 
437 	assert(l->curr_thread == -1);
438 
439 	lock_global();
440 
441 	for (n = 0; n < CFG_NUM_THREADS; n++) {
442 		if (threads[n].state == THREAD_STATE_FREE) {
443 			threads[n].state = THREAD_STATE_ACTIVE;
444 			found_thread = true;
445 			break;
446 		}
447 	}
448 
449 	unlock_global();
450 
451 	if (!found_thread) {
452 		args->a0 = OPTEE_SMC_RETURN_ETHREAD_LIMIT;
453 		return;
454 	}
455 
456 	l->curr_thread = n;
457 
458 	threads[n].flags = 0;
459 	init_regs(threads + n, args);
460 
461 	/* Save Hypervisor Client ID */
462 	threads[n].hyp_clnt_id = args->a7;
463 
464 	thread_lazy_save_ns_vfp();
465 	thread_resume(&threads[n].regs);
466 }
467 
468 #ifdef ARM32
469 static void copy_a0_to_a5(struct thread_ctx_regs *regs,
470 		struct thread_smc_args *args)
471 {
472 	/*
473 	 * Update returned values from RPC, values will appear in
474 	 * r0-r3 when thread is resumed.
475 	 */
476 	regs->r0 = args->a0;
477 	regs->r1 = args->a1;
478 	regs->r2 = args->a2;
479 	regs->r3 = args->a3;
480 	regs->r4 = args->a4;
481 	regs->r5 = args->a5;
482 }
483 #endif /*ARM32*/
484 
485 #ifdef ARM64
486 static void copy_a0_to_a5(struct thread_ctx_regs *regs,
487 		struct thread_smc_args *args)
488 {
489 	/*
490 	 * Update returned values from RPC, values will appear in
491 	 * x0-x3 when thread is resumed.
492 	 */
493 	regs->x[0] = args->a0;
494 	regs->x[1] = args->a1;
495 	regs->x[2] = args->a2;
496 	regs->x[3] = args->a3;
497 	regs->x[4] = args->a4;
498 	regs->x[5] = args->a5;
499 }
500 #endif /*ARM64*/
501 
502 static void thread_resume_from_rpc(struct thread_smc_args *args)
503 {
504 	size_t n = args->a3; /* thread id */
505 	struct thread_core_local *l = thread_get_core_local();
506 	uint32_t rv = 0;
507 
508 	assert(l->curr_thread == -1);
509 
510 	lock_global();
511 
512 	if (n < CFG_NUM_THREADS &&
513 	    threads[n].state == THREAD_STATE_SUSPENDED &&
514 	    args->a7 == threads[n].hyp_clnt_id)
515 		threads[n].state = THREAD_STATE_ACTIVE;
516 	else
517 		rv = OPTEE_SMC_RETURN_ERESUME;
518 
519 	unlock_global();
520 
521 	if (rv) {
522 		args->a0 = rv;
523 		return;
524 	}
525 
526 	l->curr_thread = n;
527 
528 	if (threads[n].have_user_map)
529 		core_mmu_set_user_map(&threads[n].user_map);
530 
531 	/*
532 	 * Return from RPC to request service of an IRQ must not
533 	 * get parameters from non-secure world.
534 	 */
535 	if (threads[n].flags & THREAD_FLAGS_COPY_ARGS_ON_RETURN) {
536 		copy_a0_to_a5(&threads[n].regs, args);
537 		threads[n].flags &= ~THREAD_FLAGS_COPY_ARGS_ON_RETURN;
538 	}
539 
540 	thread_lazy_save_ns_vfp();
541 	thread_resume(&threads[n].regs);
542 }
543 
544 void thread_handle_fast_smc(struct thread_smc_args *args)
545 {
546 	thread_check_canaries();
547 	thread_fast_smc_handler_ptr(args);
548 	/* Fast handlers must not unmask any exceptions */
549 	assert(thread_get_exceptions() == THREAD_EXCP_ALL);
550 }
551 
552 void thread_handle_std_smc(struct thread_smc_args *args)
553 {
554 	thread_check_canaries();
555 
556 	if (args->a0 == OPTEE_SMC_CALL_RETURN_FROM_RPC)
557 		thread_resume_from_rpc(args);
558 	else
559 		thread_alloc_and_run(args);
560 }
561 
562 /* Helper routine for the assembly function thread_std_smc_entry() */
563 void __thread_std_smc_entry(struct thread_smc_args *args)
564 {
565 	struct thread_ctx *thr = threads + thread_get_id();
566 
567 	if (!thr->rpc_arg) {
568 		paddr_t parg;
569 		uint64_t carg;
570 		void *arg;
571 
572 		thread_rpc_alloc_arg(
573 			OPTEE_MSG_GET_ARG_SIZE(THREAD_RPC_MAX_NUM_PARAMS),
574 			&parg, &carg);
575 		if (!parg || !ALIGNMENT_IS_OK(parg, struct optee_msg_arg) ||
576 		    !(arg = phys_to_virt(parg, CORE_MEM_NSEC_SHM))) {
577 			thread_rpc_free_arg(carg);
578 			args->a0 = OPTEE_SMC_RETURN_ENOMEM;
579 			return;
580 		}
581 
582 		thr->rpc_arg = arg;
583 		thr->rpc_carg = carg;
584 	}
585 
586 	thread_std_smc_handler_ptr(args);
587 
588 	tee_fs_rpc_cache_clear(&thr->tsd);
589 	if (!thread_prealloc_rpc_cache) {
590 		thread_rpc_free_arg(thr->rpc_carg);
591 		thr->rpc_carg = 0;
592 		thr->rpc_arg = 0;
593 	}
594 }
595 
596 void *thread_get_tmp_sp(void)
597 {
598 	struct thread_core_local *l = thread_get_core_local();
599 
600 	return (void *)l->tmp_stack_va_end;
601 }
602 
603 #ifdef ARM64
604 vaddr_t thread_get_saved_thread_sp(void)
605 {
606 	struct thread_core_local *l = thread_get_core_local();
607 	int ct = l->curr_thread;
608 
609 	assert(ct != -1);
610 	return threads[ct].kern_sp;
611 }
612 #endif /*ARM64*/
613 
614 bool thread_addr_is_in_stack(vaddr_t va)
615 {
616 	struct thread_ctx *thr;
617 	int ct = thread_get_id_may_fail();
618 
619 	if (ct == -1)
620 		return false;
621 
622 	thr = threads + ct;
623 	return va < thr->stack_va_end &&
624 	       va >= (thr->stack_va_end - STACK_THREAD_SIZE);
625 }
626 
627 void thread_state_free(void)
628 {
629 	struct thread_core_local *l = thread_get_core_local();
630 	int ct = l->curr_thread;
631 
632 	assert(ct != -1);
633 	assert(TAILQ_EMPTY(&threads[ct].mutexes));
634 
635 	thread_lazy_restore_ns_vfp();
636 	tee_pager_release_phys(
637 		(void *)(threads[ct].stack_va_end - STACK_THREAD_SIZE),
638 		STACK_THREAD_SIZE);
639 
640 	lock_global();
641 
642 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
643 	threads[ct].state = THREAD_STATE_FREE;
644 	threads[ct].flags = 0;
645 	l->curr_thread = -1;
646 
647 	unlock_global();
648 }
649 
650 #ifdef ARM32
651 static bool is_from_user(uint32_t cpsr)
652 {
653 	return (cpsr & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_USR;
654 }
655 #endif
656 
657 #ifdef ARM64
658 static bool is_from_user(uint32_t cpsr)
659 {
660 	if (cpsr & (SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT))
661 		return true;
662 	if (((cpsr >> SPSR_64_MODE_EL_SHIFT) & SPSR_64_MODE_EL_MASK) ==
663 	     SPSR_64_MODE_EL0)
664 		return true;
665 	return false;
666 }
667 #endif
668 
669 #ifdef CFG_WITH_PAGER
670 static void release_unused_kernel_stack(struct thread_ctx *thr)
671 {
672 	vaddr_t sp = thr->regs.svc_sp;
673 	vaddr_t base = thr->stack_va_end - STACK_THREAD_SIZE;
674 	size_t len = sp - base;
675 
676 	tee_pager_release_phys((void *)base, len);
677 }
678 #else
679 static void release_unused_kernel_stack(struct thread_ctx *thr __unused)
680 {
681 }
682 #endif
683 
684 int thread_state_suspend(uint32_t flags, uint32_t cpsr, vaddr_t pc)
685 {
686 	struct thread_core_local *l = thread_get_core_local();
687 	int ct = l->curr_thread;
688 
689 	assert(ct != -1);
690 
691 	thread_check_canaries();
692 
693 	release_unused_kernel_stack(threads + ct);
694 
695 	if (is_from_user(cpsr))
696 		thread_user_save_vfp();
697 	thread_lazy_restore_ns_vfp();
698 
699 	lock_global();
700 
701 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
702 	threads[ct].flags |= flags;
703 	threads[ct].regs.cpsr = cpsr;
704 	threads[ct].regs.pc = pc;
705 	threads[ct].state = THREAD_STATE_SUSPENDED;
706 
707 	threads[ct].have_user_map = core_mmu_user_mapping_is_active();
708 	if (threads[ct].have_user_map) {
709 		core_mmu_get_user_map(&threads[ct].user_map);
710 		core_mmu_set_user_map(NULL);
711 	}
712 
713 	l->curr_thread = -1;
714 
715 	unlock_global();
716 
717 	return ct;
718 }
719 
720 #ifdef ARM32
721 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
722 {
723 	l->tmp_stack_va_end = sp;
724 	thread_set_irq_sp(sp);
725 	thread_set_fiq_sp(sp);
726 }
727 
728 static void set_abt_stack(struct thread_core_local *l __unused, vaddr_t sp)
729 {
730 	thread_set_abt_sp(sp);
731 }
732 #endif /*ARM32*/
733 
734 #ifdef ARM64
735 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
736 {
737 	/*
738 	 * We're already using the tmp stack when this function is called
739 	 * so there's no need to assign it to any stack pointer. However,
740 	 * we'll need to restore it at different times so store it here.
741 	 */
742 	l->tmp_stack_va_end = sp;
743 }
744 
745 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
746 {
747 	l->abt_stack_va_end = sp;
748 }
749 #endif /*ARM64*/
750 
751 bool thread_init_stack(uint32_t thread_id, vaddr_t sp)
752 {
753 	if (thread_id >= CFG_NUM_THREADS)
754 		return false;
755 	threads[thread_id].stack_va_end = sp;
756 	return true;
757 }
758 
759 int thread_get_id_may_fail(void)
760 {
761 	/* thread_get_core_local() requires IRQs to be disabled */
762 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ);
763 	struct thread_core_local *l = thread_get_core_local();
764 	int ct = l->curr_thread;
765 
766 	thread_unmask_exceptions(exceptions);
767 	return ct;
768 }
769 
770 int thread_get_id(void)
771 {
772 	int ct = thread_get_id_may_fail();
773 
774 	assert(ct >= 0 && ct < CFG_NUM_THREADS);
775 	return ct;
776 }
777 
778 static void init_handlers(const struct thread_handlers *handlers)
779 {
780 	thread_std_smc_handler_ptr = handlers->std_smc;
781 	thread_fast_smc_handler_ptr = handlers->fast_smc;
782 	thread_fiq_handler_ptr = handlers->fiq;
783 	thread_cpu_on_handler_ptr = handlers->cpu_on;
784 	thread_cpu_off_handler_ptr = handlers->cpu_off;
785 	thread_cpu_suspend_handler_ptr = handlers->cpu_suspend;
786 	thread_cpu_resume_handler_ptr = handlers->cpu_resume;
787 	thread_system_off_handler_ptr = handlers->system_off;
788 	thread_system_reset_handler_ptr = handlers->system_reset;
789 }
790 
791 #ifdef CFG_WITH_PAGER
792 static void init_thread_stacks(void)
793 {
794 	size_t n;
795 
796 	/*
797 	 * Allocate virtual memory for thread stacks.
798 	 */
799 	for (n = 0; n < CFG_NUM_THREADS; n++) {
800 		tee_mm_entry_t *mm;
801 		vaddr_t sp;
802 
803 		/* Find vmem for thread stack and its protection gap */
804 		mm = tee_mm_alloc(&tee_mm_vcore,
805 				  SMALL_PAGE_SIZE + STACK_THREAD_SIZE);
806 		assert(mm);
807 
808 		/* Claim eventual physical page */
809 		tee_pager_add_pages(tee_mm_get_smem(mm), tee_mm_get_size(mm),
810 				    true);
811 
812 		/* Add the area to the pager */
813 		tee_pager_add_core_area(tee_mm_get_smem(mm) + SMALL_PAGE_SIZE,
814 					tee_mm_get_bytes(mm) - SMALL_PAGE_SIZE,
815 					TEE_MATTR_PRW | TEE_MATTR_LOCKED,
816 					NULL, NULL);
817 
818 		/* init effective stack */
819 		sp = tee_mm_get_smem(mm) + tee_mm_get_bytes(mm);
820 		if (!thread_init_stack(n, sp))
821 			panic("init stack failed");
822 	}
823 }
824 #else
825 static void init_thread_stacks(void)
826 {
827 	size_t n;
828 
829 	/* Assign the thread stacks */
830 	for (n = 0; n < CFG_NUM_THREADS; n++) {
831 		if (!thread_init_stack(n, GET_STACK(stack_thread[n])))
832 			panic("thread_init_stack failed");
833 	}
834 }
835 #endif /*CFG_WITH_PAGER*/
836 
837 void thread_init_primary(const struct thread_handlers *handlers)
838 {
839 	init_handlers(handlers);
840 
841 	/* Initialize canaries around the stacks */
842 	init_canaries();
843 
844 	init_thread_stacks();
845 	pgt_init();
846 }
847 
848 static void init_sec_mon(size_t pos __maybe_unused)
849 {
850 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
851 	/* Initialize secure monitor */
852 	sm_init(GET_STACK(stack_tmp[pos]));
853 #endif
854 }
855 
856 void thread_init_per_cpu(void)
857 {
858 	size_t pos = get_core_pos();
859 	struct thread_core_local *l = thread_get_core_local();
860 
861 	init_sec_mon(pos);
862 
863 	set_tmp_stack(l, GET_STACK(stack_tmp[pos]) - STACK_TMP_OFFS);
864 	set_abt_stack(l, GET_STACK(stack_abt[pos]));
865 
866 	thread_init_vbar();
867 }
868 
869 struct thread_specific_data *thread_get_tsd(void)
870 {
871 	return &threads[thread_get_id()].tsd;
872 }
873 
874 struct thread_ctx_regs *thread_get_ctx_regs(void)
875 {
876 	struct thread_core_local *l = thread_get_core_local();
877 
878 	assert(l->curr_thread != -1);
879 	return &threads[l->curr_thread].regs;
880 }
881 
882 void thread_set_irq(bool enable)
883 {
884 	/* thread_get_core_local() requires IRQs to be disabled */
885 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ);
886 	struct thread_core_local *l;
887 
888 	l = thread_get_core_local();
889 
890 	assert(l->curr_thread != -1);
891 
892 	if (enable) {
893 		threads[l->curr_thread].flags |= THREAD_FLAGS_IRQ_ENABLE;
894 		thread_set_exceptions(exceptions & ~THREAD_EXCP_IRQ);
895 	} else {
896 		/*
897 		 * No need to disable IRQ here since it's already disabled
898 		 * above.
899 		 */
900 		threads[l->curr_thread].flags &= ~THREAD_FLAGS_IRQ_ENABLE;
901 	}
902 }
903 
904 void thread_restore_irq(void)
905 {
906 	/* thread_get_core_local() requires IRQs to be disabled */
907 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ);
908 	struct thread_core_local *l;
909 
910 	l = thread_get_core_local();
911 
912 	assert(l->curr_thread != -1);
913 
914 	if (threads[l->curr_thread].flags & THREAD_FLAGS_IRQ_ENABLE)
915 		thread_set_exceptions(exceptions & ~THREAD_EXCP_IRQ);
916 }
917 
918 #ifdef CFG_WITH_VFP
919 uint32_t thread_kernel_enable_vfp(void)
920 {
921 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ);
922 	struct thread_ctx *thr = threads + thread_get_id();
923 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
924 
925 	assert(!vfp_is_enabled());
926 
927 	if (!thr->vfp_state.ns_saved) {
928 		vfp_lazy_save_state_final(&thr->vfp_state.ns);
929 		thr->vfp_state.ns_saved = true;
930 	} else if (thr->vfp_state.sec_lazy_saved &&
931 		   !thr->vfp_state.sec_saved) {
932 		/*
933 		 * This happens when we're handling an abort while the
934 		 * thread was using the VFP state.
935 		 */
936 		vfp_lazy_save_state_final(&thr->vfp_state.sec);
937 		thr->vfp_state.sec_saved = true;
938 	} else if (tuv && tuv->lazy_saved && !tuv->saved) {
939 		/*
940 		 * This can happen either during syscall or abort
941 		 * processing (while processing a syscall).
942 		 */
943 		vfp_lazy_save_state_final(&tuv->vfp);
944 		tuv->saved = true;
945 	}
946 
947 	vfp_enable();
948 	return exceptions;
949 }
950 
951 void thread_kernel_disable_vfp(uint32_t state)
952 {
953 	uint32_t exceptions;
954 
955 	assert(vfp_is_enabled());
956 
957 	vfp_disable();
958 	exceptions = thread_get_exceptions();
959 	assert(exceptions & THREAD_EXCP_IRQ);
960 	exceptions &= ~THREAD_EXCP_IRQ;
961 	exceptions |= state & THREAD_EXCP_IRQ;
962 	thread_set_exceptions(exceptions);
963 }
964 
965 void thread_kernel_save_vfp(void)
966 {
967 	struct thread_ctx *thr = threads + thread_get_id();
968 
969 	assert(thread_get_exceptions() & THREAD_EXCP_IRQ);
970 	if (vfp_is_enabled()) {
971 		vfp_lazy_save_state_init(&thr->vfp_state.sec);
972 		thr->vfp_state.sec_lazy_saved = true;
973 	}
974 }
975 
976 void thread_kernel_restore_vfp(void)
977 {
978 	struct thread_ctx *thr = threads + thread_get_id();
979 
980 	assert(thread_get_exceptions() & THREAD_EXCP_IRQ);
981 	assert(!vfp_is_enabled());
982 	if (thr->vfp_state.sec_lazy_saved) {
983 		vfp_lazy_restore_state(&thr->vfp_state.sec,
984 				       thr->vfp_state.sec_saved);
985 		thr->vfp_state.sec_saved = false;
986 		thr->vfp_state.sec_lazy_saved = false;
987 	}
988 }
989 
990 void thread_user_enable_vfp(struct thread_user_vfp_state *uvfp)
991 {
992 	struct thread_ctx *thr = threads + thread_get_id();
993 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
994 
995 	assert(thread_get_exceptions() & THREAD_EXCP_IRQ);
996 	assert(!vfp_is_enabled());
997 
998 	if (!thr->vfp_state.ns_saved) {
999 		vfp_lazy_save_state_final(&thr->vfp_state.ns);
1000 		thr->vfp_state.ns_saved = true;
1001 	} else if (tuv && uvfp != tuv) {
1002 		if (tuv->lazy_saved && !tuv->saved) {
1003 			vfp_lazy_save_state_final(&tuv->vfp);
1004 			tuv->saved = true;
1005 		}
1006 	}
1007 
1008 	if (uvfp->lazy_saved)
1009 		vfp_lazy_restore_state(&uvfp->vfp, uvfp->saved);
1010 	uvfp->lazy_saved = false;
1011 	uvfp->saved = false;
1012 
1013 	thr->vfp_state.uvfp = uvfp;
1014 	vfp_enable();
1015 }
1016 
1017 void thread_user_save_vfp(void)
1018 {
1019 	struct thread_ctx *thr = threads + thread_get_id();
1020 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1021 
1022 	assert(thread_get_exceptions() & THREAD_EXCP_IRQ);
1023 	if (!vfp_is_enabled())
1024 		return;
1025 
1026 	assert(tuv && !tuv->lazy_saved && !tuv->saved);
1027 	vfp_lazy_save_state_init(&tuv->vfp);
1028 	tuv->lazy_saved = true;
1029 }
1030 
1031 void thread_user_clear_vfp(struct thread_user_vfp_state *uvfp)
1032 {
1033 	struct thread_ctx *thr = threads + thread_get_id();
1034 
1035 	if (uvfp == thr->vfp_state.uvfp)
1036 		thr->vfp_state.uvfp = NULL;
1037 	uvfp->lazy_saved = false;
1038 	uvfp->saved = false;
1039 }
1040 #endif /*CFG_WITH_VFP*/
1041 
1042 #ifdef ARM32
1043 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1044 {
1045 	uint32_t s;
1046 
1047 	if (!is_32bit)
1048 		return false;
1049 
1050 	s = read_spsr();
1051 	s &= ~(CPSR_MODE_MASK | CPSR_T | CPSR_IT_MASK1 | CPSR_IT_MASK2);
1052 	s |= CPSR_MODE_USR;
1053 	if (entry_func & 1)
1054 		s |= CPSR_T;
1055 	*spsr = s;
1056 	return true;
1057 }
1058 #endif
1059 
1060 #ifdef ARM64
1061 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1062 {
1063 	uint32_t s;
1064 
1065 	if (is_32bit) {
1066 		s = read_daif() & (SPSR_32_AIF_MASK << SPSR_32_AIF_SHIFT);
1067 		s |= SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT;
1068 		s |= (entry_func & SPSR_32_T_MASK) << SPSR_32_T_SHIFT;
1069 	} else {
1070 		s = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
1071 	}
1072 
1073 	*spsr = s;
1074 	return true;
1075 }
1076 #endif
1077 
1078 uint32_t thread_enter_user_mode(unsigned long a0, unsigned long a1,
1079 		unsigned long a2, unsigned long a3, unsigned long user_sp,
1080 		unsigned long entry_func, bool is_32bit,
1081 		uint32_t *exit_status0, uint32_t *exit_status1)
1082 {
1083 	uint32_t spsr;
1084 
1085 	if (!get_spsr(is_32bit, entry_func, &spsr)) {
1086 		*exit_status0 = 1; /* panic */
1087 		*exit_status1 = 0xbadbadba;
1088 		return 0;
1089 	}
1090 	return __thread_enter_user_mode(a0, a1, a2, a3, user_sp, entry_func,
1091 					spsr, exit_status0, exit_status1);
1092 }
1093 
1094 void thread_add_mutex(struct mutex *m)
1095 {
1096 	struct thread_core_local *l = thread_get_core_local();
1097 	int ct = l->curr_thread;
1098 
1099 	assert(ct != -1 && threads[ct].state == THREAD_STATE_ACTIVE);
1100 	assert(m->owner_id == -1);
1101 	m->owner_id = ct;
1102 	TAILQ_INSERT_TAIL(&threads[ct].mutexes, m, link);
1103 }
1104 
1105 void thread_rem_mutex(struct mutex *m)
1106 {
1107 	struct thread_core_local *l = thread_get_core_local();
1108 	int ct = l->curr_thread;
1109 
1110 	assert(ct != -1 && threads[ct].state == THREAD_STATE_ACTIVE);
1111 	assert(m->owner_id == ct);
1112 	m->owner_id = -1;
1113 	TAILQ_REMOVE(&threads[ct].mutexes, m, link);
1114 }
1115 
1116 bool thread_disable_prealloc_rpc_cache(uint64_t *cookie)
1117 {
1118 	bool rv;
1119 	size_t n;
1120 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ);
1121 
1122 	lock_global();
1123 
1124 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1125 		if (threads[n].state != THREAD_STATE_FREE) {
1126 			rv = false;
1127 			goto out;
1128 		}
1129 	}
1130 
1131 	rv = true;
1132 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1133 		if (threads[n].rpc_arg) {
1134 			*cookie = threads[n].rpc_carg;
1135 			threads[n].rpc_carg = 0;
1136 			threads[n].rpc_arg = NULL;
1137 			goto out;
1138 		}
1139 	}
1140 
1141 	*cookie = 0;
1142 	thread_prealloc_rpc_cache = false;
1143 out:
1144 	unlock_global();
1145 	thread_unmask_exceptions(exceptions);
1146 	return rv;
1147 }
1148 
1149 bool thread_enable_prealloc_rpc_cache(void)
1150 {
1151 	bool rv;
1152 	size_t n;
1153 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ);
1154 
1155 	lock_global();
1156 
1157 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1158 		if (threads[n].state != THREAD_STATE_FREE) {
1159 			rv = false;
1160 			goto out;
1161 		}
1162 	}
1163 
1164 	rv = true;
1165 	thread_prealloc_rpc_cache = true;
1166 out:
1167 	unlock_global();
1168 	thread_unmask_exceptions(exceptions);
1169 	return rv;
1170 }
1171 
1172 static uint32_t rpc_cmd_nolock(uint32_t cmd, size_t num_params,
1173 		struct optee_msg_param *params)
1174 {
1175 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1176 	struct thread_ctx *thr = threads + thread_get_id();
1177 	struct optee_msg_arg *arg = thr->rpc_arg;
1178 	uint64_t carg = thr->rpc_carg;
1179 	const size_t params_size = sizeof(struct optee_msg_param) * num_params;
1180 	size_t n;
1181 
1182 	assert(arg && carg && num_params <= THREAD_RPC_MAX_NUM_PARAMS);
1183 
1184 	memset(arg, 0, OPTEE_MSG_GET_ARG_SIZE(THREAD_RPC_MAX_NUM_PARAMS));
1185 	arg->cmd = cmd;
1186 	arg->ret = TEE_ERROR_GENERIC; /* in case value isn't updated */
1187 	arg->num_params = num_params;
1188 	memcpy(OPTEE_MSG_GET_PARAMS(arg), params, params_size);
1189 
1190 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1191 	thread_rpc(rpc_args);
1192 	for (n = 0; n < num_params; n++) {
1193 		switch (params[n].attr & OPTEE_MSG_ATTR_TYPE_MASK) {
1194 		case OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT:
1195 		case OPTEE_MSG_ATTR_TYPE_VALUE_INOUT:
1196 		case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:
1197 		case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:
1198 		case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:
1199 		case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:
1200 			memcpy(params + n, OPTEE_MSG_GET_PARAMS(arg) + n,
1201 			       sizeof(struct optee_msg_param));
1202 			break;
1203 		default:
1204 			break;
1205 		}
1206 	}
1207 	return arg->ret;
1208 }
1209 
1210 uint32_t thread_rpc_cmd(uint32_t cmd, size_t num_params,
1211 		struct optee_msg_param *params)
1212 {
1213 	uint32_t ret;
1214 
1215 	ret = rpc_cmd_nolock(cmd, num_params, params);
1216 
1217 	return ret;
1218 }
1219 
1220 static bool check_alloced_shm(paddr_t pa, size_t len, size_t align)
1221 {
1222 	if (pa & (align - 1))
1223 		return false;
1224 	return core_pbuf_is(CORE_MEM_NSEC_SHM, pa, len);
1225 }
1226 
1227 void thread_rpc_free_arg(uint64_t cookie)
1228 {
1229 	if (cookie) {
1230 		uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
1231 			OPTEE_SMC_RETURN_RPC_FREE
1232 		};
1233 
1234 		reg_pair_from_64(cookie, rpc_args + 1, rpc_args + 2);
1235 		thread_rpc(rpc_args);
1236 	}
1237 }
1238 
1239 void thread_rpc_alloc_arg(size_t size, paddr_t *arg, uint64_t *cookie)
1240 {
1241 	paddr_t pa;
1242 	uint64_t co;
1243 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
1244 		OPTEE_SMC_RETURN_RPC_ALLOC, size
1245 	};
1246 
1247 	thread_rpc(rpc_args);
1248 
1249 	pa = reg_pair_to_64(rpc_args[1], rpc_args[2]);
1250 	co = reg_pair_to_64(rpc_args[4], rpc_args[5]);
1251 	if (!check_alloced_shm(pa, size, sizeof(uint64_t))) {
1252 		thread_rpc_free_arg(co);
1253 		pa = 0;
1254 		co = 0;
1255 	}
1256 
1257 	*arg = pa;
1258 	*cookie = co;
1259 }
1260 
1261 /**
1262  * Free physical memory previously allocated with thread_rpc_alloc()
1263  *
1264  * @cookie:	cookie received when allocating the buffer
1265  * @bt:		 must be the same as supplied when allocating
1266  */
1267 static void thread_rpc_free(unsigned int bt, uint64_t cookie)
1268 {
1269 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1270 	struct thread_ctx *thr = threads + thread_get_id();
1271 	struct optee_msg_arg *arg = thr->rpc_arg;
1272 	uint64_t carg = thr->rpc_carg;
1273 	struct optee_msg_param *params = OPTEE_MSG_GET_PARAMS(arg);
1274 
1275 	memset(arg, 0, OPTEE_MSG_GET_ARG_SIZE(1));
1276 	arg->cmd = OPTEE_MSG_RPC_CMD_SHM_FREE;
1277 	arg->ret = TEE_ERROR_GENERIC; /* in case value isn't updated */
1278 	arg->num_params = 1;
1279 
1280 	params[0].attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
1281 	params[0].u.value.a = bt;
1282 	params[0].u.value.b = cookie;
1283 	params[0].u.value.c = 0;
1284 
1285 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1286 	thread_rpc(rpc_args);
1287 }
1288 
1289 /**
1290  * Allocates shared memory buffer via RPC
1291  *
1292  * @size:	size in bytes of shared memory buffer
1293  * @align:	required alignment of buffer
1294  * @bt:		buffer type OPTEE_MSG_RPC_SHM_TYPE_*
1295  * @payload:	returned physical pointer to buffer, 0 if allocation
1296  *		failed.
1297  * @cookie:	returned cookie used when freeing the buffer
1298  */
1299 static void thread_rpc_alloc(size_t size, size_t align, unsigned int bt,
1300 			paddr_t *payload, uint64_t *cookie)
1301 {
1302 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1303 	struct thread_ctx *thr = threads + thread_get_id();
1304 	struct optee_msg_arg *arg = thr->rpc_arg;
1305 	uint64_t carg = thr->rpc_carg;
1306 	struct optee_msg_param *params = OPTEE_MSG_GET_PARAMS(arg);
1307 
1308 	memset(arg, 0, OPTEE_MSG_GET_ARG_SIZE(1));
1309 	arg->cmd = OPTEE_MSG_RPC_CMD_SHM_ALLOC;
1310 	arg->ret = TEE_ERROR_GENERIC; /* in case value isn't updated */
1311 	arg->num_params = 1;
1312 
1313 	params[0].attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
1314 	params[0].u.value.a = bt;
1315 	params[0].u.value.b = size;
1316 	params[0].u.value.c = align;
1317 
1318 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1319 	thread_rpc(rpc_args);
1320 	if (arg->ret != TEE_SUCCESS)
1321 		goto fail;
1322 
1323 	if (arg->num_params != 1)
1324 		goto fail;
1325 
1326 	if (params[0].attr != OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT)
1327 		goto fail;
1328 
1329 	if (!check_alloced_shm(params[0].u.tmem.buf_ptr, size, align)) {
1330 		thread_rpc_free(bt, params[0].u.tmem.shm_ref);
1331 		goto fail;
1332 	}
1333 
1334 	*payload = params[0].u.tmem.buf_ptr;
1335 	*cookie = params[0].u.tmem.shm_ref;
1336 	return;
1337 fail:
1338 	*payload = 0;
1339 	*cookie = 0;
1340 }
1341 
1342 void thread_rpc_alloc_payload(size_t size, paddr_t *payload, uint64_t *cookie)
1343 {
1344 	thread_rpc_alloc(size, 8, OPTEE_MSG_RPC_SHM_TYPE_APPL, payload, cookie);
1345 }
1346 
1347 void thread_rpc_free_payload(uint64_t cookie)
1348 {
1349 	thread_rpc_free(OPTEE_MSG_RPC_SHM_TYPE_APPL, cookie);
1350 }
1351