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