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