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