xref: /optee_os/core/arch/arm/kernel/thread.c (revision bce4951c2b0143aadc21c1cb592eaf0fc1a87d75)
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 {
663 	vaddr_t sp = thr->regs.svc_sp;
664 	vaddr_t base = thr->stack_va_end - STACK_THREAD_SIZE;
665 	size_t len = sp - base;
666 
667 	tee_pager_release_phys((void *)base, len);
668 }
669 #else
670 static void release_unused_kernel_stack(struct thread_ctx *thr __unused)
671 {
672 }
673 #endif
674 
675 int thread_state_suspend(uint32_t flags, uint32_t cpsr, vaddr_t pc)
676 {
677 	struct thread_core_local *l = thread_get_core_local();
678 	int ct = l->curr_thread;
679 
680 	assert(ct != -1);
681 
682 	thread_check_canaries();
683 
684 	release_unused_kernel_stack(threads + ct);
685 
686 	if (is_from_user(cpsr)) {
687 		thread_user_save_vfp();
688 		tee_ta_update_session_utime_suspend();
689 		tee_ta_gprof_sample_pc(pc);
690 	}
691 	thread_lazy_restore_ns_vfp();
692 
693 	lock_global();
694 
695 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
696 	threads[ct].flags |= flags;
697 	threads[ct].regs.cpsr = cpsr;
698 	threads[ct].regs.pc = pc;
699 	threads[ct].state = THREAD_STATE_SUSPENDED;
700 
701 	threads[ct].have_user_map = core_mmu_user_mapping_is_active();
702 	if (threads[ct].have_user_map) {
703 		core_mmu_get_user_map(&threads[ct].user_map);
704 		core_mmu_set_user_map(NULL);
705 	}
706 
707 	l->curr_thread = -1;
708 
709 	unlock_global();
710 
711 	return ct;
712 }
713 
714 #ifdef ARM32
715 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
716 {
717 	l->tmp_stack_va_end = sp;
718 	thread_set_irq_sp(sp);
719 	thread_set_fiq_sp(sp);
720 }
721 
722 static void set_abt_stack(struct thread_core_local *l __unused, vaddr_t sp)
723 {
724 	thread_set_abt_sp(sp);
725 }
726 #endif /*ARM32*/
727 
728 #ifdef ARM64
729 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
730 {
731 	/*
732 	 * We're already using the tmp stack when this function is called
733 	 * so there's no need to assign it to any stack pointer. However,
734 	 * we'll need to restore it at different times so store it here.
735 	 */
736 	l->tmp_stack_va_end = sp;
737 }
738 
739 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
740 {
741 	l->abt_stack_va_end = sp;
742 }
743 #endif /*ARM64*/
744 
745 bool thread_init_stack(uint32_t thread_id, vaddr_t sp)
746 {
747 	if (thread_id >= CFG_NUM_THREADS)
748 		return false;
749 	threads[thread_id].stack_va_end = sp;
750 	return true;
751 }
752 
753 int thread_get_id_may_fail(void)
754 {
755 	/*
756 	 * thread_get_core_local() requires foreign interrupts to be disabled
757 	 */
758 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
759 	struct thread_core_local *l = thread_get_core_local();
760 	int ct = l->curr_thread;
761 
762 	thread_unmask_exceptions(exceptions);
763 	return ct;
764 }
765 
766 int thread_get_id(void)
767 {
768 	int ct = thread_get_id_may_fail();
769 
770 	assert(ct >= 0 && ct < CFG_NUM_THREADS);
771 	return ct;
772 }
773 
774 static void init_handlers(const struct thread_handlers *handlers)
775 {
776 	thread_std_smc_handler_ptr = handlers->std_smc;
777 	thread_fast_smc_handler_ptr = handlers->fast_smc;
778 	thread_nintr_handler_ptr = handlers->nintr;
779 	thread_cpu_on_handler_ptr = handlers->cpu_on;
780 	thread_cpu_off_handler_ptr = handlers->cpu_off;
781 	thread_cpu_suspend_handler_ptr = handlers->cpu_suspend;
782 	thread_cpu_resume_handler_ptr = handlers->cpu_resume;
783 	thread_system_off_handler_ptr = handlers->system_off;
784 	thread_system_reset_handler_ptr = handlers->system_reset;
785 }
786 
787 #ifdef CFG_WITH_PAGER
788 static void init_thread_stacks(void)
789 {
790 	size_t n;
791 
792 	/*
793 	 * Allocate virtual memory for thread stacks.
794 	 */
795 	for (n = 0; n < CFG_NUM_THREADS; n++) {
796 		tee_mm_entry_t *mm;
797 		vaddr_t sp;
798 
799 		/* Find vmem for thread stack and its protection gap */
800 		mm = tee_mm_alloc(&tee_mm_vcore,
801 				  SMALL_PAGE_SIZE + STACK_THREAD_SIZE);
802 		assert(mm);
803 
804 		/* Claim eventual physical page */
805 		tee_pager_add_pages(tee_mm_get_smem(mm), tee_mm_get_size(mm),
806 				    true);
807 
808 		/* Add the area to the pager */
809 		tee_pager_add_core_area(tee_mm_get_smem(mm) + SMALL_PAGE_SIZE,
810 					tee_mm_get_bytes(mm) - SMALL_PAGE_SIZE,
811 					TEE_MATTR_PRW | TEE_MATTR_LOCKED,
812 					NULL, NULL);
813 
814 		/* init effective stack */
815 		sp = tee_mm_get_smem(mm) + tee_mm_get_bytes(mm);
816 		if (!thread_init_stack(n, sp))
817 			panic("init stack failed");
818 	}
819 }
820 #else
821 static void init_thread_stacks(void)
822 {
823 	size_t n;
824 
825 	/* Assign the thread stacks */
826 	for (n = 0; n < CFG_NUM_THREADS; n++) {
827 		if (!thread_init_stack(n, GET_STACK(stack_thread[n])))
828 			panic("thread_init_stack failed");
829 	}
830 }
831 #endif /*CFG_WITH_PAGER*/
832 
833 void thread_init_primary(const struct thread_handlers *handlers)
834 {
835 	init_handlers(handlers);
836 
837 	/* Initialize canaries around the stacks */
838 	init_canaries();
839 
840 	init_thread_stacks();
841 	pgt_init();
842 }
843 
844 static void init_sec_mon(size_t pos __maybe_unused)
845 {
846 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
847 	/* Initialize secure monitor */
848 	sm_init(GET_STACK(stack_tmp[pos]));
849 #endif
850 }
851 
852 void thread_init_per_cpu(void)
853 {
854 	size_t pos = get_core_pos();
855 	struct thread_core_local *l = thread_get_core_local();
856 
857 	init_sec_mon(pos);
858 
859 	set_tmp_stack(l, GET_STACK(stack_tmp[pos]) - STACK_TMP_OFFS);
860 	set_abt_stack(l, GET_STACK(stack_abt[pos]));
861 
862 	thread_init_vbar();
863 }
864 
865 struct thread_specific_data *thread_get_tsd(void)
866 {
867 	return &threads[thread_get_id()].tsd;
868 }
869 
870 struct thread_ctx_regs *thread_get_ctx_regs(void)
871 {
872 	struct thread_core_local *l = thread_get_core_local();
873 
874 	assert(l->curr_thread != -1);
875 	return &threads[l->curr_thread].regs;
876 }
877 
878 void thread_set_foreign_intr(bool enable)
879 {
880 	/* thread_get_core_local() requires foreign interrupts to be disabled */
881 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
882 	struct thread_core_local *l;
883 
884 	l = thread_get_core_local();
885 
886 	assert(l->curr_thread != -1);
887 
888 	if (enable) {
889 		threads[l->curr_thread].flags |=
890 					THREAD_FLAGS_FOREIGN_INTR_ENABLE;
891 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
892 	} else {
893 		/*
894 		 * No need to disable foreign interrupts here since they're
895 		 * already disabled above.
896 		 */
897 		threads[l->curr_thread].flags &=
898 					~THREAD_FLAGS_FOREIGN_INTR_ENABLE;
899 	}
900 }
901 
902 void thread_restore_foreign_intr(void)
903 {
904 	/* thread_get_core_local() requires foreign interrupts to be disabled */
905 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
906 	struct thread_core_local *l;
907 
908 	l = thread_get_core_local();
909 
910 	assert(l->curr_thread != -1);
911 
912 	if (threads[l->curr_thread].flags & THREAD_FLAGS_FOREIGN_INTR_ENABLE)
913 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
914 }
915 
916 #ifdef CFG_WITH_VFP
917 uint32_t thread_kernel_enable_vfp(void)
918 {
919 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
920 	struct thread_ctx *thr = threads + thread_get_id();
921 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
922 
923 	assert(!vfp_is_enabled());
924 
925 	if (!thr->vfp_state.ns_saved) {
926 		vfp_lazy_save_state_final(&thr->vfp_state.ns);
927 		thr->vfp_state.ns_saved = true;
928 	} else if (thr->vfp_state.sec_lazy_saved &&
929 		   !thr->vfp_state.sec_saved) {
930 		/*
931 		 * This happens when we're handling an abort while the
932 		 * thread was using the VFP state.
933 		 */
934 		vfp_lazy_save_state_final(&thr->vfp_state.sec);
935 		thr->vfp_state.sec_saved = true;
936 	} else if (tuv && tuv->lazy_saved && !tuv->saved) {
937 		/*
938 		 * This can happen either during syscall or abort
939 		 * processing (while processing a syscall).
940 		 */
941 		vfp_lazy_save_state_final(&tuv->vfp);
942 		tuv->saved = true;
943 	}
944 
945 	vfp_enable();
946 	return exceptions;
947 }
948 
949 void thread_kernel_disable_vfp(uint32_t state)
950 {
951 	uint32_t exceptions;
952 
953 	assert(vfp_is_enabled());
954 
955 	vfp_disable();
956 	exceptions = thread_get_exceptions();
957 	assert(exceptions & THREAD_EXCP_FOREIGN_INTR);
958 	exceptions &= ~THREAD_EXCP_FOREIGN_INTR;
959 	exceptions |= state & THREAD_EXCP_FOREIGN_INTR;
960 	thread_set_exceptions(exceptions);
961 }
962 
963 void thread_kernel_save_vfp(void)
964 {
965 	struct thread_ctx *thr = threads + thread_get_id();
966 
967 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
968 	if (vfp_is_enabled()) {
969 		vfp_lazy_save_state_init(&thr->vfp_state.sec);
970 		thr->vfp_state.sec_lazy_saved = true;
971 	}
972 }
973 
974 void thread_kernel_restore_vfp(void)
975 {
976 	struct thread_ctx *thr = threads + thread_get_id();
977 
978 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
979 	assert(!vfp_is_enabled());
980 	if (thr->vfp_state.sec_lazy_saved) {
981 		vfp_lazy_restore_state(&thr->vfp_state.sec,
982 				       thr->vfp_state.sec_saved);
983 		thr->vfp_state.sec_saved = false;
984 		thr->vfp_state.sec_lazy_saved = false;
985 	}
986 }
987 
988 void thread_user_enable_vfp(struct thread_user_vfp_state *uvfp)
989 {
990 	struct thread_ctx *thr = threads + thread_get_id();
991 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
992 
993 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
994 	assert(!vfp_is_enabled());
995 
996 	if (!thr->vfp_state.ns_saved) {
997 		vfp_lazy_save_state_final(&thr->vfp_state.ns);
998 		thr->vfp_state.ns_saved = true;
999 	} else if (tuv && uvfp != tuv) {
1000 		if (tuv->lazy_saved && !tuv->saved) {
1001 			vfp_lazy_save_state_final(&tuv->vfp);
1002 			tuv->saved = true;
1003 		}
1004 	}
1005 
1006 	if (uvfp->lazy_saved)
1007 		vfp_lazy_restore_state(&uvfp->vfp, uvfp->saved);
1008 	uvfp->lazy_saved = false;
1009 	uvfp->saved = false;
1010 
1011 	thr->vfp_state.uvfp = uvfp;
1012 	vfp_enable();
1013 }
1014 
1015 void thread_user_save_vfp(void)
1016 {
1017 	struct thread_ctx *thr = threads + thread_get_id();
1018 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1019 
1020 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1021 	if (!vfp_is_enabled())
1022 		return;
1023 
1024 	assert(tuv && !tuv->lazy_saved && !tuv->saved);
1025 	vfp_lazy_save_state_init(&tuv->vfp);
1026 	tuv->lazy_saved = true;
1027 }
1028 
1029 void thread_user_clear_vfp(struct thread_user_vfp_state *uvfp)
1030 {
1031 	struct thread_ctx *thr = threads + thread_get_id();
1032 
1033 	if (uvfp == thr->vfp_state.uvfp)
1034 		thr->vfp_state.uvfp = NULL;
1035 	uvfp->lazy_saved = false;
1036 	uvfp->saved = false;
1037 }
1038 #endif /*CFG_WITH_VFP*/
1039 
1040 #ifdef ARM32
1041 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1042 {
1043 	uint32_t s;
1044 
1045 	if (!is_32bit)
1046 		return false;
1047 
1048 	s = read_spsr();
1049 	s &= ~(CPSR_MODE_MASK | CPSR_T | CPSR_IT_MASK1 | CPSR_IT_MASK2);
1050 	s |= CPSR_MODE_USR;
1051 	if (entry_func & 1)
1052 		s |= CPSR_T;
1053 	*spsr = s;
1054 	return true;
1055 }
1056 #endif
1057 
1058 #ifdef ARM64
1059 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1060 {
1061 	uint32_t s;
1062 
1063 	if (is_32bit) {
1064 		s = read_daif() & (SPSR_32_AIF_MASK << SPSR_32_AIF_SHIFT);
1065 		s |= SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT;
1066 		s |= (entry_func & SPSR_32_T_MASK) << SPSR_32_T_SHIFT;
1067 	} else {
1068 		s = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
1069 	}
1070 
1071 	*spsr = s;
1072 	return true;
1073 }
1074 #endif
1075 
1076 uint32_t thread_enter_user_mode(unsigned long a0, unsigned long a1,
1077 		unsigned long a2, unsigned long a3, unsigned long user_sp,
1078 		unsigned long entry_func, bool is_32bit,
1079 		uint32_t *exit_status0, uint32_t *exit_status1)
1080 {
1081 	uint32_t spsr;
1082 
1083 	tee_ta_update_session_utime_resume();
1084 
1085 	if (!get_spsr(is_32bit, entry_func, &spsr)) {
1086 		*exit_status0 = 1; /* panic */
1087 		*exit_status1 = 0xbadbadba;
1088 		return 0;
1089 	}
1090 	return __thread_enter_user_mode(a0, a1, a2, a3, user_sp, entry_func,
1091 					spsr, exit_status0, exit_status1);
1092 }
1093 
1094 void thread_add_mutex(struct mutex *m)
1095 {
1096 	struct thread_core_local *l = thread_get_core_local();
1097 	int ct = l->curr_thread;
1098 
1099 	assert(ct != -1 && threads[ct].state == THREAD_STATE_ACTIVE);
1100 	assert(m->owner_id == MUTEX_OWNER_ID_NONE);
1101 	m->owner_id = ct;
1102 	TAILQ_INSERT_TAIL(&threads[ct].mutexes, m, link);
1103 }
1104 
1105 void thread_rem_mutex(struct mutex *m)
1106 {
1107 	struct thread_core_local *l = thread_get_core_local();
1108 	int ct = l->curr_thread;
1109 
1110 	assert(ct != -1 && threads[ct].state == THREAD_STATE_ACTIVE);
1111 	assert(m->owner_id == ct);
1112 	m->owner_id = MUTEX_OWNER_ID_NONE;
1113 	TAILQ_REMOVE(&threads[ct].mutexes, m, link);
1114 }
1115 
1116 bool thread_disable_prealloc_rpc_cache(uint64_t *cookie)
1117 {
1118 	bool rv;
1119 	size_t n;
1120 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1121 
1122 	lock_global();
1123 
1124 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1125 		if (threads[n].state != THREAD_STATE_FREE) {
1126 			rv = false;
1127 			goto out;
1128 		}
1129 	}
1130 
1131 	rv = true;
1132 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1133 		if (threads[n].rpc_arg) {
1134 			*cookie = threads[n].rpc_carg;
1135 			threads[n].rpc_carg = 0;
1136 			threads[n].rpc_arg = NULL;
1137 			goto out;
1138 		}
1139 	}
1140 
1141 	*cookie = 0;
1142 	thread_prealloc_rpc_cache = false;
1143 out:
1144 	unlock_global();
1145 	thread_unmask_exceptions(exceptions);
1146 	return rv;
1147 }
1148 
1149 bool thread_enable_prealloc_rpc_cache(void)
1150 {
1151 	bool rv;
1152 	size_t n;
1153 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1154 
1155 	lock_global();
1156 
1157 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1158 		if (threads[n].state != THREAD_STATE_FREE) {
1159 			rv = false;
1160 			goto out;
1161 		}
1162 	}
1163 
1164 	rv = true;
1165 	thread_prealloc_rpc_cache = true;
1166 out:
1167 	unlock_global();
1168 	thread_unmask_exceptions(exceptions);
1169 	return rv;
1170 }
1171 
1172 static bool check_alloced_shm(paddr_t pa, size_t len, size_t align)
1173 {
1174 	if (pa & (align - 1))
1175 		return false;
1176 	return core_pbuf_is(CORE_MEM_NSEC_SHM, pa, len);
1177 }
1178 
1179 void thread_rpc_free_arg(uint64_t cookie)
1180 {
1181 	if (cookie) {
1182 		uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
1183 			OPTEE_SMC_RETURN_RPC_FREE
1184 		};
1185 
1186 		reg_pair_from_64(cookie, rpc_args + 1, rpc_args + 2);
1187 		thread_rpc(rpc_args);
1188 	}
1189 }
1190 
1191 void thread_rpc_alloc_arg(size_t size, paddr_t *arg, uint64_t *cookie)
1192 {
1193 	paddr_t pa;
1194 	uint64_t co;
1195 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
1196 		OPTEE_SMC_RETURN_RPC_ALLOC, size
1197 	};
1198 
1199 	thread_rpc(rpc_args);
1200 
1201 	pa = reg_pair_to_64(rpc_args[1], rpc_args[2]);
1202 	co = reg_pair_to_64(rpc_args[4], rpc_args[5]);
1203 	if (!check_alloced_shm(pa, size, sizeof(uint64_t))) {
1204 		thread_rpc_free_arg(co);
1205 		pa = 0;
1206 		co = 0;
1207 	}
1208 
1209 	*arg = pa;
1210 	*cookie = co;
1211 }
1212 
1213 static bool get_rpc_arg(uint32_t cmd, size_t num_params,
1214 			struct optee_msg_arg **arg_ret, uint64_t *carg_ret)
1215 {
1216 	struct thread_ctx *thr = threads + thread_get_id();
1217 	struct optee_msg_arg *arg = thr->rpc_arg;
1218 	size_t sz = OPTEE_MSG_GET_ARG_SIZE(THREAD_RPC_MAX_NUM_PARAMS);
1219 	paddr_t p;
1220 	uint64_t c;
1221 
1222 	if (num_params > THREAD_RPC_MAX_NUM_PARAMS)
1223 		return false;
1224 
1225 	if (!arg) {
1226 		thread_rpc_alloc_arg(sz, &p, &c);
1227 		if (!p)
1228 			return false;
1229 		if (!ALIGNMENT_IS_OK(p, struct optee_msg_arg))
1230 			goto bad;
1231 		arg = phys_to_virt(p, MEM_AREA_NSEC_SHM);
1232 		if (!arg)
1233 			goto bad;
1234 
1235 		thr->rpc_arg = arg;
1236 		thr->rpc_carg = c;
1237 	}
1238 
1239 	memset(arg, 0, OPTEE_MSG_GET_ARG_SIZE(num_params));
1240 	arg->cmd = cmd;
1241 	arg->num_params = num_params;
1242 	arg->ret = TEE_ERROR_GENERIC; /* in case value isn't updated */
1243 
1244 	*arg_ret = arg;
1245 	*carg_ret = thr->rpc_carg;
1246 	return true;
1247 
1248 bad:
1249 	thread_rpc_free_arg(c);
1250 	return false;
1251 }
1252 
1253 uint32_t thread_rpc_cmd(uint32_t cmd, size_t num_params,
1254 			struct optee_msg_param *params)
1255 {
1256 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1257 	struct optee_msg_arg *arg;
1258 	uint64_t carg;
1259 	size_t n;
1260 
1261 	/*
1262 	 * Break recursion in case plat_prng_add_jitter_entropy_norpc()
1263 	 * sleeps on a mutex or unlocks a mutex with a sleeper (contended
1264 	 * mutex).
1265 	 */
1266 	if (cmd != OPTEE_MSG_RPC_CMD_WAIT_QUEUE)
1267 		plat_prng_add_jitter_entropy_norpc();
1268 
1269 	if (!get_rpc_arg(cmd, num_params, &arg, &carg))
1270 		return TEE_ERROR_OUT_OF_MEMORY;
1271 
1272 	memcpy(arg->params, params, sizeof(*params) * num_params);
1273 
1274 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1275 	thread_rpc(rpc_args);
1276 	for (n = 0; n < num_params; n++) {
1277 		switch (params[n].attr & OPTEE_MSG_ATTR_TYPE_MASK) {
1278 		case OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT:
1279 		case OPTEE_MSG_ATTR_TYPE_VALUE_INOUT:
1280 		case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:
1281 		case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:
1282 		case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:
1283 		case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:
1284 			params[n] = arg->params[n];
1285 			break;
1286 		default:
1287 			break;
1288 		}
1289 	}
1290 	return arg->ret;
1291 }
1292 
1293 /**
1294  * Free physical memory previously allocated with thread_rpc_alloc()
1295  *
1296  * @cookie:	cookie received when allocating the buffer
1297  * @bt:		must be the same as supplied when allocating
1298  */
1299 static void thread_rpc_free(unsigned int bt, uint64_t cookie)
1300 {
1301 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1302 	struct optee_msg_arg *arg;
1303 	uint64_t carg;
1304 
1305 	if (!get_rpc_arg(OPTEE_MSG_RPC_CMD_SHM_FREE, 1, &arg, &carg))
1306 		return;
1307 
1308 	arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
1309 	arg->params[0].u.value.a = bt;
1310 	arg->params[0].u.value.b = cookie;
1311 	arg->params[0].u.value.c = 0;
1312 
1313 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1314 	thread_rpc(rpc_args);
1315 }
1316 
1317 /**
1318  * Allocates shared memory buffer via RPC
1319  *
1320  * @size:	size in bytes of shared memory buffer
1321  * @align:	required alignment of buffer
1322  * @bt:		buffer type OPTEE_MSG_RPC_SHM_TYPE_*
1323  * @payload:	returned physical pointer to buffer, 0 if allocation
1324  *		failed.
1325  * @cookie:	returned cookie used when freeing the buffer
1326  */
1327 static void thread_rpc_alloc(size_t size, size_t align, unsigned int bt,
1328 			paddr_t *payload, uint64_t *cookie)
1329 {
1330 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1331 	struct optee_msg_arg *arg;
1332 	uint64_t carg;
1333 
1334 	if (!get_rpc_arg(OPTEE_MSG_RPC_CMD_SHM_ALLOC, 1, &arg, &carg))
1335 		goto fail;
1336 
1337 	arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
1338 	arg->params[0].u.value.a = bt;
1339 	arg->params[0].u.value.b = size;
1340 	arg->params[0].u.value.c = align;
1341 
1342 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1343 	thread_rpc(rpc_args);
1344 	if (arg->ret != TEE_SUCCESS)
1345 		goto fail;
1346 
1347 	if (arg->num_params != 1)
1348 		goto fail;
1349 
1350 	if (arg->params[0].attr != OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT)
1351 		goto fail;
1352 
1353 	if (!check_alloced_shm(arg->params[0].u.tmem.buf_ptr, size, align)) {
1354 		thread_rpc_free(bt, arg->params[0].u.tmem.shm_ref);
1355 		goto fail;
1356 	}
1357 
1358 	*payload = arg->params[0].u.tmem.buf_ptr;
1359 	*cookie = arg->params[0].u.tmem.shm_ref;
1360 	return;
1361 fail:
1362 	*payload = 0;
1363 	*cookie = 0;
1364 }
1365 
1366 void thread_rpc_alloc_payload(size_t size, paddr_t *payload, uint64_t *cookie)
1367 {
1368 	thread_rpc_alloc(size, 8, OPTEE_MSG_RPC_SHM_TYPE_APPL, payload, cookie);
1369 }
1370 
1371 void thread_rpc_free_payload(uint64_t cookie)
1372 {
1373 	thread_rpc_free(OPTEE_MSG_RPC_SHM_TYPE_APPL, cookie);
1374 }
1375