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