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