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